snice 7.0.0 → 7.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/adapters/react/SniceProvider.js +1 -1
  2. package/adapters/react/SniceRouter.js +1 -1
  3. package/adapters/react/matchRoute.js +1 -1
  4. package/adapters/react/useRequestHandler.js +1 -1
  5. package/bin/snice.js +3 -1
  6. package/bin/templates/default/package.json +1 -1
  7. package/bin/templates/gitignore +27 -0
  8. package/bin/templates/react/package.json +1 -1
  9. package/dist/cdn/accordion/snice-accordion.js +1 -1
  10. package/dist/cdn/action-bar/snice-action-bar.js +1 -1
  11. package/dist/cdn/activity-feed/snice-activity-feed.js +1 -1
  12. package/dist/cdn/alert/snice-alert.js +1 -1
  13. package/dist/cdn/app-tiles/snice-app-tiles.js +1 -1
  14. package/dist/cdn/approval-flow/snice-approval-flow.js +1 -1
  15. package/dist/cdn/audio-recorder/snice-audio-recorder.js +1 -1
  16. package/dist/cdn/availability/snice-availability.js +1 -1
  17. package/dist/cdn/avatar/snice-avatar.js +1 -1
  18. package/dist/cdn/avatar-group/snice-avatar-group.js +1 -1
  19. package/dist/cdn/badge/snice-badge.js +1 -1
  20. package/dist/cdn/banner/snice-banner.js +1 -1
  21. package/dist/cdn/binpack/snice-binpack.js +1 -1
  22. package/dist/cdn/book/snice-book.js +1 -1
  23. package/dist/cdn/booking/snice-booking.js +1 -1
  24. package/dist/cdn/breadcrumbs/snice-breadcrumbs.js +1 -1
  25. package/dist/cdn/button/snice-button.js +1 -1
  26. package/dist/cdn/calendar/snice-calendar.js +1 -1
  27. package/dist/cdn/camera/snice-camera.js +1 -1
  28. package/dist/cdn/camera-annotate/snice-camera-annotate.js +1 -1
  29. package/dist/cdn/candlestick/snice-candlestick.js +1 -1
  30. package/dist/cdn/card/snice-card.js +1 -1
  31. package/dist/cdn/carousel/snice-carousel.js +1 -1
  32. package/dist/cdn/cart/snice-cart.js +1 -1
  33. package/dist/cdn/chart/snice-chart.js +1 -1
  34. package/dist/cdn/chat/snice-chat.js +1 -1
  35. package/dist/cdn/checkbox/snice-checkbox.js +1 -1
  36. package/dist/cdn/chip/snice-chip.js +1 -1
  37. package/dist/cdn/code-block/snice-code-block.js +1 -1
  38. package/dist/cdn/color-display/snice-color-display.js +1 -1
  39. package/dist/cdn/color-picker/snice-color-picker.js +1 -1
  40. package/dist/cdn/command-palette/snice-command-palette.js +1 -1
  41. package/dist/cdn/comments/snice-comments.js +1 -1
  42. package/dist/cdn/countdown/snice-countdown.js +1 -1
  43. package/dist/cdn/cropper/snice-cropper.js +1 -1
  44. package/dist/cdn/data-card/snice-data-card.js +1 -1
  45. package/dist/cdn/date-picker/snice-date-picker.js +1 -1
  46. package/dist/cdn/date-range-picker/snice-date-range-picker.js +1 -1
  47. package/dist/cdn/date-time-picker/snice-date-time-picker.js +1 -1
  48. package/dist/cdn/diff/snice-diff.js +1 -1
  49. package/dist/cdn/divider/snice-divider.js +1 -1
  50. package/dist/cdn/doc/snice-doc.js +1 -1
  51. package/dist/cdn/draw/snice-draw.js +1 -1
  52. package/dist/cdn/drawer/snice-drawer.js +1 -1
  53. package/dist/cdn/empty-state/snice-empty-state.js +1 -1
  54. package/dist/cdn/estimate/snice-estimate.js +1 -1
  55. package/dist/cdn/file-gallery/snice-file-gallery.js +1 -1
  56. package/dist/cdn/file-upload/snice-file-upload.js +1 -1
  57. package/dist/cdn/flip-card/snice-flip-card.js +1 -1
  58. package/dist/cdn/flow/snice-flow.js +1 -1
  59. package/dist/cdn/form-layout/snice-form-layout.js +1 -1
  60. package/dist/cdn/funnel/snice-funnel.js +1 -1
  61. package/dist/cdn/gantt/snice-gantt.js +1 -1
  62. package/dist/cdn/gauge/snice-gauge.js +1 -1
  63. package/dist/cdn/grid/snice-grid.js +1 -1
  64. package/dist/cdn/heatmap/snice-heatmap.js +1 -1
  65. package/dist/cdn/image/snice-image.js +1 -1
  66. package/dist/cdn/input/snice-input.js +1 -1
  67. package/dist/cdn/invoice/snice-invoice.js +1 -1
  68. package/dist/cdn/kanban/snice-kanban.js +1 -1
  69. package/dist/cdn/key-value/snice-key-value.js +1 -1
  70. package/dist/cdn/kpi/snice-kpi.js +1 -1
  71. package/dist/cdn/layout/snice-layout.js +1 -1
  72. package/dist/cdn/leaderboard/snice-leaderboard.js +1 -1
  73. package/dist/cdn/link/snice-link.js +1 -1
  74. package/dist/cdn/link-preview/snice-link-preview.js +1 -1
  75. package/dist/cdn/list/snice-list.js +1 -1
  76. package/dist/cdn/location/snice-location.js +1 -1
  77. package/dist/cdn/login/snice-login.js +1 -1
  78. package/dist/cdn/map/snice-map.js +1 -1
  79. package/dist/cdn/markdown/snice-markdown.js +1 -1
  80. package/dist/cdn/masonry/snice-masonry.js +1 -1
  81. package/dist/cdn/menu/snice-menu.js +1 -1
  82. package/dist/cdn/message-strip/snice-message-strip.js +1 -1
  83. package/dist/cdn/modal/snice-modal.js +1 -1
  84. package/dist/cdn/music-player/snice-music-player.js +1 -1
  85. package/dist/cdn/nav/snice-nav.js +1 -1
  86. package/dist/cdn/network-graph/snice-network-graph.js +1 -1
  87. package/dist/cdn/notification-center/snice-notification-center.js +1 -1
  88. package/dist/cdn/order-tracker/snice-order-tracker.js +1 -1
  89. package/dist/cdn/org-chart/snice-org-chart.js +1 -1
  90. package/dist/cdn/pagination/snice-pagination.js +1 -1
  91. package/dist/cdn/paint/snice-paint.js +1 -1
  92. package/dist/cdn/pdf-viewer/snice-pdf-viewer.js +1 -1
  93. package/dist/cdn/permission-matrix/snice-permission-matrix.js +1 -1
  94. package/dist/cdn/podcast-player/snice-podcast-player.js +1 -1
  95. package/dist/cdn/popover/snice-popover.js +1 -1
  96. package/dist/cdn/pricing-table/snice-pricing-table.js +1 -1
  97. package/dist/cdn/product-card/snice-product-card.js +1 -1
  98. package/dist/cdn/progress/snice-progress.js +1 -1
  99. package/dist/cdn/progress-ring/snice-progress-ring.js +1 -1
  100. package/dist/cdn/qr-code/snice-qr-code.js +1 -1
  101. package/dist/cdn/qr-reader/snice-qr-reader.js +1 -1
  102. package/dist/cdn/radio/snice-radio.js +1 -1
  103. package/dist/cdn/range-slider/snice-range-slider.js +1 -1
  104. package/dist/cdn/rating/snice-rating.js +1 -1
  105. package/dist/cdn/receipt/snice-receipt.js +1 -1
  106. package/dist/cdn/recipe/snice-recipe.js +1 -1
  107. package/dist/cdn/runtime/snice-runtime.esm.js +4 -4
  108. package/dist/cdn/runtime/snice-runtime.esm.js.map +1 -1
  109. package/dist/cdn/runtime/snice-runtime.esm.min.js.map +1 -1
  110. package/dist/cdn/runtime/snice-runtime.js +4 -4
  111. package/dist/cdn/runtime/snice-runtime.js.map +1 -1
  112. package/dist/cdn/runtime/snice-runtime.min.js.map +1 -1
  113. package/dist/cdn/sankey/snice-sankey.js +1 -1
  114. package/dist/cdn/segmented-control/snice-segmented-control.js +1 -1
  115. package/dist/cdn/select/snice-select.js +1 -1
  116. package/dist/cdn/skeleton/snice-skeleton.js +1 -1
  117. package/dist/cdn/slider/snice-slider.js +1 -1
  118. package/dist/cdn/sortable/snice-sortable.js +1 -1
  119. package/dist/cdn/sparkline/snice-sparkline.js +1 -1
  120. package/dist/cdn/spinner/snice-spinner.js +1 -1
  121. package/dist/cdn/split-button/snice-split-button.js +1 -1
  122. package/dist/cdn/split-pane/snice-split-pane.js +1 -1
  123. package/dist/cdn/spotlight/snice-spotlight.js +1 -1
  124. package/dist/cdn/stat-group/snice-stat-group.js +1 -1
  125. package/dist/cdn/step-input/snice-step-input.js +1 -1
  126. package/dist/cdn/stepper/snice-stepper.js +1 -1
  127. package/dist/cdn/switch/snice-switch.js +1 -1
  128. package/dist/cdn/table/snice-table.esm.js +1 -1
  129. package/dist/cdn/table/snice-table.js +1 -1
  130. package/dist/cdn/tabs/snice-tabs.js +1 -1
  131. package/dist/cdn/tag/snice-tag.js +1 -1
  132. package/dist/cdn/tag-input/snice-tag-input.js +1 -1
  133. package/dist/cdn/terminal/snice-terminal.js +1 -1
  134. package/dist/cdn/testimonial/snice-testimonial.js +1 -1
  135. package/dist/cdn/textarea/snice-textarea.js +1 -1
  136. package/dist/cdn/time-picker/snice-time-picker.js +1 -1
  137. package/dist/cdn/time-range-picker/snice-time-range-picker.js +1 -1
  138. package/dist/cdn/timeline/snice-timeline.js +1 -1
  139. package/dist/cdn/timer/snice-timer.js +1 -1
  140. package/dist/cdn/toast/snice-toast.js +1 -1
  141. package/dist/cdn/tooltip/snice-tooltip.js +1 -1
  142. package/dist/cdn/tree/snice-tree.js +1 -1
  143. package/dist/cdn/treemap/snice-treemap.js +1 -1
  144. package/dist/cdn/user-card/snice-user-card.js +1 -1
  145. package/dist/cdn/video-player/snice-video-player.js +1 -1
  146. package/dist/cdn/virtual-scroller/snice-virtual-scroller.js +1 -1
  147. package/dist/cdn/waterfall/snice-waterfall.js +1 -1
  148. package/dist/cdn/weather/snice-weather.js +1 -1
  149. package/dist/cdn/work-order/snice-work-order.js +1 -1
  150. package/dist/index.cjs +1 -1
  151. package/dist/index.esm.js +1 -1
  152. package/dist/index.iife.js +1 -1
  153. package/dist/react/SniceProvider.js +1 -1
  154. package/dist/react/SniceRouter.js +1 -1
  155. package/dist/react/index.js +1 -1
  156. package/dist/react/matchRoute.js +1 -1
  157. package/dist/react/useRequestHandler.js +1 -1
  158. package/dist/symbols.cjs +1 -1
  159. package/dist/symbols.esm.js +1 -1
  160. package/dist/transitions.cjs +1 -1
  161. package/dist/transitions.esm.js +1 -1
  162. package/docs/ai/components/chat.md +4 -0
  163. package/docs/ai/components/doc.md +1 -0
  164. package/docs/ai/components/drawer.md +2 -0
  165. package/docs/ai/components/estimate.md +15 -0
  166. package/docs/ai/components/layout.md +7 -0
  167. package/docs/ai/components/modal.md +4 -0
  168. package/docs/ai/components/product-card.md +4 -0
  169. package/docs/ai/components/receipt.md +34 -0
  170. package/docs/ai/components/select.md +4 -0
  171. package/docs/ai/components/tabs.md +5 -0
  172. package/docs/ai/components/terminal.md +17 -0
  173. package/docs/ai/components/tooltip.md +5 -0
  174. package/docs/components/chat.md +7 -38
  175. package/docs/components/doc.md +1 -0
  176. package/docs/components/drawer.md +2 -0
  177. package/docs/components/estimate.md +15 -0
  178. package/docs/components/layout.md +9 -0
  179. package/docs/components/modal.md +6 -0
  180. package/docs/components/notification-center.md +0 -3
  181. package/docs/components/product-card.md +6 -0
  182. package/docs/components/receipt.md +31 -0
  183. package/docs/components/select.md +6 -0
  184. package/docs/components/tabs.md +7 -0
  185. package/docs/components/terminal.md +17 -0
  186. package/docs/components/tooltip.md +7 -0
  187. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"snice-runtime.min.js","sources":["../../index.esm.js","../../transitions.esm.js","../../symbols.esm.js"],"sourcesContent":["/*!\n * snice v6.1.0\n * A decorator-driven web component library with differential rendering, routing, controllers, and 130+ ready-made UI components. Use as much or as little as you want. Zero dependencies, works anywhere.\n * (c) 2024\n * Released under the MIT License.\n *\n * GENERATED FILE — DO NOT EDIT. Source: src/. Rebuild: npm run build:core\n */\n// Global namespace for Snice framework\n// Ensures all registries and symbols are shared across different JS files/modules\n// Initialize the global Snice namespace on globalThis\n// This ensures all module instances share the same registry\nif (!globalThis.snice) {\n globalThis.snice = {\n controllerRegistry: new Map(),\n pendingControllerAttachments: new Map(),\n controllerIdCounter: 0\n };\n}\n// Multiple copies of Snice can share a global created by an older build.\nglobalThis.snice.pendingControllerAttachments ??= new Map();\n// Export direct reference to globalThis.snice\nconst snice = globalThis.snice;\n// Helper function to get or create a global symbol\n// Symbol.for() already guarantees global uniqueness, no need for a Map cache\nfunction getSymbol(name) {\n return Symbol.for(`snice:${name}`);\n}\n\n// Central file for all symbols used in the framework\n// All symbols are stored globally to ensure consistency across modules\nconst IS_CONTROLLER_CLASS = getSymbol('is-controller-class');\nconst IS_CONTROLLER_INSTANCE = getSymbol('is-controller-instance');\nconst IS_ELEMENT_CLASS = getSymbol('is-element-class');\nconst CHANNEL_HANDLERS = getSymbol('channel-handlers');\n// Internal element state symbols\nconst READY_PROMISE = getSymbol('ready-promise');\nconst READY_RESOLVE = getSymbol('ready-resolve');\nconst RENDERED_PROMISE = getSymbol('rendered-promise');\nconst RENDERED_RESOLVE = getSymbol('rendered-resolve');\n// Set when a render is requested but dropped because the element was\n// disconnected; consumed on reconnect to replay exactly the missed render.\nconst PENDING_RECONNECT_RENDER = getSymbol('pending-reconnect-render');\n// Per-element synchronous render-nesting depth, used to cap runaway re-entry\n// without a shared global counter that one element could exhaust for others.\nconst RENDER_DEPTH = getSymbol('render-depth');\nconst RENDER_ROOT = getSymbol('render-root');\nconst ELEMENT_OPTIONS = getSymbol('element-options');\nconst CONTROLLER = getSymbol('controller');\nconst INITIALIZED = getSymbol('initialized');\n// Controller symbols\nconst CONTROLLER_KEY = getSymbol('controller-key');\nconst CONTROLLER_NAME_KEY = getSymbol('controller-name');\nconst CONTROLLER_ID = getSymbol('controller-id');\nconst CONTROLLER_OPERATIONS = getSymbol('controller-operations');\nconst NATIVE_CONTROLLER = getSymbol('native-controller');\n// Set while a controller CLASS (not a registry name) is attached — the\n// attribute/MutationObserver channel must not attach over or detach it.\nconst DIRECT_CONTROLLER = getSymbol('direct-controller');\n// A controller class bound by a template before the custom element was\n// defined/upgraded. Picked up by connectedCallback on first initialization.\nconst PENDING_CONTROLLER_BINDING = getSymbol('pending-controller-binding');\n// Cleanup symbol - holds an object with all cleanup arrays\nconst CLEANUP = getSymbol('cleanup');\n// Property symbols\nconst PROPERTIES = getSymbol('properties');\nconst PROPERTY_VALUES = getSymbol('property-values');\nconst PROPERTY_DEFAULTS = getSymbol('property-defaults');\nconst PROPERTY_WRAPPERS = getSymbol('property-wrappers');\nconst PRE_INIT_PROPERTY_VALUES = getSymbol('pre-init-property-values');\nconst PRE_UPGRADE_PROPERTY_BINDINGS = getSymbol('pre-upgrade-property-bindings');\nconst PROPERTIES_INITIALIZED = getSymbol('properties-initialized');\nconst PROPERTY_WATCHERS = getSymbol('property-watchers');\nconst EXPLICITLY_SET_PROPERTIES = getSymbol('explicitly-set-properties');\n// Router context symbol\nconst ROUTER_CONTEXT = getSymbol('router-context');\nconst PAGE_TRANSITION = getSymbol('page-transition');\nconst CREATED_AT = getSymbol('created-at');\n// Lifecycle symbols\nconst READY_HANDLERS = getSymbol('ready-handlers');\nconst DISPOSE_HANDLERS = getSymbol('dispose-handlers');\nconst RECONNECT_HANDLERS = getSymbol('reconnect-handlers');\nconst MOVED_HANDLERS = getSymbol('moved-handlers');\nconst ADOPTED_HANDLERS = getSymbol('adopted-handlers');\n// Observer symbols\nconst OBSERVERS = getSymbol('observers');\n// Property setter flag (prevents attributeChangedCallback re-triggering watchers)\nconst SETTING_FROM_PROPERTY = getSymbol('setting-from-property');\n// Lifecycle callback timers\nconst MOVED_TIMERS = getSymbol('moved-timers');\nconst ADOPTED_TIMERS = getSymbol('adopted-timers');\n// Dispatch timing symbols\nconst DISPATCH_TIMERS = getSymbol('dispatch-timers');\n// Render symbols (v3.0.0)\nconst RENDER_METHOD = getSymbol('render-method');\nconst RENDER_OPTIONS = getSymbol('render-options');\nconst RENDER_INSTANCE = getSymbol('render-instance');\nconst RENDER_TIMERS = getSymbol('render-timers');\nconst RENDER_CALLBACKS = getSymbol('render-callbacks');\nconst STYLES_METHOD = getSymbol('styles-method');\nconst STYLES_APPLIED = getSymbol('styles-applied');\nconst PARENT_STYLES_METHODS = getSymbol('parent-styles-methods');\nconst SNICE_ELEMENT_BASE = getSymbol('snice-element-base');\n// Navigation context symbols\nconst CONTEXT_HANDLER = getSymbol('context-handler');\nconst NAVIGATION_CONTEXT_INSTANCE = getSymbol('navigation-context-instance');\nconst REGISTERED_ELEMENTS = getSymbol('registered-elements');\nconst IS_UPDATING = getSymbol('is-updating');\nconst CONTEXT_REGISTER = getSymbol('context-register');\nconst CONTEXT_UNREGISTER = getSymbol('context-unregister');\nconst CONTEXT_NOTIFY_ELEMENT = getSymbol('context-notify-element');\nconst CONTEXT_TIMER = getSymbol('context-timer');\nconst CONTEXT_CALLED = getSymbol('context-called');\nconst CONTEXT_UPDATE = getSymbol('context-update');\n// Registration de-dup sets on the constructor — replace previous `__*Methods`\n// expando strings that violated the no-double-underscore rule.\nconst CONTEXT_METHODS = getSymbol('context-methods');\nconst WATCH_METHODS = getSymbol('watch-methods');\nconst OBSERVE_METHODS = getSymbol('observe-methods');\nconst ON_METHODS = getSymbol('on-methods');\nconst RESPOND_METHODS = getSymbol('respond-methods');\nconst READY_METHODS = getSymbol('ready-methods');\nconst DISPOSE_METHODS = getSymbol('dispose-methods');\nconst RECONNECT_METHODS = getSymbol('reconnect-methods');\nconst MOVED_METHODS = getSymbol('moved-methods');\nconst ADOPTED_METHODS = getSymbol('adopted-methods');\n// Controller attach-abort — set to an AbortController while attachController\n// is awaiting element.ready, so detachController can short-circuit the wait.\nconst CONTROLLER_ABORT = getSymbol('controller-abort');\n// Set on a controller instance once it has gotten past element.ready and is\n// being attached, so detachController knows not to run detach() on a controller\n// whose attach() was aborted before it ever ran.\nconst CONTROLLER_ATTACHED = getSymbol('controller-attached');\nconst PROPERTY_DEFINERS = getSymbol('property-definers');\n\n/**\n * SimpleArray type for arrays that can be safely reflected to attributes\n * Supports arrays of: string, number, boolean\n * Uses full-width comma (,) as separator to avoid conflicts\n * Strings cannot contain the full-width comma character\n */\nclass SimpleArray {\n static { this.SEPARATOR = ','; } // U+FF0C Full-width comma\n /**\n * Serialize array to string for attribute storage\n */\n static serialize(arr) {\n if (!Array.isArray(arr))\n return '';\n return arr.map(item => {\n if (typeof item === 'string') {\n // Validate string doesn't contain our separator\n if (item.includes(SimpleArray.SEPARATOR)) {\n throw new Error(`SimpleArray strings cannot contain the character \"${SimpleArray.SEPARATOR}\" (U+FF0C)`);\n }\n return item;\n }\n else if (typeof item === 'number' || typeof item === 'boolean') {\n return String(item);\n }\n else {\n throw new Error(`SimpleArray only supports string, number, and boolean types. Got: ${typeof item}`);\n }\n }).join(SimpleArray.SEPARATOR);\n }\n /**\n * Parse string from attribute back to array\n */\n static parse(str) {\n if (str === null || str === undefined)\n return [];\n // Empty string should not be parsed as containing an empty string\n // since empty arrays don't get reflected (handled by the reflection logic)\n if (str === '')\n return [];\n return str.split(SimpleArray.SEPARATOR).map(item => {\n // Try to parse as number\n if (/^-?\\d+\\.?\\d*$/.test(item)) {\n const num = Number(item);\n if (!isNaN(num))\n return num;\n }\n // Parse as boolean\n if (item === 'true')\n return true;\n if (item === 'false')\n return false;\n // Default to string\n return item;\n });\n }\n}\n\n/**\n * Generic transition system for animating between elements\n */\nvar TransitionMode;\n(function (TransitionMode) {\n /** out transition completes before in transition starts */\n TransitionMode[\"SEQUENTIAL\"] = \"sequential\";\n /** both transitions happen at the same time */\n TransitionMode[\"SIMULTANEOUS\"] = \"simultaneous\";\n})(TransitionMode || (TransitionMode = {}));\n\nvar _a, _b, _c;\n// Symbol for storing the Set of elements\n// Use Symbol.for() to ensure symbols are shared across multiple Snice instances\nconst REGISTERED_ELEMENTS_SET = Symbol.for('snice:registered-elements-set');\n// Counter for generating unique context IDs\nlet contextIdCounter = 0;\n/**\n * Represents the bundled router state that can notify registered elements of changes\n */\nclass Context {\n constructor(context = {}, placards = [], currentRoute = '', routeParams = {}, fetcher) {\n // Stores the SET of wrapped-method names per element so that classes with\n // multiple @context() handlers register every method, not just the last one.\n this[_a] = new WeakMap();\n this[_b] = new Set();\n this[_c] = false;\n this.id = contextIdCounter++;\n this.application = context;\n this.navigation = {\n placards,\n route: currentRoute,\n params: routeParams\n };\n // Initialize fetch with middleware support or fallback to native fetch\n if (fetcher && typeof fetcher.create === 'function') {\n this.fetch = fetcher.create(this);\n }\n else if (typeof fetch === 'function') {\n this.fetch = fetch.bind(this);\n }\n else {\n throw new Error('No fetch implementation available');\n }\n }\n /**\n * Register an element to receive context updates\n * @internal Used by @context decorator\n */\n [(_a = REGISTERED_ELEMENTS, _b = REGISTERED_ELEMENTS_SET, _c = IS_UPDATING, CONTEXT_REGISTER)](element, methodName) {\n const map = this[REGISTERED_ELEMENTS];\n let names = map.get(element);\n if (!names) {\n names = new Set();\n map.set(element, names);\n }\n names.add(methodName);\n this[REGISTERED_ELEMENTS_SET].add(element);\n }\n /**\n * Unregister an element from receiving context updates. With a methodName,\n * removes only that one handler (so a `once` handler tearing itself down\n * doesn't kill the element's other @context handlers); without one, removes\n * the element entirely (used on disconnect).\n * @internal Used by @context decorator cleanup\n */\n [CONTEXT_UNREGISTER](element, methodName) {\n const map = this[REGISTERED_ELEMENTS];\n if (methodName !== undefined) {\n const names = map.get(element);\n if (!names)\n return;\n names.delete(methodName);\n if (names.size > 0)\n return; // other handlers remain — keep the element\n }\n map.delete(element);\n this[REGISTERED_ELEMENTS_SET].delete(element);\n }\n /**\n * Update the context and notify all registered elements\n * Prevents infinite loops by tracking update state\n * @internal Used by Router during navigation\n */\n [CONTEXT_UPDATE](context, placards, currentRoute, routeParams) {\n this.application = context;\n this.navigation.placards = placards;\n this.navigation.route = currentRoute;\n this.navigation.params = routeParams;\n this.notify();\n }\n /**\n * Signal all @context() subscribers to re-read context\n * Does not modify any state — just notifies listeners with current values\n */\n update() {\n this.notify();\n }\n notify() {\n // Prevent infinite loops\n if (this[IS_UPDATING]) {\n return;\n }\n this[IS_UPDATING] = true;\n // Notify all registered elements by calling EVERY registered method\n // name on each. Classes with multiple @context() methods get all fired.\n const elementsSet = this[REGISTERED_ELEMENTS_SET];\n const elementsMap = this[REGISTERED_ELEMENTS];\n for (const element of elementsSet) {\n const names = elementsMap.get(element);\n if (!names)\n continue;\n for (const methodName of names) {\n if (typeof element[methodName] === 'function') {\n try {\n element[methodName](this);\n }\n catch (error) {\n console.error(`Error calling @context method ${methodName}:`, error);\n }\n }\n }\n }\n this[IS_UPDATING] = false;\n }\n /**\n * Notify a specific element of the current context state\n * @internal Used by @context decorator\n */\n [CONTEXT_NOTIFY_ELEMENT](element) {\n const names = this[REGISTERED_ELEMENTS].get(element);\n if (!names)\n return;\n for (const methodName of names) {\n if (typeof element[methodName] === 'function') {\n element[methodName](this);\n }\n }\n }\n}\n\n/**\n * Detects the type constructor from an initial value\n * @param initialValue - The default value assigned to a property field (e.g., `name = \"default\"` -> \"default\")\n * @returns The constructor function (String, Number, Boolean, etc.) or undefined if type can't be determined\n */\nfunction detectType(initialValue) {\n if (initialValue === null || initialValue === undefined) {\n return undefined;\n }\n if (typeof initialValue === 'string') {\n return String;\n }\n if (typeof initialValue === 'number') {\n return Number;\n }\n if (typeof initialValue === 'boolean') {\n return Boolean;\n }\n if (initialValue instanceof Date) {\n return Date;\n }\n if (typeof initialValue === 'bigint') {\n return BigInt;\n }\n if (Array.isArray(initialValue)) {\n return Array;\n }\n return undefined;\n}\n/**\n * Parses an attribute value based on the property type\n * @param attributeValue - The raw string value from the HTML attribute (e.g., \"123\", \"true\", \"hello\")\n * @param propertyOptions - The options from @property decorator (contains explicit type, attribute name, etc.)\n * @param currentValue - The current stored value of the property (used for type inference when no explicit type)\n * @param initialValue - The default value assigned to the property field (used for type detection as fallback)\n * @returns The parsed value in the correct JavaScript type\n */\nfunction parseAttributeValue(attributeValue, propertyOptions, currentValue, initialValue) {\n // Use explicit type or detect from initial value\n const typeToUse = propertyOptions.type || detectType(initialValue);\n if (propertyOptions.converter?.fromAttribute) {\n return propertyOptions.converter.fromAttribute(attributeValue, typeToUse);\n }\n switch (typeToUse) {\n case Boolean:\n // Boolean semantics per user specification:\n // - No attribute = false\n // - String \"false\" = false\n // - String \"true\" = true\n // - Empty string = true (attribute exists like <element bool-attr>)\n // - Any other value = true\n if (attributeValue === null)\n return false; // No attribute\n if (attributeValue === 'false')\n return false; // String \"false\"\n // All other cases (including empty string) = true (attribute exists)\n return true;\n case Number:\n return attributeValue !== null ? Number(attributeValue) : null;\n case String:\n return attributeValue;\n case Date:\n return attributeValue ? new Date(attributeValue) : null;\n case BigInt:\n if (attributeValue && attributeValue.endsWith('n')) {\n return BigInt(attributeValue.slice(0, -1));\n }\n else {\n return attributeValue ? BigInt(attributeValue) : null;\n }\n case SimpleArray:\n return SimpleArray.parse(attributeValue);\n case Array:\n try {\n return attributeValue ? JSON.parse(attributeValue) : [];\n }\n catch {\n return [];\n }\n case Object:\n try {\n return attributeValue ? JSON.parse(attributeValue) : {};\n }\n catch {\n return {};\n }\n default:\n // If no type specified and can't detect, try to infer from current value type\n if (typeof currentValue === 'number' && attributeValue !== null) {\n return Number(attributeValue);\n }\n else {\n return attributeValue;\n }\n }\n}\n/**\n * Converts a property value to its attribute string representation\n * @param value - The property value to convert\n * @param propertyOptions - The options from @property decorator\n * @param initialValue - The default value assigned to the property field (used for type detection)\n * @returns The string representation for the HTML attribute, or null if value should remove attribute\n */\n/**\n * Default property dirty-check: has the value changed? Like `!==`, but treats\n * NaN → NaN as unchanged (NaN !== NaN would otherwise re-fire forever).\n */\nfunction notEqual(value, old) {\n // Changed unless strictly equal, or both are NaN (each self-unequal).\n return value !== old && (value === value || old === old);\n}\n/**\n * Extract attribute name from property options\n */\nfunction getAttrName(opts, propName) {\n // Lowercase always: the DOM stores attribute names lowercase, so an explicit\n // camelCase `attribute:` would otherwise never match observedAttributes and\n // attributeChangedCallback would never fire. get/setAttribute are already\n // case-insensitive, so this is safe for every caller.\n if (typeof opts.attribute === 'string')\n return opts.attribute.toLowerCase();\n if (opts.attribute === true || opts.attributeNaming === 'kebab') {\n return propName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n }\n return propName.toLowerCase();\n}\n/**\n * Escape HTML text-node content. Use for text that will be interpolated\n * into an HTML string (not an attribute value).\n */\nfunction escapeHtml(value) {\n return String(value ?? '')\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\n}\n/**\n * Escape HTML attribute value. Use for anything interpolated inside a\n * quoted attribute (e.g. `href=\"${...}\"`). Escapes both quote styles so\n * the value cannot close the attribute or the surrounding tag.\n */\nfunction escapeAttr(value) {\n return String(value ?? '')\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n/**\n * Validate a URL's scheme against a safe-list. Relative references are\n * accepted after parsing, while absolute and network-path references must\n * resolve to an allowed protocol. Raw ASCII control characters are rejected\n * before parsing so they cannot be stripped out to disguise a scheme.\n *\n * Rejects `javascript:`, `data:`, `vbscript:`, and any scheme not in the\n * allowed set by default. Pass to `window.open`, `iframe.src`, `<a href>`,\n * etc. when the URL originates from user input.\n *\n * @example\n * if (!isSafeUrl(url)) return;\n * window.open(url, '_blank');\n */\nfunction isSafeUrl(url, opts = {}) {\n let raw;\n try {\n raw = String(url ?? '');\n }\n catch {\n return false;\n }\n if (!raw || /[\\u0000-\\u001f\\u007f]/.test(raw))\n return false;\n const s = raw.trim();\n if (!s)\n return false;\n const allowed = opts.allowed ?? ['http:', 'https:', 'mailto:', 'tel:'];\n try {\n const parsed = new URL(s, 'http://__snice-relative.invalid/');\n const hasExplicitScheme = /^[a-z][a-z\\d+.-]*:/i.test(s);\n const isNetworkPathReference = /^[\\\\/]{2}/.test(s);\n // Paths, hashes, and query-only references inherit the embedding page's\n // protocol and are safe independently of the absolute-protocol allowlist.\n if (!hasExplicitScheme && !isNetworkPathReference)\n return true;\n return allowed.some(protocol => typeof protocol === 'string'\n && protocol.toLowerCase() === parsed.protocol);\n }\n catch {\n return false;\n }\n}\n/**\n * Parse a duration string into a unit-aware Duration.\n * Recognized suffixes: `ms` (milliseconds), `s` (seconds), `m` (minutes),\n * `h` (hours). Plain numbers with no suffix are treated as milliseconds.\n * Unparseable input yields a zero-duration.\n *\n * @example\n * parseDuration('200ms').milliseconds() // 200\n * parseDuration('0.4s').milliseconds() // 400\n * parseDuration('0.4s').seconds() // 0.4\n */\nfunction parseDuration(value) {\n const v = String(value).trim();\n const num = parseFloat(v);\n let ms;\n if (isNaN(num)) {\n ms = 0;\n }\n else if (/ms$/i.test(v)) {\n ms = num;\n }\n else if (/s$/i.test(v)) {\n ms = num * 1000;\n }\n else if (/m$/i.test(v)) {\n ms = num * 60000;\n }\n else if (/h$/i.test(v)) {\n ms = num * 3600000;\n }\n else {\n ms = num;\n }\n return {\n milliseconds: () => ms,\n seconds: () => ms / 1000,\n minutes: () => ms / 60000,\n };\n}\n/**\n * Lazy-init a Set on a symbol key\n */\nfunction ensureSet(obj, sym) {\n if (!obj[sym])\n obj[sym] = new Set();\n return obj[sym];\n}\n/**\n * Lazy-init an object on a symbol key\n */\nfunction ensureObj(obj, sym) {\n if (!obj[sym])\n obj[sym] = {};\n return obj[sym];\n}\n/**\n * Invoke property watchers for a given property change\n */\nfunction invokeWatchers(instance, constructor, propName, oldValue, newValue) {\n const watchers = constructor[PROPERTY_WATCHERS];\n if (!watchers)\n return;\n // Look up watchers by the JS property name AND the explicit `attribute:`\n // name (if declared). Lets `@watch('show-dropdown')` match a property\n // declared as `@property({ attribute: 'show-dropdown' }) showDropdown`.\n const keys = [propName];\n const propOpts = constructor[PROPERTIES]?.get(propName);\n const attrName = propOpts && typeof propOpts.attribute === 'string' ? propOpts.attribute : null;\n if (attrName && attrName !== propName)\n keys.push(attrName);\n for (const key of keys) {\n if (watchers.has(key)) {\n for (const w of watchers.get(key)) {\n try {\n w.method.call(instance, oldValue, newValue, propName);\n }\n catch (e) {\n console.error(`Error in @watch('${key}') method ${w.methodName}:`, e);\n }\n }\n }\n }\n if (watchers.has('*')) {\n for (const w of watchers.get('*')) {\n try {\n w.method.call(instance, oldValue, newValue, propName);\n }\n catch (e) {\n console.error(`Error in @watch('*') method ${w.methodName}:`, e);\n }\n }\n }\n}\n/**\n * Fire the one-time initialization call for `@watch(..., { immediate: true })`\n * handlers. Runs once per declared property after the element is initialized,\n * passing the effective initial value with `oldValue` undefined. Non-immediate\n * watchers are untouched — they only react to later changes.\n */\nfunction invokeImmediateWatchers(instance, constructor) {\n const watchers = constructor[PROPERTY_WATCHERS];\n const properties = constructor[PROPERTIES];\n if (!watchers || !properties)\n return;\n for (const [propName, propOptions] of properties) {\n // A watcher may be registered under the JS name, the explicit `attribute:`\n // name, or the `*` wildcard; fire each immediate one exactly once, keyed to\n // this property's current value.\n const keys = [propName];\n const attrName = propOptions && typeof propOptions.attribute === 'string' ? propOptions.attribute : null;\n if (attrName && attrName !== propName)\n keys.push(attrName);\n keys.push('*');\n for (const key of keys) {\n if (!watchers.has(key))\n continue;\n for (const w of watchers.get(key)) {\n if (!w.immediate)\n continue;\n try {\n w.method.call(instance, undefined, instance[propName], propName);\n }\n catch (e) {\n console.error(`Error in @watch('${key}') method ${w.methodName}:`, e);\n }\n }\n }\n }\n}\n/**\n * Create a debounced version of a function\n */\nfunction createDebounced(fn, delay) {\n let timer = null;\n return function (...args) {\n if (timer !== null)\n clearTimeout(timer);\n timer = setTimeout(() => { fn.apply(this, args); timer = null; }, delay);\n };\n}\n/**\n * Create a throttled version of a function (leading + trailing edge)\n */\nfunction createThrottled(fn, delay) {\n let lastCall = 0;\n let timer = null;\n return function (...args) {\n const now = Date.now();\n const remaining = delay - (now - lastCall);\n if (remaining <= 0) {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n lastCall = now;\n return fn.apply(this, args);\n }\n if (!timer) {\n timer = setTimeout(() => { lastCall = Date.now(); timer = null; fn.apply(this, args); }, remaining);\n }\n };\n}\n/**\n * Resolve a scope option to a concrete EventTarget.\n *\n * - undefined → host element (default behavior)\n * - 'global' → `document`\n * - string → `host.closest(selector)` (nearest matching ancestor)\n * - EventTarget instance → that target directly\n * - resolver function → called with host as `this`, returns target or null\n *\n * Returns null when the scope cannot be resolved (e.g. selector matches no\n * ancestor, resolver returns null). Caller decides how to handle null —\n * typically warn in dev and skip listener attachment.\n */\nfunction resolveScope(host, scope) {\n if (scope === undefined || scope === null)\n return host;\n if (scope === 'global')\n return typeof document !== 'undefined' ? document : null;\n if (typeof scope === 'function') {\n try {\n return scope.call(host) || null;\n }\n catch {\n return null;\n }\n }\n if (typeof scope === 'string') {\n return host.closest?.(scope) || null;\n }\n // Direct EventTarget instance.\n if (scope && typeof scope.addEventListener === 'function') {\n return scope;\n }\n return null;\n}\nfunction valueToAttribute(value, propertyOptions, initialValue) {\n // Handle null/undefined/false values and empty arrays\n if (value === null || value === undefined || value === false ||\n (propertyOptions?.type === SimpleArray && Array.isArray(value) && value.length === 0)) {\n return null;\n }\n // Use custom converter if provided\n if (propertyOptions.converter?.toAttribute) {\n return propertyOptions.converter.toAttribute(value, propertyOptions.type);\n }\n // Use explicit type or detect from initial value\n const typeToUse = propertyOptions.type || detectType(initialValue);\n switch (typeToUse) {\n case Boolean:\n // For boolean attributes, return \"true\" when true\n // (false is already handled above - returns null to remove attribute)\n return 'true';\n case Date:\n return value instanceof Date ? value.toISOString() : String(value);\n case BigInt:\n return typeof value === 'bigint' ? value.toString() + 'n' : String(value);\n case SimpleArray:\n return Array.isArray(value) ? SimpleArray.serialize(value) : String(value);\n case Array:\n return Array.isArray(value) ? JSON.stringify(value) : String(value);\n case Object:\n return typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value);\n default:\n return String(value);\n }\n}\n/**\n * Warn (once per class) about @watch targets that match no @property —\n * such watchers can never fire, and the typo is otherwise silent.\n * Valid targets: property names, their attribute forms, and the '*' wildcard.\n */\nconst validatedWatchClasses = new WeakSet();\nfunction validateWatchedProperties(instance, constructor) {\n if (validatedWatchClasses.has(constructor))\n return;\n validatedWatchClasses.add(constructor);\n const watchers = constructor[PROPERTY_WATCHERS];\n if (!watchers || watchers.size === 0)\n return;\n const properties = constructor[PROPERTIES];\n // invokeWatchers matches exactly: the property name, or an EXPLICIT\n // `attribute:` string. A derived/lowercased attribute name is NOT watchable,\n // so it must not be treated as valid here.\n const valid = new Set(['*']);\n if (properties) {\n for (const [name, opts] of properties) {\n valid.add(name);\n if (typeof opts?.attribute === 'string')\n valid.add(opts.attribute);\n }\n }\n for (const key of watchers.keys()) {\n if (valid.has(key))\n continue;\n const tag = instance.tagName ? instance.tagName.toLowerCase() : 'element';\n const known = properties ? [...properties.keys()].join(', ') : '(none)';\n console.warn(`@watch('${key}') on <${tag}> matches no @property — it will never fire. ` +\n `Known properties: ${known}.`);\n }\n}\n\n// Global cache for MediaQueryList objects\nconst mediaQueryCache = new Map();\n/**\n * Decorator for observing external changes like viewport intersection, resize, media queries, and DOM mutations\n *\n * @param target - The observation target (e.g., 'intersection', 'resize', 'media:(min-width: 768px)', 'mutation:childList') or array of targets\n * @param selectorOrOptions - CSS selector for element to observe OR options object\n * @param options - Options object (when second parameter is a selector)\n */\nfunction observe(observeTarget, selectorOrOptions, options) {\n // Handle overloaded parameters\n let selector;\n let opts;\n if (typeof selectorOrOptions === 'string') {\n selector = selectorOrOptions;\n opts = options;\n }\n else {\n selector = undefined;\n opts = selectorOrOptions;\n }\n return function (target, context) {\n const propertyKey = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // hasOwnProperty guards so subclasses don't mutate parent state via\n // the prototype chain. Without this, instantiating a child pushes into\n // the parent's OBSERVERS array and fires child observers on fresh\n // parent instances.\n if (!Object.prototype.hasOwnProperty.call(constructor, OBSERVE_METHODS)) {\n constructor[OBSERVE_METHODS] = new Set();\n }\n if (constructor[OBSERVE_METHODS].has(target))\n return;\n constructor[OBSERVE_METHODS].add(target);\n if (!Object.prototype.hasOwnProperty.call(constructor, OBSERVERS)) {\n const inherited = constructor[OBSERVERS];\n constructor[OBSERVERS] = inherited ? [...inherited] : [];\n }\n const observeTargets = Array.isArray(observeTarget) ? observeTarget : [observeTarget];\n for (const targetString of observeTargets) {\n const [type, ...modifiers] = targetString.split(':');\n const targetStr = modifiers.join(':');\n constructor[OBSERVERS].push({\n type,\n target: targetStr,\n selector,\n methodName: propertyKey,\n method: target,\n options: opts\n });\n }\n });\n };\n}\n// Helper to setup observers for elements\nfunction setupObservers(instance, element) {\n const observers = instance.constructor[OBSERVERS];\n if (!observers || !Array.isArray(observers) || observers.length === 0) {\n return;\n }\n // Initialize cleanup object if needed\n if (!instance[CLEANUP]) {\n instance[CLEANUP] = { events: [], channels: [], observers: [] };\n }\n else if (!instance[CLEANUP].observers) {\n instance[CLEANUP].observers = [];\n }\n for (const observer of observers) {\n const method = observer.method.bind(instance);\n // Apply throttling if specified\n const callback = observer.options?.throttle\n ? createThrottled(method, observer.options.throttle)\n : method;\n switch (observer.type) {\n case 'intersection':\n setupIntersectionObserver(instance, element, observer, callback);\n break;\n case 'resize':\n setupResizeObserver(instance, element, observer, callback);\n break;\n case 'media':\n setupMediaQueryObserver(instance, element, observer, callback);\n break;\n case 'mutation':\n setupMutationObserver(instance, element, observer, callback);\n break;\n default:\n console.warn(`Unknown observer type: ${observer.type}`);\n }\n }\n}\nfunction setupIntersectionObserver(instance, element, observer, callback) {\n const options = {\n threshold: observer.options?.threshold ?? 0,\n rootMargin: observer.options?.rootMargin ?? '0px',\n root: observer.options?.root ?? null\n };\n // Wrap callback to handle return value\n const wrappedCallback = (entries) => {\n for (const entry of entries) {\n try {\n const result = callback(entry);\n if (result === false && io) {\n io.unobserve(entry.target);\n }\n }\n catch (error) {\n console.error(`Error in intersection observer ${observer.methodName}:`, error);\n }\n }\n };\n if (typeof IntersectionObserver === 'undefined') {\n console.warn('IntersectionObserver is not available in this environment');\n return;\n }\n const io = new IntersectionObserver(wrappedCallback, options);\n // Find target elements\n const targets = observer.selector\n ? Array.from(element.shadowRoot?.querySelectorAll(observer.selector) || [])\n : [element];\n // Start observing\n targets.forEach(target => io.observe(target));\n // Store cleanup\n instance[CLEANUP].observers.push(() => {\n targets.forEach(target => io.unobserve(target));\n // Only disconnect if no more targets\n if (io.takeRecords().length === 0) {\n io.disconnect();\n }\n });\n}\nfunction setupResizeObserver(instance, element, observer, callback) {\n const box = observer.options?.box || 'content-box';\n // Wrap callback with error handling\n const wrappedCallback = (entries) => {\n for (const entry of entries) {\n try {\n callback(entry);\n }\n catch (error) {\n console.error(`Error in resize observer ${observer.methodName}:`, error);\n }\n }\n };\n // Check if ResizeObserver is available\n if (typeof ResizeObserver === 'undefined') {\n console.warn('ResizeObserver is not available in this environment');\n return;\n }\n // Create ResizeObserver\n const ro = new ResizeObserver(wrappedCallback);\n // Find target elements\n const targets = observer.selector\n ? Array.from(element.shadowRoot?.querySelectorAll(observer.selector) || [])\n : [element];\n // Start observing with options\n targets.forEach(target => {\n ro.observe(target, { box });\n });\n // Store cleanup\n instance[CLEANUP].observers.push(() => {\n ro.disconnect();\n });\n}\nfunction setupMediaQueryObserver(instance, _element, observer, callback) {\n // Extract media query from target (e.g., \"media:(min-width: 768px)\" -> \"(min-width: 768px)\")\n const mediaQuery = observer.target;\n if (!mediaQuery) {\n console.warn('Media query observer requires a query string');\n return;\n }\n // Get or create MediaQueryList (cached globally)\n let mql = mediaQueryCache.get(mediaQuery);\n if (!mql) {\n try {\n mql = window.matchMedia(mediaQuery);\n mediaQueryCache.set(mediaQuery, mql);\n }\n catch (error) {\n console.error(`Invalid media query: ${mediaQuery}`, error);\n return;\n }\n }\n // Wrap callback with error handling\n const wrappedCallback = (event) => {\n try {\n callback('matches' in event ? event.matches : event.matches);\n }\n catch (error) {\n console.error(`Error in media query observer ${observer.methodName}:`, error);\n }\n };\n // Call immediately with current state\n wrappedCallback(mql);\n // Listen for changes\n const changeHandler = (e) => wrappedCallback(e);\n // Modern browsers use addEventListener\n if (mql.addEventListener) {\n mql.addEventListener('change', changeHandler);\n instance[CLEANUP].observers.push(() => {\n mql.removeEventListener('change', changeHandler);\n });\n }\n else {\n // Fallback for older browsers\n mql.addListener(changeHandler);\n instance[CLEANUP].observers.push(() => {\n mql.removeListener(changeHandler);\n });\n }\n}\nfunction setupMutationObserver(instance, element, observer, callback) {\n // Parse mutation type and attribute from target\n // e.g., \"childList\", \"attributes:class\", \"attributes:data-state\"\n const parts = observer.target.split(':');\n const mutationType = parts[0] || 'childList';\n const attributeName = parts[1];\n // Build MutationObserver options\n const options = {};\n switch (mutationType) {\n case 'childList':\n options.childList = true;\n break;\n case 'attributes':\n options.attributes = true;\n if (attributeName) {\n options.attributeFilter = [attributeName];\n }\n break;\n default: {\n // A leading . # or [ means the author put a CSS selector where the\n // mutation type goes — point at the correct two-argument form.\n if (/^[.#[]/.test(mutationType)) {\n console.warn(`@observe: \"mutation:${mutationType}\" — \"${mutationType}\" looks like a selector. ` +\n `Selectors are the second argument — did you mean ` +\n `@observe('mutation:childList', '${mutationType}')?`);\n }\n else {\n console.warn(`Unknown mutation type: ${mutationType} (expected childList or attributes)`);\n }\n return;\n }\n }\n // Apply subtree with safety limits\n if (observer.options?.subtree) {\n options.subtree = true;\n // Could implement maxDepth checking in the callback\n if (observer.options.maxDepth) {\n console.warn('maxDepth is set but requires custom implementation');\n }\n }\n // Wrap callback with error handling and optional depth filtering\n const needsDepthFilter = !!(observer.options?.maxDepth && observer.options.subtree);\n const wrappedCallback = (mutations) => {\n try {\n if (!needsDepthFilter) {\n callback(mutations);\n return;\n }\n const maxDepth = observer.options.maxDepth;\n const root = element.shadowRoot || element;\n const filtered = mutations.filter(mutation => {\n let depth = 0;\n let current = mutation.target;\n while (current && current !== root && depth < maxDepth) {\n current = current.parentNode;\n depth++;\n }\n return depth < maxDepth;\n });\n if (filtered.length > 0)\n callback(filtered);\n }\n catch (error) {\n console.error(`Error in mutation observer ${observer.methodName}:`, error);\n }\n };\n // Create MutationObserver\n const mo = new MutationObserver(wrappedCallback);\n // Find target elements\n const isController = instance[IS_CONTROLLER_INSTANCE] === true;\n // For mutation observers without selector:\n // - Controllers: observe the shadow DOM of the element they're attached to (if it exists)\n // - Elements: observe the element itself (light DOM) to avoid infinite loops\n const targets = observer.selector\n ? Array.from(element.shadowRoot?.querySelectorAll(observer.selector) || [])\n : isController && element.shadowRoot\n ? [element.shadowRoot]\n : [element];\n // Start observing\n targets.forEach(target => {\n mo.observe(target, options);\n });\n // Store cleanup\n instance[CLEANUP].observers.push(() => {\n mo.disconnect();\n });\n}\n// Helper to cleanup observers\nfunction cleanupObservers(instance) {\n if (instance[CLEANUP]?.observers) {\n for (const cleanup of instance[CLEANUP].observers) {\n cleanup();\n }\n instance[CLEANUP].observers = [];\n }\n}\n\n// @request decorator transforms methods to return Promise<T>\n/**\n * Decorator for making requests from elements or controllers.\n * Uses async generator pattern for bidirectional communication.\n *\n * @param requestName The name of the request\n * @param options Optional configuration\n */\nfunction request(requestName, options) {\n return function (originalMethod, _context) {\n // Create timing variables for debounce/throttle\n let debounceTimeout;\n let throttleLastCall = 0;\n let throttleTimeout;\n const throttleTrailingResolvers = [];\n return async function (...args) {\n const actualRequest = async () => {\n // @request always acts as requester (client side)\n const responseTimeout = options?.timeout ?? 120000; // Default 2 minute timeout\n const discoveryTimeout = options?.discoveryTimeout ?? 50; // Default 50ms discovery timeout\n // Create the generator\n const generator = originalMethod.apply(this, args);\n // Get the first yield (the request payload)\n const { value: payload, done } = await generator.next();\n if (done) {\n // Generator returned without yielding\n return payload;\n }\n // Create data promise and expose resolve/reject\n let dataResolve;\n let dataReject;\n const dataPromise = new Promise((resolve, reject) => {\n dataResolve = resolve;\n dataReject = reject;\n });\n // Create discovery timeout promise and expose resolve/reject\n let discoveryResolve;\n let discoveryReject;\n let discoveryTimeoutId;\n let discovered = false;\n const discoveryPromise = new Promise((resolve, reject) => {\n discoveryResolve = resolve;\n discoveryReject = reject;\n discoveryTimeoutId = setTimeout(() => {\n reject(new Error(`Request \"${requestName}\" found no @respond('${requestName}') handler within ${discoveryTimeout}ms — ` +\n `attach a responding controller/element, or pass { optional: true } to resolve undefined when unhandled.`));\n }, discoveryTimeout);\n });\n // Dispatch event with promises\n const eventName = `@request/${requestName}`;\n const event = new CustomEvent(eventName, {\n bubbles: options?.bubbles !== undefined ? options.bubbles : true,\n cancelable: options?.cancelable || false,\n composed: true, // Allow crossing shadow DOM boundaries\n detail: {\n payload,\n discovery: {\n resolve: () => {\n discovered = true;\n clearTimeout(discoveryTimeoutId);\n discoveryResolve();\n },\n reject: discoveryReject\n },\n data: {\n resolve: dataResolve,\n reject: dataReject\n }\n }\n });\n // Check if this is a controller instance using the symbol\n const isController = this[IS_CONTROLLER_INSTANCE] === true;\n const dispatcher = isController && this.element ? this.element : this;\n dispatcher.dispatchEvent(event);\n try {\n // Wait for discovery timeout to be cleared (handler found) or discovery timeout to reject (no handler)\n await discoveryPromise;\n // If we get here, a handler was found and discovery timeout was cleared\n // Now wait for the actual data response with the full response timeout\n const responseTimeoutId = setTimeout(() => {\n dataReject(new Error(`Request \"${requestName}\" timed out after ${responseTimeout}ms`));\n }, responseTimeout);\n const response = await dataPromise;\n clearTimeout(responseTimeoutId);\n // Send response back to generator and get final return value\n const { value: finalValue } = await generator.next(response);\n return finalValue;\n }\n catch (error) {\n // optional: an unhandled request isn't an error — resume the generator\n // with undefined so `const data = await (yield payload)` sees no data.\n // A response TIMEOUT (handler exists but is slow) still throws.\n if (options?.optional && !discovered) {\n const { value: finalValue } = await generator.next(undefined);\n return finalValue;\n }\n // Drive the generator's own catch block and return whatever it recovers\n // with (e.g. a cached fallback). If the generator re-throws instead,\n // generator.throw rejects and the error propagates to the caller.\n const { value: recovered } = await generator.throw(error);\n return recovered;\n }\n }; // Close actualRequest function\n // Debounce\n if (options?.debounce) {\n return new Promise((resolve, reject) => {\n clearTimeout(debounceTimeout);\n debounceTimeout = setTimeout(async () => {\n try {\n resolve(await actualRequest());\n }\n catch (error) {\n reject(error);\n }\n }, options.debounce);\n });\n }\n // No throttle — execute immediately\n if (!options?.throttle)\n return actualRequest();\n // Throttle: time elapsed — invoke now\n const now = Date.now();\n const remaining = options.throttle - (now - throttleLastCall);\n if (remaining <= 0) {\n // Cancelling the scheduled trailing call must not orphan the promises\n // queued for it — settle them with this fresh result. Also reset\n // throttleTimeout so later within-window calls don't attach to a dead\n // timer and hang.\n clearTimeout(throttleTimeout);\n throttleTimeout = null;\n throttleLastCall = now;\n const orphaned = throttleTrailingResolvers.splice(0);\n const p = actualRequest();\n if (orphaned.length) {\n p.then((r) => { for (const x of orphaned)\n x.resolve(r); }, (e) => { for (const x of orphaned)\n x.reject(e); });\n }\n return p;\n }\n // Throttle: already has pending trailing call — attach to it\n if (throttleTimeout) {\n return new Promise((resolve, reject) => {\n throttleTrailingResolvers.push({ resolve, reject });\n });\n }\n // Throttle: schedule trailing call\n return new Promise((resolve, reject) => {\n throttleTrailingResolvers.push({ resolve, reject });\n throttleTimeout = setTimeout(async () => {\n throttleLastCall = Date.now();\n throttleTimeout = null;\n const resolvers = throttleTrailingResolvers.splice(0);\n try {\n const result = await actualRequest();\n for (const r of resolvers)\n r.resolve(result);\n }\n catch (error) {\n for (const r of resolvers)\n r.reject(error);\n }\n }, remaining);\n });\n };\n };\n}\n/**\n * Decorator for responding to requests in elements or controllers.\n *\n * @param requestName The name of the request to respond to\n * @param options Optional configuration\n */\nfunction respond(requestName, options) {\n return function (target, context) {\n const propertyKey = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // hasOwnProperty guards so subclasses don't mutate parent state via\n // the prototype chain.\n if (!Object.prototype.hasOwnProperty.call(constructor, RESPOND_METHODS)) {\n constructor[RESPOND_METHODS] = new Set();\n }\n if (constructor[RESPOND_METHODS].has(target))\n return;\n constructor[RESPOND_METHODS].add(target);\n if (!Object.prototype.hasOwnProperty.call(constructor, CHANNEL_HANDLERS)) {\n const inherited = constructor[CHANNEL_HANDLERS];\n constructor[CHANNEL_HANDLERS] = inherited ? [...inherited] : [];\n }\n constructor[CHANNEL_HANDLERS].push({\n channelName: requestName,\n methodName: propertyKey,\n method: target,\n options: options\n });\n });\n };\n}\n// Helper to setup response handlers for elements and controllers\nfunction setupResponseHandlers(instance, element) {\n const handlers = instance.constructor[CHANNEL_HANDLERS];\n if (!handlers)\n return;\n // Store cleanup functions\n // Initialize cleanup object if needed\n if (!instance[CLEANUP]) {\n instance[CLEANUP] = { events: [], channels: [] };\n }\n for (const handler of handlers) {\n const boundMethod = handler.method.bind(instance);\n const eventName = `@request/${handler.channelName}`;\n // Create timing variables for debounce/throttle per handler\n let debounceTimeout;\n let throttleLastCall = 0;\n let throttleTimeout;\n const throttleTrailingResolvers = [];\n let throttleLatestArgs = null;\n // Create wrapped method with timing if needed\n const createTimedMethod = (originalMethod) => {\n if (handler.options?.debounce) {\n return (...args) => new Promise((resolve, reject) => {\n clearTimeout(debounceTimeout);\n debounceTimeout = setTimeout(async () => {\n try {\n resolve(await originalMethod(...args));\n }\n catch (error) {\n reject(error);\n }\n }, handler.options.debounce);\n });\n }\n if (!handler.options?.throttle)\n return originalMethod;\n return (...args) => {\n const now = Date.now();\n const remaining = handler.options.throttle - (now - throttleLastCall);\n if (remaining <= 0) {\n // Same as the @request side: settle any queued trailing callers with\n // this fresh result rather than orphaning their promises.\n clearTimeout(throttleTimeout);\n throttleTimeout = null;\n throttleLastCall = now;\n const orphaned = throttleTrailingResolvers.splice(0);\n throttleLatestArgs = null;\n const result = originalMethod(...args);\n if (orphaned.length) {\n Promise.resolve(result).then((r) => { for (const x of orphaned)\n x.resolve(r); }, (e) => { for (const x of orphaned)\n x.reject(e); });\n }\n return result;\n }\n // Remember the LATEST args so the trailing call uses fresh input,\n // and queue every suppressed caller's resolver so they all receive\n // the trailing result instead of `undefined`.\n throttleLatestArgs = args;\n return new Promise((resolve, reject) => {\n throttleTrailingResolvers.push({ resolve, reject });\n if (throttleTimeout)\n return; // already scheduled\n throttleTimeout = setTimeout(async () => {\n throttleLastCall = Date.now();\n throttleTimeout = null;\n const resolvers = throttleTrailingResolvers.splice(0);\n const finalArgs = throttleLatestArgs ?? args;\n throttleLatestArgs = null;\n try {\n const result = await originalMethod(...finalArgs);\n for (const r of resolvers)\n r.resolve(result);\n }\n catch (error) {\n for (const r of resolvers)\n r.reject(error);\n }\n }, remaining);\n });\n };\n };\n const timedMethod = createTimedMethod(boundMethod);\n // Setup response handler\n const responseHandler = (event) => {\n // Extract promises and payload\n const { data, discovery, payload } = event.detail;\n // Prevent other responders from responding\n event.preventDefault();\n event.stopImmediatePropagation();\n event.stopPropagation();\n // Clear the discovery timeout immediately - we found a handler\n discovery.resolve();\n // Call the timed responder method and handle the result\n Promise.resolve(timedMethod(payload))\n .then(result => {\n data.resolve(result);\n })\n .catch(error => {\n data.reject(error);\n console.error(`Error in response handler ${handler.methodName}:`, error);\n });\n };\n element.addEventListener(eventName, responseHandler);\n instance[CLEANUP].channels.push(() => {\n element.removeEventListener(eventName, responseHandler);\n });\n }\n}\n// Helper to cleanup response handlers\nfunction cleanupResponseHandlers(instance) {\n if (instance[CLEANUP]?.channels) {\n for (const cleanup of instance[CLEANUP].channels) {\n cleanup();\n }\n instance[CLEANUP].channels = [];\n }\n}\n\n/**\n * Template system for Snice v3.0.0\n * Provides html`` and css`` tagged template processors with differential rendering\n */\n// Unique symbols for type checking\n// Use Symbol.for() to ensure symbols are shared across multiple Snice instances\nconst HTML_RESULT = Symbol.for('snice:html-result');\nconst CSS_RESULT = Symbol.for('snice:css-result');\n// Static css`` sites are the common stylesheet path and can be reused forever.\n// Interpolated sites are intentionally not retained: caching every distinct\n// primitive interpolation would turn a dynamic css`` call into an unbounded\n// per-callsite value history.\nconst cssResultCache = new WeakMap();\n/**\n * Tagged template function for creating HTML templates\n *\n * @example\n * ```typescript\n * html`<div class=\"card\">\n * <h1>${this.title}</h1>\n * <button @click=${this.handleClick}>Click me</button>\n * </div>`\n * ```\n */\nfunction html(strings, ...values) {\n return {\n _$litType$: HTML_RESULT,\n strings,\n values\n };\n}\n/**\n * Tagged template function for SVG fragments.\n *\n * Bare SVG elements (<circle>, <path>, ...) parse as unknown elements in an\n * HTML context. Use svg`` for fragments composed into a surrounding <svg>:\n *\n * @example\n * ```typescript\n * html`<svg viewBox=\"0 0 100 100\">${svg`<circle cx=\"50\" cy=\"50\" r=${r}></circle>`}</svg>`\n * ```\n */\nfunction svg(strings, ...values) {\n return {\n _$litType$: HTML_RESULT,\n strings,\n values,\n svg: true\n };\n}\n/**\n * Tagged template function for creating CSS\n *\n * @example\n * ```typescript\n * css`:host {\n * display: block;\n * padding: 1rem;\n * }`\n * ```\n */\nfunction css(strings, ...values) {\n const cached = values.length === 0 ? cssResultCache.get(strings) : undefined;\n if (cached)\n return cached;\n // Combine strings and values into final CSS text\n let cssText = strings[0];\n for (let i = 0; i < values.length; i++) {\n // Inline a nested css`` result by its text so style fragments compose;\n // String() on a CSSResult object would yield \"[object Object]\".\n const value = values[i];\n cssText += (isCSSResult(value) ? value.cssText : String(value)) + strings[i + 1];\n }\n const result = {\n _$litType$: CSS_RESULT,\n cssText\n };\n // Try to create constructable stylesheet for better performance\n // This will be cached and reused across instances. Guard against envs\n // without a Document global (for example, workers).\n if (typeof CSSStyleSheet !== 'undefined' &&\n typeof Document !== 'undefined' &&\n 'adoptedStyleSheets' in Document.prototype) {\n try {\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(cssText);\n result.styleSheet = sheet;\n }\n catch (e) {\n // Fall back to regular <style> tag if constructable stylesheets fail\n }\n }\n if (values.length === 0)\n cssResultCache.set(strings, result);\n return result;\n}\n/**\n * Check if a value is a TemplateResult\n */\nfunction isTemplateResult(value) {\n return value && value._$litType$ === HTML_RESULT;\n}\n/**\n * Check if a value is a CSSResult\n */\nfunction isCSSResult(value) {\n return value && value._$litType$ === CSS_RESULT;\n}\n/**\n * Nothing - represents no value (different from null/undefined)\n * Used to remove content from templates\n * Use Symbol.for() to ensure symbols are shared across multiple Snice instances\n */\nconst nothing = Symbol.for('snice:nothing');\n// Unique symbol for unsafe HTML\n// Use Symbol.for() to ensure symbols are shared across multiple Snice instances\nconst UNSAFE_HTML = Symbol.for('snice:unsafe-html');\n/**\n * Mark a string as raw HTML that should not be escaped\n * WARNING: Only use with sanitized content - using user input can lead to XSS!\n *\n * @example\n * ```typescript\n * const htmlString = '<span class=\"bold\">Hello</span>';\n * html`<div>${unsafeHTML(htmlString)}</div>`\n * ```\n */\nfunction unsafeHTML(html) {\n return {\n _$litType$: UNSAFE_HTML,\n html\n };\n}\n/**\n * Check if a value is an UnsafeHTML wrapper\n */\nfunction isUnsafeHTML(value) {\n return value && value._$litType$ === UNSAFE_HTML;\n}\n\nconst REPEAT_RESULT = Symbol.for('snice:repeat-result');\n/**\n * Render a keyed collection without adding wrapper elements.\n *\n * Keys are mandatory because repeat() is the explicit identity-preserving list\n * API. Duplicate keys throw before DOM reconciliation rather than silently\n * reusing the wrong row.\n */\nfunction repeat(items, options) {\n if (!options || typeof options.key !== 'function' || typeof options.render !== 'function') {\n throw new TypeError('snice: repeat() requires { key, render }.');\n }\n const array = items == null ? [] : Array.from(items);\n const keys = array.map(options.key);\n const seen = new Set();\n for (const key of keys) {\n if (seen.has(key)) {\n throw new Error(`snice: repeat() received duplicate key ${String(key)}.`);\n }\n seen.add(key);\n }\n return {\n _$repeat$: REPEAT_RESULT,\n items: array,\n keys,\n values: array.map(options.render),\n empty: array.length === 0\n ? typeof options.empty === 'function'\n ? options.empty()\n : options.empty\n : undefined\n };\n}\nfunction isRepeatResult(value) {\n return !!value && value._$repeat$ === REPEAT_RESULT;\n}\n\nconst renderHosts = new WeakSet();\nfunction getRenderRoot(element) {\n return element[RENDER_ROOT] || element.shadowRoot || null;\n}\nfunction ensureRenderRoot(element) {\n const existing = getRenderRoot(element);\n if (existing)\n return existing;\n const options = element.constructor[ELEMENT_OPTIONS];\n let root;\n if (options?.renderRoot === 'light' || options?.shadow === false) {\n root = element;\n }\n else if (typeof element.createRenderRoot === 'function') {\n root = element.createRenderRoot();\n }\n else {\n const mode = typeof options?.shadow === 'string' ? options.shadow : 'open';\n root = element.attachShadow({ mode, delegatesFocus: options?.delegatesFocus });\n }\n if (root !== element && !(root instanceof ShadowRoot)) {\n throw new TypeError('snice: createRenderRoot() must return the host element or a ShadowRoot.');\n }\n element[RENDER_ROOT] = root;\n renderHosts.add(element);\n return root;\n}\nfunction findRenderHost(node) {\n const root = node.getRootNode();\n if (root instanceof ShadowRoot)\n return root.host;\n let current = node;\n while (current) {\n if (current instanceof HTMLElement && renderHosts.has(current))\n return current;\n current = current.parentNode;\n }\n return null;\n}\n\n// Unique marker for dynamic parts\n// This parses as a comment node but doesn't get escaped in attributes\nconst marker = `snice$${Math.random().toFixed(9).slice(2)}$`;\nconst markerMatch = '?' + marker;\n// A true comment, not a processing instruction (<?...>): in HTML content both\n// parse to the same comment node, but PIs are dropped inside foreign content\n// (<svg>), which would silently kill any node binding inside an svg block.\nconst nodeMarker = `<!--${markerMatch}-->`;\n// Escape the `$` chars — as a bare RegExp they'd be end anchors and the\n// pattern would never match, so marker-bearing text/comments never split.\nconst markerRegex = new RegExp(marker.replace(/\\$/g, '\\\\$'), 'g');\n// Template cache - templates with same string array can be reused\nconst templateCache = new WeakMap();\n// Sentinel for \"not yet set\" - distinct from undefined/null\nconst NOT_COMMITTED = Symbol('not-committed');\nfunction markPreUpgradePropertyBinding(element, propertyName) {\n const tagName = element.localName;\n if (!tagName?.includes('-'))\n return;\n const registry = element.ownerDocument?.defaultView?.customElements ?? globalThis.customElements;\n if (registry?.get(tagName))\n return;\n const target = element;\n if (!target[PRE_UPGRADE_PROPERTY_BINDINGS])\n target[PRE_UPGRADE_PROPERTY_BINDINGS] = new Set();\n target[PRE_UPGRADE_PROPERTY_BINDINGS].add(propertyName);\n}\n// noChange sentinel - preserves the currently committed value\nconst noChange = Symbol.for('snice:no-change');\n// live() wrapper - marks a property binding value for comparison against the\n// actual DOM property instead of the last committed value\nconst LIVE_MARKER = Symbol.for('snice:live');\n/**\n * Wrap a property binding value so the commit compares against the element's\n * CURRENT DOM property rather than the last committed value. Use for inputs\n * whose DOM state the user can change out from under the binding:\n *\n * ```typescript\n * html`<input .value=${live(this.text)} />`\n * ```\n *\n * Without live(), re-rendering with an unchanged bound value skips the DOM\n * write, leaving user-typed text in place.\n */\nfunction live(value) {\n return { _$liveMarker$: LIVE_MARKER, value };\n}\nfunction isLive(value) {\n return value && value._$liveMarker$ === LIVE_MARKER;\n}\n/**\n * Check if value is a primitive (can be compared with ===)\n */\nconst isPrimitive = (value) => value === null || (typeof value !== 'object' && typeof value !== 'function');\n/**\n * Check if value is iterable (array or has Symbol.iterator)\n */\nconst isIterable = (value) => Array.isArray(value) || typeof value?.[Symbol.iterator] === 'function';\nconst isPromiseLike = (value) => !!value && typeof value.then === 'function';\nconst isAsyncIterable = (value) => !!value && typeof value[Symbol.asyncIterator] === 'function';\n/**\n * A prepared template ready for rendering\n */\nclass Template {\n constructor(result, element, attrNamesForParts) {\n this.parts = [];\n /**\n * Value index of a `key=${...}` binding in this template, or -1 if unkeyed.\n * Used by keyed list reconciliation in NodePart._commitIterable.\n */\n this.keyIndex = -1;\n this.element = element;\n const walker = document.createTreeWalker(element.content, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT);\n let partIndex = 0;\n const nodesToRemove = [];\n let node;\n while ((node = walker.nextNode()) !== null) {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const element = node;\n const tagName = element.tagName.toLowerCase();\n const parentTag = element.parentElement?.tagName.toLowerCase();\n if ((tagName === 'else' || tagName === 'else-if') && parentTag !== 'if') {\n throw new Error(`snice: <${tagName}> must be a direct child of <if>.`);\n }\n if ((tagName === 'when' || tagName === 'default') && parentTag !== 'case') {\n throw new Error(`snice: <${tagName}> must be a direct child of <case>.`);\n }\n // Handle virtual elements: <if>, <else-if>, <case>, <when>\n // Keep them in the DOM with display:contents for now\n // Will optimize later with proper template extraction\n if (tagName === 'if') {\n // <if value=\"${condition}\">children</if>\n const valueAttr = element.getAttribute('value');\n if (valueAttr && valueAttr.includes(marker)) {\n // Remove the value attribute\n element.removeAttribute('value');\n this.parts.push({\n type: 'conditional-if',\n index: partIndex++,\n element // Keep the <if> element\n });\n // Continue processing children normally\n }\n else {\n throw new Error('snice: <if> requires a condition expression.');\n }\n continue;\n }\n // Handle <case> element\n if (tagName === 'case') {\n // <case value=\"${value}\">children</case>\n const valueAttr = element.getAttribute('value');\n if (valueAttr && valueAttr.includes(marker)) {\n for (const child of Array.from(element.childNodes)) {\n if (child.nodeType === Node.ELEMENT_NODE) {\n const branchTag = child.tagName.toLowerCase();\n if (branchTag !== 'when' && branchTag !== 'default') {\n throw new Error('snice: <case> may contain only direct <when> and <default> branches.');\n }\n }\n else if (child.nodeType === Node.TEXT_NODE && child.textContent?.trim() ||\n child.nodeType === Node.COMMENT_NODE && child.data.includes(marker)) {\n throw new Error('snice: content inside <case> must be nested in a <when> or <default> branch.');\n }\n }\n // Remove the value attribute\n element.removeAttribute('value');\n this.parts.push({\n type: 'conditional-case',\n index: partIndex++,\n element // Keep the <case> element\n });\n // Continue processing children normally\n }\n else {\n throw new Error('snice: <case> requires a value expression.');\n }\n continue;\n }\n if (tagName === 'else-if') {\n const valueAttr = element.getAttribute('value');\n if (valueAttr && valueAttr.includes(marker)) {\n element.removeAttribute('value');\n this.parts.push({\n type: 'conditional-else-if',\n index: partIndex++,\n element\n });\n }\n else {\n throw new Error('snice: <else-if> requires a condition expression.');\n }\n continue;\n }\n if (tagName === 'when') {\n const valueAttr = element.getAttribute('value');\n if (valueAttr && valueAttr.includes(marker)) {\n element.removeAttribute('value');\n this.parts.push({\n type: 'conditional-when',\n index: partIndex++,\n element\n });\n }\n continue;\n }\n if (element.hasAttributes()) {\n const attributes = element.attributes;\n const attrsToRemove = [];\n for (let i = 0; i < attributes.length; i++) {\n const attr = attributes[i];\n const value = attr.value;\n // Check for attribute bindings\n if (value.includes(marker)) {\n attrsToRemove.push(attr);\n // Get original attribute name with preserved case\n const originalName = attrNamesForParts[partIndex] || attr.name;\n // Extract static string segments by splitting on marker\n const attrStrings = value.split(marker);\n // Number of expressions = number of markers = attrStrings.length - 1\n const expressionCount = attrStrings.length - 1;\n // Property/boolean/event bindings take a SINGLE expression — they\n // can't concatenate static text (a `.prop` is an object, not a\n // string). They consume the first expression; any static text or\n // extra expressions are ignored. But the value index must still\n // advance by the true marker count, or every later binding shifts.\n const isSingleExpressionBinding = /^@@?|^[.?]/.test(originalName) ||\n originalName.startsWith('...') ||\n originalName.startsWith('class:') ||\n originalName.startsWith('style:');\n if (isSingleExpressionBinding) {\n const hasStaticText = attrStrings.some((s) => s !== '');\n if (expressionCount > 1 || hasStaticText) {\n console.warn(`snice: binding \"${originalName}\" takes a single expression; ` +\n `static text and extra interpolations are ignored. ` +\n `Use a plain attribute for string interpolation.`);\n }\n }\n if (originalName.startsWith('...')) {\n const spreadName = originalName.slice(3).toLowerCase();\n if (!['props', 'properties', 'attrs', 'attributes', 'events'].includes(spreadName)) {\n throw new Error(`snice: unknown spread binding \"${originalName}\". ` +\n 'Use ...props, ...attrs, or ...events.');\n }\n this.parts.push({\n type: 'spread',\n index: partIndex,\n name: spreadName,\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('class:')) {\n if (!originalName.slice(6))\n throw new Error('snice: class: binding requires a class name.');\n this.parts.push({\n type: 'class',\n index: partIndex,\n name: originalName.slice(6),\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('style:')) {\n if (!originalName.slice(6))\n throw new Error('snice: style: binding requires a CSS property name.');\n this.parts.push({\n type: 'style',\n index: partIndex,\n name: originalName.slice(6),\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('@@')) {\n if (!originalName.slice(2).split('|')[0])\n throw new Error('snice: event binding requires an event name.');\n // Escaped event binding for events with @ in the name (e.g., @@snice/event -> @snice/event)\n this.parts.push({\n type: 'event',\n index: partIndex,\n name: originalName.slice(1), // Keep the @ in the event name\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('@')) {\n if (!originalName.slice(1).split('|')[0])\n throw new Error('snice: event binding requires an event name.');\n // Event binding (single value only)\n this.parts.push({\n type: 'event',\n index: partIndex,\n name: originalName.slice(1),\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('.')) {\n if (!originalName.slice(1))\n throw new Error('snice: property binding requires a property name.');\n // Property binding (single value only)\n this.parts.push({\n type: 'property',\n index: partIndex,\n name: originalName.slice(1),\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('?')) {\n if (!originalName.slice(1))\n throw new Error('snice: boolean binding requires an attribute name.');\n // Boolean attribute (single value only)\n this.parts.push({\n type: 'boolean-attribute',\n index: partIndex,\n name: originalName.slice(1),\n element\n });\n partIndex += expressionCount;\n }\n else if (attr.name === 'controller' &&\n attrStrings.length === 2 && attrStrings[0] === '' && attrStrings[1] === '') {\n // Bare controller=${...} binding: accepts a decorated\n // controller class directly, or a registry name string.\n // Interpolated forms (controller=\"a-${x}\") stay plain\n // string attributes.\n this.parts.push({\n type: 'controller',\n index: partIndex,\n element\n });\n partIndex += expressionCount;\n }\n else {\n // Regular attribute - supports multiple interpolations\n // Store static string segments for interpolation\n this.parts.push({\n type: 'attribute',\n index: partIndex,\n name: attr.name,\n element,\n attrStrings\n });\n // Increment by number of expressions consumed\n partIndex += expressionCount;\n }\n }\n }\n // Remove marker attributes\n for (const attr of attrsToRemove) {\n element.removeAttribute(attr.name);\n }\n }\n }\n else if (node.nodeType === Node.COMMENT_NODE) {\n const comment = node;\n // Check for marker match (processing instruction becomes comment)\n if (comment.data === markerMatch) {\n // Node part\n const parent = comment.parentNode;\n const endNode = document.createComment('');\n parent.insertBefore(endNode, comment.nextSibling);\n this.parts.push({\n type: 'node',\n index: partIndex++,\n startNode: comment,\n endNode\n });\n }\n else if (comment.data.includes(marker)) {\n // Binding(s) inside an authored HTML comment (<!-- ${x} -->).\n // Render values into the comment text; critically, consume the\n // right number of value indices so later parts stay aligned.\n const commentStrings = comment.data.split(markerRegex);\n this.parts.push({\n type: 'comment',\n index: partIndex,\n startNode: comment,\n attrStrings: commentStrings\n });\n partIndex += commentStrings.length - 1;\n }\n }\n else if (node.nodeType === Node.TEXT_NODE) {\n const text = node;\n const data = text.data;\n if (data.includes(marker)) {\n // Split text node at markers\n const parent = text.parentNode;\n const parts = data.split(markerRegex);\n const lastIndex = parts.length - 1;\n for (let i = 0; i < lastIndex; i++) {\n parent.insertBefore(document.createTextNode(parts[i]), text);\n const comment = document.createComment('');\n const endNode = document.createComment('');\n parent.insertBefore(comment, text);\n parent.insertBefore(endNode, text);\n this.parts.push({\n type: 'node',\n index: partIndex++,\n startNode: comment,\n endNode\n });\n }\n // Last part\n if (parts[lastIndex] !== '') {\n text.data = parts[lastIndex];\n }\n else {\n nodesToRemove.push(text);\n }\n }\n }\n }\n // Remove marker nodes\n for (const node of nodesToRemove) {\n node.parentNode?.removeChild(node);\n }\n // Record the value index of a `key=${...}` binding (first one wins) so\n // list rendering can associate DOM with keys instead of indices.\n for (const part of this.parts) {\n if (part.type === 'attribute' && part.name === 'key') {\n this.keyIndex = part.index;\n break;\n }\n }\n }\n}\n/**\n * Prepare a template for rendering\n *\n * Uses state tracking to correctly handle multi-interpolation in attributes.\n * Tracks whether we're inside a tag and inside a quoted attribute value.\n */\nfunction prepareTemplate(result) {\n // Check cache first\n const { strings } = result;\n const cached = templateCache.get(strings);\n if (cached) {\n return cached;\n }\n // Build HTML with markers and extract original attribute names\n const htmlParts = [];\n const attrNamesForParts = [];\n // State tracking for multi-interpolation support\n let inTag = false; // Inside a tag (between < and >)\n let inAttrValue = false; // Inside a quoted attribute value\n let inComment = false; // Inside an HTML comment (<!-- ... -->)\n let attrQuoteChar = ''; // The quote character (' or \")\n let currentAttrName = ''; // The current attribute name\n for (let i = 0; i < strings.length; i++) {\n const str = strings[i];\n htmlParts.push(str);\n if (i < strings.length - 1) {\n // Update state by scanning the string\n for (let j = 0; j < str.length; j++) {\n const char = str[j];\n if (inComment) {\n // Only the closing --> matters inside a comment\n if (char === '-' && str.startsWith('-->', j)) {\n inComment = false;\n j += 2;\n }\n }\n else if (!inTag) {\n // Looking for tag start (or comment start)\n if (char === '<') {\n if (str.startsWith('<!--', j)) {\n inComment = true;\n j += 3;\n }\n else if (/[A-Za-z!/?]/.test(str[j + 1] || '')) {\n inTag = true;\n }\n }\n }\n else if (!inAttrValue) {\n // Inside tag, but not in attribute value\n if (char === '>') {\n inTag = false;\n }\n else if (char === '\"' || char === \"'\") {\n inAttrValue = true;\n attrQuoteChar = char;\n }\n else if (char === '=') {\n // Extract attribute name (look backwards for it).\n // Includes `~` for the \"any-modifier\" keyboard prefix\n // (e.g. `@keydown.~enter`) so it isn't truncated to `.enter`.\n let attrStart = j - 1;\n while (attrStart >= 0 && /[\\w\\-\\.@\\?/:\\+~|]/.test(str[attrStart])) {\n attrStart--;\n }\n currentAttrName = str.substring(attrStart + 1, j).trim();\n }\n }\n else {\n // Inside quoted attribute value\n if (char === attrQuoteChar) {\n inAttrValue = false;\n attrQuoteChar = '';\n }\n }\n }\n // Now determine what kind of marker to insert based on current state\n if (inComment) {\n // Binding inside an HTML comment — insert a plain marker into the\n // comment text. The Template scanner turns it into a CommentPart so\n // the value index stays aligned (a swallowed marker would shift every\n // binding after the comment).\n attrNamesForParts.push('');\n htmlParts.push(marker);\n }\n else if (inAttrValue) {\n // We're inside a quoted attribute value - this is an attribute binding\n // For subsequent interpolations in same attribute, keep using same attr name\n attrNamesForParts.push(currentAttrName);\n htmlParts.push(marker);\n }\n else if (inTag) {\n // Inside tag but not in attr value - check for special cases\n // Check if this is start of attribute value (= at end of string)\n const trimmed = str.trimEnd();\n if (trimmed.endsWith('=')) {\n // Extract attribute name (same `~` inclusion as the in-tag branch\n // above — supports `@keydown.~enter` keyboard modifier prefix).\n let attrStart = trimmed.length - 2;\n while (attrStart >= 0 && /[\\w\\-\\.@\\?\\/:\\+~|]/.test(trimmed[attrStart])) {\n attrStart--;\n }\n currentAttrName = trimmed.substring(attrStart + 1, trimmed.length - 1).trim();\n attrNamesForParts.push(currentAttrName);\n htmlParts.push(marker);\n }\n else {\n // Check if this is a meta element (<if> or <case>)\n const metaElementMatch = str.match(/<(if|else-if|case|when)\\s*$/);\n if (metaElementMatch) {\n currentAttrName = 'value';\n attrNamesForParts.push('value');\n htmlParts.push(`value=\"${marker}\"`);\n }\n else {\n throw new Error('snice: expressions directly in opening tags are not supported; ' +\n 'use an explicit attribute, property, event, class, style, or named spread binding.');\n }\n }\n }\n else {\n // Outside any tag - this is node content\n attrNamesForParts.push('');\n htmlParts.push(nodeMarker);\n }\n }\n }\n const html = htmlParts.join('');\n const template = document.createElement('template');\n if (result.svg) {\n // Parse in the SVG namespace by wrapping, then unwrap: the parsed nodes\n // keep their namespace when moved out of the temporary <svg> element.\n template.innerHTML = `<svg>${html}</svg>`;\n const wrapper = template.content.firstElementChild;\n while (wrapper.firstChild) {\n template.content.insertBefore(wrapper.firstChild, wrapper);\n }\n template.content.removeChild(wrapper);\n }\n else {\n template.innerHTML = html;\n }\n const tmpl = new Template(result, template, attrNamesForParts);\n // Cache the template for reuse\n templateCache.set(strings, tmpl);\n return tmpl;\n}\n/**\n * Extract the key of a list item rendered from a template with a\n * `key=${...}` binding. Returns undefined for unkeyed items.\n */\nfunction getItemKey(item) {\n if (!isTemplateResult(item))\n return undefined;\n const tmpl = prepareTemplate(item);\n return tmpl.keyIndex === -1 ? undefined : item.values[tmpl.keyIndex];\n}\n/**\n * Instance of a rendered template\n */\nclass TemplateInstance {\n constructor(result) {\n this.parts = [];\n this.fragment = null;\n this.conditionalParts = []; // if/case parts with their indices\n this.regularParts = []; // all other parts with their indices\n this.template = prepareTemplate(result);\n this.strings = result.strings;\n }\n /**\n * Check if this instance uses the same template strings\n * (template identity is based on the strings array reference)\n */\n isSameTemplate(strings) {\n return this.strings === strings;\n }\n renderFragment() {\n if (!this.fragment) {\n // First render - clone template and create parts\n this.fragment = this.template.element.content.cloneNode(true);\n // Build a map of nodes from template to cloned fragment\n const walker = document.createTreeWalker(this.template.element.content, NodeFilter.SHOW_ALL);\n const clonedWalker = document.createTreeWalker(this.fragment, NodeFilter.SHOW_ALL);\n const nodeMap = new Map();\n let templateNode = walker.currentNode;\n let clonedNode = clonedWalker.currentNode;\n while (templateNode && clonedNode) {\n nodeMap.set(templateNode, clonedNode);\n templateNode = walker.nextNode();\n clonedNode = clonedWalker.nextNode();\n }\n const dynamicWhenElements = new Set();\n for (const definition of this.template.parts) {\n if (definition.type === 'conditional-when') {\n dynamicWhenElements.add(nodeMap.get(definition.element));\n }\n }\n for (let i = 0; i < this.template.parts.length; i++) {\n const partDef = this.template.parts[i];\n let part;\n switch (partDef.type) {\n case 'node':\n const startNode = nodeMap.get(partDef.startNode);\n const endNode = nodeMap.get(partDef.endNode);\n part = new NodePart(startNode, endNode);\n break;\n case 'attribute':\n const attrElement = nodeMap.get(partDef.element);\n part = new AttributePart(attrElement, partDef.name, partDef.attrStrings);\n break;\n case 'property':\n const propElement = nodeMap.get(partDef.element);\n part = new PropertyPart(propElement, partDef.name);\n break;\n case 'boolean-attribute':\n const boolElement = nodeMap.get(partDef.element);\n part = new BooleanAttributePart(boolElement, partDef.name);\n break;\n case 'event':\n const eventElement = nodeMap.get(partDef.element);\n part = new EventPart(eventElement, partDef.name);\n break;\n case 'class':\n const classElement = nodeMap.get(partDef.element);\n part = new ClassPart(classElement, partDef.name);\n break;\n case 'style':\n const styleElement = nodeMap.get(partDef.element);\n part = new StylePart(styleElement, partDef.name);\n break;\n case 'spread':\n const spreadElement = nodeMap.get(partDef.element);\n part = new SpreadPart(spreadElement, partDef.name);\n break;\n case 'controller':\n const controllerElement = nodeMap.get(partDef.element);\n part = new ControllerPart(controllerElement);\n break;\n case 'conditional-if':\n const conditionalIfElement = nodeMap.get(partDef.element);\n part = new ConditionalIfPart(conditionalIfElement);\n break;\n case 'conditional-else-if':\n const conditionalElseIfElement = nodeMap.get(partDef.element);\n part = new ConditionalElseIfPart(conditionalElseIfElement);\n break;\n case 'conditional-case':\n const conditionalCaseElement = nodeMap.get(partDef.element);\n part = new ConditionalCasePart(conditionalCaseElement, dynamicWhenElements);\n break;\n case 'conditional-when':\n const conditionalWhenElement = nodeMap.get(partDef.element);\n part = new ConditionalWhenPart(conditionalWhenElement);\n break;\n case 'comment':\n const commentNode = nodeMap.get(partDef.startNode);\n part = new CommentPart(commentNode, partDef.attrStrings);\n break;\n default:\n throw new Error(`Unknown part type: ${partDef.type}`);\n }\n this.parts.push(part);\n // Separate conditional parts from regular parts for optimized update\n // Use partDef.index (the VALUE index) not i (the part array index)\n if (part instanceof ConditionalIfPart ||\n part instanceof ConditionalElseIfPart ||\n part instanceof ConditionalCasePart ||\n part instanceof ConditionalWhenPart) {\n this.conditionalParts.push({ part, index: partDef.index });\n }\n else {\n this.regularParts.push({ part, index: partDef.index });\n }\n }\n }\n return this.fragment;\n }\n render(values) {\n const fragment = this.renderFragment();\n // Commit values to parts\n this.update(values);\n return fragment;\n }\n update(values) {\n // Optimized: Process conditional parts first (if any), then regular parts\n // Using pre-separated arrays with cached indices avoids instanceof and indexOf calls\n // Process conditional parts first (they control visibility)\n for (const { part, index } of this.conditionalParts) {\n part.commit(values[index]);\n }\n // Conditions are staged above, then flushed once. This avoids transiently\n // mounting an else/default branch while later else-if/when expressions in\n // the same update are still being committed.\n const flushed = new Set();\n for (const { part } of this.conditionalParts) {\n const coordinator = part instanceof ConditionalElseIfPart\n ? part.coordinator\n : part instanceof ConditionalWhenPart\n ? part.coordinator\n : part;\n if (flushed.has(coordinator))\n continue;\n flushed.add(coordinator);\n if (coordinator instanceof ConditionalIfPart || coordinator instanceof ConditionalCasePart) {\n coordinator.flush();\n }\n }\n for (const { part, index } of this.regularParts) {\n // AttributeParts with interpolation consume multiple values\n if (part instanceof AttributePart && part.strings !== undefined) {\n // Pass full values array and starting index for interpolation\n part.commit(values, index);\n // The part consumes (strings.length - 1) values\n // But since we're iterating by template part index, this is handled by the Template\n }\n else if (part instanceof CommentPart) {\n // CommentParts also consume (strings.length - 1) values\n part.commit(values, index);\n }\n else {\n part.commit(values[index]);\n }\n }\n // Branch switches can move event-bearing nodes between the live DOM and\n // parked fragments. Reconcile connection state after every update so\n // listeners detach while parked and reattach when their branch returns.\n let lifecycleError;\n for (const part of this.parts) {\n try {\n if (part.isConnected)\n part.reconnected();\n else\n part.disconnected();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n clear() {\n let lifecycleError;\n for (const part of this.parts) {\n try {\n part.destroy();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n disconnected(preserveEventListeners = false) {\n let lifecycleError;\n for (const part of this.parts) {\n try {\n part.disconnected(preserveEventListeners);\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n reconnected() {\n let lifecycleError;\n for (const part of this.parts) {\n try {\n part.reconnected();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n}\n/**\n * Base class for all parts\n */\nclass Part {\n get isConnected() {\n return this.element?.isConnected ?? false;\n }\n disconnected(_preserveEventListeners = false) { }\n reconnected() { }\n destroy() {\n let lifecycleError;\n try {\n this.clear();\n }\n catch (error) {\n lifecycleError = error;\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n}\n/**\n * NodePart handles text content and nested templates\n *\n * Lit-HTML style optimizations:\n * - Reuses TemplateInstance when same template strings are rendered\n * - Reuses text nodes when updating primitive → primitive\n * - Reuses child NodeParts when rendering arrays\n */\nclass NodePart extends Part {\n constructor(startNode, endNode) {\n super();\n this.type = 'node';\n this._committedValue = NOT_COMMITTED;\n this._itemKeys = null; // keys of the last committed iterable, when fully keyed\n this._asyncSource = null;\n this._asyncVersion = 0;\n this._asyncIterator = null;\n this._asyncRunning = false;\n this._asyncStarted = false;\n this._asyncCompleted = false;\n this._asyncPaused = false;\n this._committingAsyncValue = false;\n this.startNode = startNode;\n this.endNode = endNode;\n }\n commit(value) {\n // Handle noChange sentinel\n if (value === noChange) {\n return;\n }\n if (isPromiseLike(value) || isAsyncIterable(value)) {\n this._commitAsync(value);\n return;\n }\n if (!this._committingAsyncValue && this._asyncSource)\n this._cancelAsync(true);\n // Handle nothing/null/undefined/empty - clear content\n if (value === nothing || value == null || value === '') {\n if (this._committedValue !== nothing) {\n const cleanupError = this._clear();\n this._committedValue = nothing;\n if (cleanupError)\n throw cleanupError;\n }\n this._committedValue = nothing;\n return;\n }\n // Handle primitives (string, number, boolean, bigint, symbol)\n if (isPrimitive(value)) {\n if (value !== this._committedValue) {\n this._commitText(value);\n }\n return;\n }\n // Handle nested templates\n if (isTemplateResult(value)) {\n this._commitTemplateResult(value);\n return;\n }\n // Explicit keyed repeat() result. It feeds keys directly into the list\n // reconciler, so rendered roots do not need a synthetic key attribute or\n // wrapper element.\n if (isRepeatResult(value)) {\n if (value.values.length === 0) {\n this.commit(value.empty ?? nothing);\n }\n else {\n this._commitIterable(value.values, value.keys);\n }\n return;\n }\n // Handle unsafe HTML\n if (isUnsafeHTML(value)) {\n this._commitUnsafeHTML(value);\n return;\n }\n // Handle DOM nodes\n if (value.nodeType !== undefined) {\n this._commitNode(value);\n return;\n }\n // Handle iterables (arrays, etc.)\n if (isIterable(value)) {\n this._commitIterable(value);\n return;\n }\n // Fallback: convert to string\n this._commitText(value);\n }\n /**\n * Commit a primitive value as text\n * OPTIMIZATION: Reuses existing text node if previous value was also primitive\n */\n _commitText(value) {\n // Try to reuse existing text node\n const canReuse = this._committedValue !== NOT_COMMITTED &&\n this._committedValue !== nothing &&\n isPrimitive(this._committedValue) &&\n !Array.isArray(this._committedValue);\n if (canReuse) {\n const textNode = this.startNode.nextSibling;\n if (textNode && textNode.nodeType === Node.TEXT_NODE) {\n textNode.data = String(value);\n this._committedValue = value;\n return;\n }\n }\n const cleanupError = this._clear();\n this._insertBefore(document.createTextNode(String(value)));\n this._committedValue = value;\n if (cleanupError)\n throw cleanupError;\n }\n /**\n * Commit a TemplateResult\n * OPTIMIZATION: Reuses TemplateInstance if same template strings\n */\n _commitTemplateResult(result) {\n // Check if we can reuse the existing TemplateInstance\n const committedInstance = this._committedValue;\n if (committedInstance instanceof TemplateInstance) {\n // Check if same template by comparing strings reference\n const cachedTemplate = templateCache.get(result.strings);\n if (cachedTemplate && committedInstance.template === cachedTemplate) {\n // SAME TEMPLATE - just update values (efficient path!)\n committedInstance.update(result.values);\n return;\n }\n }\n // Different template or first render: prepare and validate the replacement\n // while it is detached. If a binding throws, the currently\n // committed range remains intact and its lifecycle stays connected.\n const instance = new TemplateInstance(result);\n const fragment = instance.renderFragment();\n try {\n instance.update(result.values);\n }\n catch (error) {\n instance.clear();\n throw error;\n }\n const previousValue = this._committedValue;\n const previousKeys = this._itemKeys;\n const previousFragment = this.endNode.ownerDocument.createDocumentFragment();\n let previousNode = this.startNode.nextSibling;\n while (previousNode && previousNode !== this.endNode) {\n const next = previousNode.nextSibling;\n previousFragment.appendChild(previousNode);\n previousNode = next;\n }\n this._insertBefore(fragment);\n this._committedValue = instance;\n this._itemKeys = null;\n try {\n if (this.isConnected)\n instance.reconnected();\n }\n catch (error) {\n try {\n instance.clear();\n }\n catch (cleanupError) {\n console.error('snice: failed to clean up a rejected nested template:', cleanupError);\n }\n let node = this.startNode.nextSibling;\n while (node && node !== this.endNode) {\n const next = node.nextSibling;\n node.remove();\n node = next;\n }\n this._insertBefore(previousFragment);\n this._committedValue = previousValue;\n this._itemKeys = previousKeys;\n throw error;\n }\n this._disposeCommitted(previousValue);\n }\n /**\n * Commit an iterable (array, Set, etc.)\n * OPTIMIZATION: Reuses existing NodeParts for items\n */\n _commitIterable(value, explicitKeys) {\n const items = Array.isArray(value) ? value : Array.from(value);\n const newKeys = explicitKeys ? Array.from(explicitKeys) : items.map(getItemKey);\n if (newKeys.length !== items.length) {\n throw new Error('snice: keyed iterable produced a different number of keys and values.');\n }\n const definedKeys = newKeys.filter(key => key !== undefined);\n if (definedKeys.length > 0 && definedKeys.length !== newKeys.length) {\n console.warn('snice: a list mixes keyed and unkeyed items. Identity falls back to position; ' +\n 'use repeat(items, { key, render }) for deterministic updates.');\n }\n if (definedKeys.length > 0 && new Set(definedKeys).size !== definedKeys.length) {\n throw new Error('snice: a keyed list contains duplicate keys.');\n }\n let cleanupError;\n // If previous value wasn't an array of parts, start fresh\n if (!Array.isArray(this._committedValue) ||\n !(this._committedValue[0] instanceof NodePart)) {\n cleanupError = this._clear();\n this._committedValue = [];\n this._itemKeys = null;\n }\n const allKeyed = items.length > 0 && newKeys.every(k => k !== undefined);\n const oldKeys = this._itemKeys;\n // Keyed reconciliation: when every item carries a key=${...} binding and\n // the key order changed, DOM (and its state) follows the key, not the\n // index. Unchanged key order falls through to the cheap index path.\n if (allKeyed && oldKeys && this._committedValue.length > 0) {\n const sameOrder = oldKeys.length === newKeys.length &&\n newKeys.every((k, i) => k === oldKeys[i]);\n if (!sameOrder) {\n cleanupError ??= this._reconcileKeyed(items, newKeys, this._committedValue, oldKeys);\n this._itemKeys = newKeys;\n if (cleanupError)\n throw cleanupError;\n return;\n }\n }\n const itemParts = this._committedValue;\n let partIndex = 0;\n for (const item of items) {\n let itemPart;\n if (partIndex >= itemParts.length) {\n // Need new NodePart - create with markers\n const startMarker = document.createComment('');\n const endMarker = document.createComment('');\n this._insertBefore(startMarker);\n this._insertBefore(endMarker);\n itemPart = new NodePart(startMarker, endMarker);\n itemParts.push(itemPart);\n }\n else {\n // Reuse existing NodePart\n itemPart = itemParts[partIndex];\n }\n // Set value on this part (recursively handles templates, text, etc.)\n itemPart.commit(item);\n partIndex++;\n }\n // Cleanup excess parts from previous render\n if (partIndex < itemParts.length) {\n // Clear DOM for removed items\n for (let i = partIndex; i < itemParts.length; i++) {\n const part = itemParts[i];\n // Dispose async state as well as removing the content. These item parts\n // are leaving the list permanently, not merely being moved.\n try {\n part.destroy();\n }\n catch (error) {\n cleanupError ??= error;\n }\n // Remove the markers themselves\n part.startNode.remove();\n part.endNode.remove();\n }\n // Truncate array\n itemParts.length = partIndex;\n }\n // Remember keys so the next commit can reconcile by key\n this._itemKeys = allKeyed ? newKeys : null;\n if (cleanupError)\n throw cleanupError;\n }\n /**\n * Reorder/reuse item parts so each key keeps its DOM.\n * Old parts whose keys disappeared are removed; new keys get fresh parts.\n */\n _reconcileKeyed(items, newKeys, oldParts, oldKeys) {\n const parent = this.endNode.parentNode;\n let cleanupError;\n // Map old parts by key (first occurrence wins on duplicate keys)\n const oldByKey = new Map();\n for (let i = 0; i < oldParts.length; i++) {\n if (!oldByKey.has(oldKeys[i]))\n oldByKey.set(oldKeys[i], oldParts[i]);\n }\n // Choose a part for each new item: reuse by key, or create during placement\n const reused = new Set();\n const newParts = new Array(items.length).fill(null);\n for (let i = 0; i < items.length; i++) {\n const candidate = oldByKey.get(newKeys[i]);\n if (candidate && !reused.has(candidate)) {\n reused.add(candidate);\n newParts[i] = candidate;\n }\n }\n // Remove parts whose keys are gone (before placement, so the DOM walk\n // below only ever sees surviving nodes)\n for (const part of oldParts) {\n if (!reused.has(part)) {\n try {\n part.destroy();\n }\n catch (error) {\n cleanupError ??= error;\n }\n part.startNode.remove();\n part.endNode.remove();\n }\n }\n // Place parts in order. `ref` walks the surviving DOM; a part already\n // sitting at `ref` is skipped, anything else is moved (or created) there.\n let ref = this.startNode.nextSibling;\n for (let i = 0; i < newParts.length; i++) {\n let part = newParts[i];\n if (part) {\n if (part.startNode === ref) {\n // Already in position — advance past its range\n ref = part.endNode.nextSibling;\n }\n else {\n // Move the part's whole range [startNode..endNode] before ref.\n // Detach into a fragment first, then insert in one operation —\n // node identity (and any state inside) is preserved either way.\n const range = document.createDocumentFragment();\n let node = part.startNode;\n const stop = part.endNode.nextSibling;\n while (node && node !== stop) {\n const next = node.nextSibling;\n range.appendChild(node);\n node = next;\n }\n parent.insertBefore(range, ref);\n }\n }\n else {\n // New key — fresh part inserted at the current position\n const startMarker = document.createComment('');\n const endMarker = document.createComment('');\n parent.insertBefore(startMarker, ref);\n parent.insertBefore(endMarker, ref);\n part = new NodePart(startMarker, endMarker);\n newParts[i] = part;\n }\n part.commit(items[i]);\n }\n this._committedValue = newParts;\n return cleanupError;\n }\n /**\n * Commit a DOM node directly\n */\n _commitNode(node) {\n if (this._committedValue !== node) {\n const cleanupError = this._clear();\n this._insertBefore(node);\n this._committedValue = node;\n if (cleanupError)\n throw cleanupError;\n }\n }\n /**\n * Commit unsafe HTML string\n */\n _commitUnsafeHTML(value) {\n // Can't diff arbitrary HTML, but when the STRING is unchanged the DOM is\n // already correct — skip the clear+reparse so live state (typed input\n // values, focus, scroll) inside the block survives unrelated re-renders.\n const prev = this._committedValue;\n if (isUnsafeHTML(prev) && prev.html === value.html) {\n return;\n }\n const cleanupError = this._clear();\n const temp = document.createElement('template');\n temp.innerHTML = value.html;\n this._insertBefore(temp.content);\n this._committedValue = value;\n if (cleanupError)\n throw cleanupError;\n }\n _commitAsync(source) {\n // A Promise/stream object is the identity of the async operation. Once it\n // settles, unrelated parent renders must keep the committed result rather\n // than clearing it and subscribing to the same source again.\n if (source === this._asyncSource)\n return;\n this._cancelAsync(false);\n this._asyncSource = source;\n this._asyncStarted = false;\n this._asyncCompleted = false;\n this._asyncPaused = false;\n const cleanupError = this._clear();\n this._committedValue = nothing;\n this._startAsyncSource();\n if (cleanupError)\n throw cleanupError;\n }\n _startAsyncSource(forceConnected = false) {\n const source = this._asyncSource;\n if (!source || this._asyncRunning || this._asyncCompleted ||\n (!forceConnected && !this.isConnected))\n return;\n this._asyncRunning = true;\n this._asyncStarted = true;\n this._asyncPaused = false;\n const version = ++this._asyncVersion;\n if (isAsyncIterable(source)) {\n try {\n this._asyncIterator = source[Symbol.asyncIterator]();\n }\n catch (error) {\n this._asyncRunning = false;\n this._asyncCompleted = true;\n console.error('snice: async iterable template value failed:', error);\n return;\n }\n void (async () => {\n try {\n while (this._asyncIterator) {\n const result = await this._asyncIterator.next();\n if (result.done || version !== this._asyncVersion)\n break;\n this._commitAsyncValue(result.value);\n }\n }\n catch (error) {\n if (version === this._asyncVersion)\n console.error('snice: async iterable template value failed:', error);\n }\n finally {\n if (version === this._asyncVersion) {\n this._asyncIterator = null;\n this._asyncRunning = false;\n this._asyncCompleted = true;\n }\n }\n })();\n return;\n }\n Promise.resolve(source).then(value => {\n if (version !== this._asyncVersion)\n return;\n this._asyncRunning = false;\n this._asyncCompleted = true;\n try {\n this._commitAsyncValue(value);\n }\n catch (error) {\n console.error('snice: promise template value failed:', error);\n }\n }, error => {\n if (version !== this._asyncVersion)\n return;\n this._asyncRunning = false;\n this._asyncCompleted = true;\n console.error('snice: promise template value failed:', error);\n });\n }\n _commitAsyncValue(value) {\n this._committingAsyncValue = true;\n try {\n this.commit(value);\n }\n finally {\n this._committingAsyncValue = false;\n }\n }\n _cancelAsync(clearSource) {\n this._asyncVersion++;\n const iterator = this._asyncIterator;\n this._asyncIterator = null;\n this._asyncRunning = false;\n if (clearSource) {\n this._asyncSource = null;\n this._asyncStarted = false;\n this._asyncCompleted = false;\n this._asyncPaused = false;\n }\n if (iterator?.return) {\n try {\n void Promise.resolve(iterator.return()).catch(() => { });\n }\n catch {\n // Cancellation is best-effort; internal state is already detached.\n }\n }\n }\n _insertBefore(node) {\n this.endNode.parentNode?.insertBefore(node, this.endNode);\n }\n _clear() {\n const parent = this.startNode.parentNode;\n const committed = this._committedValue;\n let cleanupError;\n try {\n this._disposeCommitted(committed);\n }\n catch (error) {\n cleanupError = error;\n }\n if (!parent) {\n this._committedValue = nothing;\n return cleanupError;\n }\n let node = this.startNode.nextSibling;\n while (node && node !== this.endNode) {\n const next = node.nextSibling;\n parent.removeChild(node);\n node = next;\n }\n this._committedValue = nothing;\n return cleanupError;\n }\n _disposeCommitted(committed) {\n let lifecycleError;\n if (committed instanceof TemplateInstance) {\n try {\n committed.clear();\n }\n catch (error) {\n lifecycleError = error;\n }\n }\n else if (Array.isArray(committed)) {\n for (const item of committed) {\n if (!(item instanceof NodePart))\n continue;\n try {\n item.destroy();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n clear() {\n this._cancelAsync(true);\n const cleanupError = this._clear();\n if (cleanupError)\n throw cleanupError;\n }\n get isConnected() {\n return this.startNode.isConnected;\n }\n disconnected(preserveEventListeners = false) {\n let lifecycleError;\n if (this._committedValue instanceof TemplateInstance) {\n try {\n this._committedValue.disconnected(preserveEventListeners);\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n else if (Array.isArray(this._committedValue)) {\n for (const part of this._committedValue) {\n if (!(part instanceof NodePart))\n continue;\n try {\n part.disconnected(preserveEventListeners);\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n }\n if (this._asyncSource && this._asyncRunning) {\n this._cancelAsync(false);\n this._asyncPaused = true;\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n reconnected() {\n let lifecycleError;\n if (this._committedValue instanceof TemplateInstance) {\n try {\n this._committedValue.reconnected();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n else if (Array.isArray(this._committedValue)) {\n for (const part of this._committedValue) {\n if (!(part instanceof NodePart))\n continue;\n try {\n part.reconnected();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n }\n if (this._asyncSource && (!this._asyncStarted || this._asyncPaused)) {\n this._startAsyncSource(true);\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n}\n/**\n * AttributePart handles regular attribute updates\n *\n * Supports multiple interpolations: class=\"a ${b} c ${d} e\"\n * Lit-HTML style: tracks each value separately for dirty checking\n */\nclass AttributePart extends Part {\n constructor(element, name, strings) {\n super();\n this.type = 'attribute';\n this._committedValue = NOT_COMMITTED;\n this.lastValues = null;\n this.lastValueIndex = 0;\n this.element = element;\n this.name = name;\n // Determine if this is interpolation or single-value binding\n if (strings && (strings.length > 2 || strings[0] !== '' || strings[1] !== '')) {\n // Interpolation case: class=\"foo ${x} bar ${y}\"\n // strings = [\"foo \", \" bar \", \"\"]\n this._committedValue = new Array(strings.length - 1).fill(NOT_COMMITTED);\n this.strings = strings;\n }\n else {\n // Single-value case: class=\"${x}\"\n this._committedValue = NOT_COMMITTED;\n }\n }\n /**\n * Commit value(s) to the attribute\n *\n * For single-value binding: commit(value)\n * For interpolation: commit(values, startIndex) where values is full template values array\n */\n commit(value, valueIndex = 0) {\n let change = false;\n let finalValue;\n // === SINGLE-VALUE BINDING ===\n if (this.strings === undefined) {\n if (value === noChange)\n return;\n change = !isPrimitive(value) ||\n (value !== this._committedValue && value !== noChange);\n if (change) {\n this._committedValue = value;\n finalValue = value;\n }\n else {\n return; // No change, skip DOM update\n }\n }\n // === INTERPOLATION BINDING ===\n else {\n const values = value;\n this.lastValues = [...values];\n this.lastValueIndex = valueIndex;\n const committedValues = this._committedValue;\n finalValue = this.strings[0];\n for (let i = 0; i < this.strings.length - 1; i++) {\n let v = values[valueIndex + i];\n // Handle noChange sentinel\n if (v === noChange) {\n v = committedValues[i];\n // First-ever commit: there is no previous value to keep — resolve\n // to empty. Without this, the NOT_COMMITTED symbol would be\n // string-concatenated below and throw.\n if (v === NOT_COMMITTED)\n v = '';\n }\n // Track if any value changed\n change = change || !isPrimitive(v) || v !== committedValues[i];\n // Handle nothing sentinel - removes entire attribute\n if (v === nothing) {\n finalValue = nothing;\n }\n else if (finalValue !== nothing) {\n finalValue = finalValue + (v ?? '') + this.strings[i + 1];\n }\n // Always record each value for future comparison\n committedValues[i] = v;\n }\n if (!change) {\n return; // No change, skip DOM update\n }\n }\n // Commit to DOM\n this._commitValue(finalValue);\n }\n _commitValue(value) {\n // Only the `nothing` sentinel removes the attribute. null/undefined\n // commit an empty attribute value, consistent with the interpolated\n // path above (which renders them as '').\n if (value === nothing) {\n this.element.removeAttribute(this.name);\n }\n else {\n this.element.setAttribute(this.name, String(value ?? ''));\n }\n }\n clear() {\n this.element.removeAttribute(this.name);\n }\n}\n/**\n * CommentPart renders binding values into an authored HTML comment's text\n * (<!-- debug: ${x} -->). Its real job is index alignment: each binding in a\n * comment consumes one value slot, so bindings after the comment stay bound\n * to their own values.\n */\nclass CommentPart extends Part {\n constructor(node, strings) {\n super();\n this.type = 'node';\n this.lastValues = null;\n this.lastValueIndex = 0;\n this.node = node;\n this.strings = strings;\n this._committedValues = new Array(strings.length - 1).fill(NOT_COMMITTED);\n }\n /**\n * Commit values into the comment text.\n * commit(values, startIndex) — like interpolated AttributePart, this part\n * consumes (strings.length - 1) values from the template values array.\n */\n commit(values, startIndex = 0) {\n const vals = values;\n this.lastValues = [...vals];\n this.lastValueIndex = startIndex;\n let change = false;\n let text = this.strings[0];\n for (let i = 0; i < this.strings.length - 1; i++) {\n let v = vals[startIndex + i];\n if (v === noChange) {\n v = this._committedValues[i];\n if (v === NOT_COMMITTED)\n v = '';\n }\n change = change || !isPrimitive(v) || v !== this._committedValues[i];\n this._committedValues[i] = v;\n text += String(v === nothing ? '' : (v ?? '')) + this.strings[i + 1];\n }\n if (change) {\n if (text.includes('--') || text.endsWith('-')) {\n throw new Error('snice: comment expressions cannot produce \"--\" or end with \"-\".');\n }\n this.node.data = text;\n }\n }\n clear() { }\n}\n/** Toggle one class without rebuilding the element's full class string. */\nclass ClassPart extends Part {\n constructor(element, name) {\n super();\n this.type = 'class';\n this.committed = NOT_COMMITTED;\n this.element = element;\n this.name = name;\n }\n commit(value) {\n if (value === noChange)\n return;\n const enabled = value !== nothing && Boolean(value);\n if (enabled === this.committed)\n return;\n this.committed = enabled;\n this.element.classList.toggle(this.name, enabled);\n }\n clear() {\n this.element.classList.remove(this.name);\n this.committed = NOT_COMMITTED;\n }\n}\n/** Set one CSS property, including custom properties, declaratively. */\nclass StylePart extends Part {\n constructor(element, name) {\n super();\n this.type = 'style';\n this.committed = NOT_COMMITTED;\n this.element = element;\n this.name = name;\n }\n commit(value) {\n if (value === noChange || Object.is(value, this.committed))\n return;\n this.committed = value;\n const style = this.element.style;\n if (value === nothing || value == null || value === false) {\n style.removeProperty(this.name);\n }\n else {\n style.setProperty(this.name, String(value));\n }\n }\n clear() {\n this.element.style.removeProperty(this.name);\n this.committed = NOT_COMMITTED;\n }\n}\nfunction validateSpreadEvents(next, label) {\n const names = new Set();\n for (const [rawName, value] of Object.entries(next)) {\n const name = rawName.startsWith('@') ? rawName.slice(1) : rawName;\n if (!name)\n throw new TypeError(`snice: ${label} contains an empty event name.`);\n if (names.has(name)) {\n throw new TypeError(`snice: ${label} contains duplicate event name \"${name}\".`);\n }\n names.add(name);\n const listenerObject = !!value && typeof value === 'object' &&\n typeof value.handleEvent === 'function';\n if (value !== nothing && value != null && value !== false &&\n typeof value !== 'function' && !listenerObject) {\n throw new TypeError(`snice: ${label} event \"${name}\" expects a function, EventListenerObject, or null.`);\n }\n }\n}\n/** Named spreads: ...props, ...attrs, and ...events. */\nclass SpreadPart extends Part {\n constructor(element, name) {\n super();\n this.type = 'spread';\n this.committed = {};\n this.listeners = new Map();\n this.consumedOnce = new Map();\n this.element = element;\n this.name = name;\n }\n commit(value) {\n if (value === noChange)\n return;\n if (value === nothing || value == null)\n value = {};\n if (typeof value !== 'object' || Array.isArray(value)) {\n throw new TypeError(`snice: ...${this.name} expects an object.`);\n }\n const next = value;\n if (this.name === 'events')\n this.commitEvents(next);\n else if (this.name === 'props' || this.name === 'properties')\n this.commitProperties(next);\n else\n this.commitAttributes(next);\n this.committed = { ...next };\n }\n commitProperties(next) {\n for (const key of Object.keys(this.committed)) {\n if (!Object.prototype.hasOwnProperty.call(next, key)) {\n markPreUpgradePropertyBinding(this.element, key);\n this.element[key] = undefined;\n }\n }\n for (const [key, value] of Object.entries(next)) {\n if (Object.is(this.committed[key], value))\n continue;\n markPreUpgradePropertyBinding(this.element, key);\n this.element[key] = value === nothing ? undefined : value;\n }\n }\n commitAttributes(next) {\n for (const key of Object.keys(this.committed)) {\n if (!Object.prototype.hasOwnProperty.call(next, key))\n this.element.removeAttribute(key);\n }\n for (const [key, value] of Object.entries(next)) {\n if (Object.is(this.committed[key], value))\n continue;\n if (value === nothing || value == null || value === false)\n this.element.removeAttribute(key);\n else\n this.element.setAttribute(key, value === true ? '' : String(value));\n }\n }\n commitEvents(next) {\n validateSpreadEvents(next, `...${this.name}`);\n for (const [name, value] of this.consumedOnce) {\n const rawName = Object.keys(next).find(key => this.eventName(key) === name);\n if (!rawName || !Object.is(next[rawName], value))\n this.consumedOnce.delete(name);\n }\n for (const [name, entry] of this.listeners) {\n const rawName = Object.keys(next).find(key => this.eventName(key) === name);\n if (rawName && Object.is(next[rawName], entry.value))\n continue;\n this.element.removeEventListener(name, entry.listener, entry.options);\n this.listeners.delete(name);\n }\n for (const [rawName, value] of Object.entries(next)) {\n const name = this.eventName(rawName);\n if (this.listeners.has(name))\n continue;\n const listenerObject = !!value && typeof value === 'object' &&\n typeof value.handleEvent === 'function';\n if (value === nothing || value == null || value === false)\n continue;\n if (this.consumedOnce.has(name) && Object.is(this.consumedOnce.get(name), value))\n continue;\n this.consumedOnce.delete(name);\n const options = listenerObject ? value : undefined;\n const listener = ((event) => {\n if (options?.once)\n this.consumedOnce.set(name, value);\n if (listenerObject)\n value.handleEvent(event);\n else\n value.call(this.resolveHost(), event);\n });\n this.element.addEventListener(name, listener, options);\n this.listeners.set(name, { value, listener, options });\n }\n }\n eventName(name) {\n return name.startsWith('@') ? name.slice(1) : name;\n }\n resolveHost() {\n return findRenderHost(this.element) || this.element;\n }\n clear() {\n if (this.name === 'events') {\n for (const [name, entry] of this.listeners) {\n this.element.removeEventListener(name, entry.listener, entry.options);\n }\n this.listeners.clear();\n this.consumedOnce.clear();\n }\n else if (this.name !== 'props' && this.name !== 'properties') {\n for (const key of Object.keys(this.committed))\n this.element.removeAttribute(key);\n }\n // A property spread is being destroyed with the element that owns it.\n // Resetting native/custom properties here is unnecessary and can throw for\n // setters that reject undefined (textarea.value is a common example).\n // Stale keys are still removed during an ordinary live spread update.\n this.committed = {};\n }\n disconnected(preserveEventListeners = false) {\n if (this.name === 'events' && !preserveEventListeners)\n this.detachListeners();\n }\n reconnected() {\n if (this.name === 'events' && this.listeners.size === 0)\n this.commitEvents(this.committed);\n }\n detachListeners() {\n for (const [name, entry] of this.listeners) {\n this.element.removeEventListener(name, entry.listener, entry.options);\n }\n this.listeners.clear();\n }\n}\n/**\n * PropertyPart handles property bindings (.property=${value})\n */\nclass PropertyPart extends Part {\n constructor(element, name) {\n super();\n this.type = 'property';\n this._committedValue = NOT_COMMITTED;\n this.element = element;\n this.name = name;\n }\n commit(value) {\n if (value === noChange)\n return;\n // live(): compare against the element's actual DOM property, so state\n // the user changed (typed text, toggled checkbox) is reset even when the\n // bound value itself is unchanged.\n if (isLive(value)) {\n value = value.value;\n if (value === noChange)\n return;\n const domValue = this.element[this.name];\n if (value === domValue) {\n this._committedValue = value;\n return;\n }\n }\n else {\n // Dirty check - skip if same value\n if (value === this._committedValue)\n return;\n }\n this._committedValue = value;\n markPreUpgradePropertyBinding(this.element, this.name);\n this.element[this.name] = value === nothing ? undefined : value;\n }\n clear() {\n // This part is being destroyed with its owning template. The element is\n // about to leave the tree, so writing `undefined` is both unnecessary and\n // unsafe for native setters such as HTMLTextAreaElement.value.\n this._committedValue = NOT_COMMITTED;\n }\n}\n/**\n * ControllerPart handles bare controller=${...} bindings.\n *\n * Accepts a controller class decorated with @controller (attached directly,\n * no registry lookup) or a registry name string (delegated to the attribute\n * channel with the exact semantics of a static controller=\"name\"). While a\n * class is bound it owns the element: the attribute/MutationObserver channel\n * is inert until the class is unbound.\n *\n * Renders commit while the tree is detached and connect afterwards, so\n * attachment happens on reconnected()/connected commits; every hook is\n * idempotent because the update loop reconciles connection state on each pass.\n */\nclass ControllerPart extends Part {\n constructor(element) {\n super();\n this.type = 'controller';\n this._committedValue = NOT_COMMITTED;\n this.element = element;\n }\n commit(value) {\n if (value === noChange)\n return;\n // Normalize every \"no controller\" shape to null\n const next = (value == null || value === false || value === '' || value === nothing)\n ? null\n : value;\n const first = this._committedValue === NOT_COMMITTED;\n const previous = first ? null : this._committedValue;\n if (!first && next === previous)\n return;\n this._committedValue = next;\n const el = this.element;\n // Leaving a class binding: release the element back to the attribute channel.\n if (typeof previous === 'function' && typeof next !== 'function') {\n if (el[PENDING_CONTROLLER_BINDING] !== undefined) {\n delete el[PENDING_CONTROLLER_BINDING];\n }\n else if (el[IS_ELEMENT_CLASS]) {\n el.controller = null;\n }\n else {\n this._detach();\n }\n }\n if (typeof next === 'function') {\n // Class binding takes over — drop any attribute so the string channel\n // cannot fight it.\n if (this.element.hasAttribute('controller'))\n this.element.removeAttribute('controller');\n if (this.isConnected) {\n this._apply(next);\n }\n else if (this.element.localName.includes('-') && !el[IS_ELEMENT_CLASS]) {\n // Park on not-yet-upgraded custom elements even while detached — the\n // element picks the class up in connectedCallback on upgrade.\n el[PENDING_CONTROLLER_BINDING] = next;\n }\n // Detached native/upgraded elements attach in reconnected().\n }\n else if (typeof next === 'string') {\n this.element.setAttribute('controller', next);\n }\n else if (typeof previous === 'string') {\n this.element.removeAttribute('controller');\n }\n }\n /** Drive the element toward the committed class. Idempotent. */\n _apply(controllerClass) {\n const el = this.element;\n if (el[IS_ELEMENT_CLASS]) {\n if (el.controller !== controllerClass) {\n // Setter handles detach of the old controller and attach of the new.\n el.controller = controllerClass;\n }\n else {\n // Same value: the setter would no-op, but the element may have\n // self-detached on disconnect. attachController dedupes when the\n // controller is still attached.\n this._attach(controllerClass);\n }\n return;\n }\n if (this.element.localName.includes('-')) {\n // Custom element that hasn't upgraded yet (defined later, or cloned\n // into a detached fragment). Park the class — connectedCallback picks\n // it up on upgrade. Assigning the property now would shadow the future\n // prototype accessor with an own expando property.\n el[PENDING_CONTROLLER_BINDING] = controllerClass;\n return;\n }\n // Native element — attach directly. Mirror the observer path's ready shim.\n if (!el.ready)\n el.ready = Promise.resolve();\n this._attach(controllerClass);\n }\n _attach(controllerClass) {\n attachController(this.element, controllerClass).catch((error) => {\n if (error?.name === 'ControllerAttachAborted')\n return;\n console.error(`Failed to attach controller \"${controllerClass?.name || controllerClass}\":`, error);\n });\n }\n _detach() {\n detachController(this.element).catch((error) => {\n console.error('Failed to detach controller:', error);\n });\n }\n disconnected(_preserveEventListeners = false) {\n const committed = this._committedValue;\n if (typeof committed !== 'function')\n return;\n const el = this.element;\n if (el[PENDING_CONTROLLER_BINDING] !== undefined)\n return; // never attached\n if (el[IS_ELEMENT_CLASS])\n return; // snice elements detach themselves on disconnect\n this._detach();\n }\n reconnected() {\n const committed = this._committedValue;\n if (typeof committed !== 'function')\n return;\n this._apply(committed);\n }\n clear() {\n const el = this.element;\n if (el[PENDING_CONTROLLER_BINDING] !== undefined)\n delete el[PENDING_CONTROLLER_BINDING];\n const committed = this._committedValue;\n this._committedValue = NOT_COMMITTED;\n if (typeof committed !== 'function')\n return;\n if (el[IS_ELEMENT_CLASS])\n return; // the element's own teardown detaches\n this._detach();\n }\n}\n/**\n * BooleanAttributePart handles boolean attributes (?attribute=${value})\n */\nclass BooleanAttributePart extends Part {\n constructor(element, name) {\n super();\n this.type = 'boolean-attribute';\n this._committedValue = NOT_COMMITTED;\n this.element = element;\n this.name = name;\n }\n commit(value) {\n if (value === noChange)\n return;\n // Coerce to boolean\n const boolValue = !!value && value !== nothing;\n // Dirty check - skip if same boolean value\n if (boolValue === this._committedValue)\n return;\n this._committedValue = boolValue;\n if (boolValue) {\n this.element.setAttribute(this.name, '');\n }\n else {\n this.element.removeAttribute(this.name);\n }\n }\n clear() {\n this.element.removeAttribute(this.name);\n this._committedValue = NOT_COMMITTED;\n }\n}\n/**\n * EventPart handles event listener bindings with keyboard shortcut support\n */\nclass EventPart extends Part {\n constructor(element, eventName) {\n super();\n this.type = 'event';\n this.listener = null;\n this.listenerOptions = undefined;\n this.value = undefined;\n this.keyFilter = null;\n this.host = null; // Cache host element\n this.modifiers = new Set();\n this.once = false;\n this.onceConsumed = false;\n this.element = element;\n const [eventSpec, ...modifierSpecs] = eventName.split('|');\n const aliases = {\n preventdefault: 'prevent',\n stoppropagation: 'stop',\n stopimmediatepropagation: 'immediate'\n };\n const allowed = new Set(['prevent', 'stop', 'immediate', 'once', 'capture', 'passive', 'self']);\n for (const raw of modifierSpecs) {\n const normalized = aliases[raw.toLowerCase()] || raw.toLowerCase();\n if (!allowed.has(normalized)) {\n throw new Error(`snice: unknown event modifier \"${raw}\" in @${eventName}. ` +\n 'Supported modifiers: prevent, stop, immediate, once, capture, passive, self.');\n }\n this.modifiers.add(normalized);\n }\n if (this.modifiers.has('passive') && this.modifiers.has('prevent')) {\n throw new Error(`snice: @${eventName} cannot combine passive and prevent.`);\n }\n // Parse keyboard shortcuts:\n // Supports both dot notation (@keydown.enter) and colon notation (@keydown:Enter) to match @on decorator\n // Only parse colons for keyboard events, not custom events\n const isKeyboardEvent = ['keydown', 'keyup', 'keypress'].includes(eventSpec.split('.')[0].split(':')[0]);\n // Only keyboard events split on `.`/`:` into a key filter — a custom event\n // name may legitimately contain a dot (e.g. `app.ready`) and must be kept whole.\n const dotIndex = isKeyboardEvent ? eventSpec.indexOf('.') : -1;\n const colonIndex = isKeyboardEvent ? eventSpec.indexOf(':') : -1;\n // Use whichever delimiter comes first (dot or colon)\n const delimiterIndex = dotIndex > 0 && colonIndex > 0\n ? Math.min(dotIndex, colonIndex)\n : Math.max(dotIndex, colonIndex);\n if (delimiterIndex > 0) {\n const baseEvent = eventSpec.substring(0, delimiterIndex);\n const keySpec = eventSpec.substring(delimiterIndex + 1);\n this.eventName = baseEvent;\n this.keyFilter = parseKeyboardFilter(keySpec);\n }\n else {\n this.eventName = eventSpec;\n warnIfModifierMisuse(eventSpec);\n }\n }\n commit(value) {\n // Handle noChange sentinel\n if (value === noChange)\n return;\n // Handle nothing sentinel - remove listener\n if (value === nothing) {\n value = null;\n }\n const isListenerObject = !!value &&\n typeof value === 'object' &&\n typeof value.handleEvent === 'function';\n if (value !== null && value !== undefined && value !== false &&\n typeof value !== 'function' && !isListenerObject) {\n throw new TypeError(`snice: @${this.eventName} expects a function, EventListenerObject, or null.`);\n }\n if (isListenerObject && this.modifiers.has('prevent') && !!value.passive) {\n throw new Error(`snice: @${this.eventName} cannot combine a passive listener object with prevent.`);\n }\n // Skip if same value (but null/undefined always triggers update for cleanup)\n if (value === this.value && value !== null && value !== undefined)\n return;\n // Remove old listener (with the same capture option it was added with)\n if (this.listener) {\n this.element.removeEventListener(this.eventName, this.listener, this.listenerOptions);\n this.listener = null;\n this.listenerOptions = undefined;\n }\n // Add new listener\n if (value === null || value === undefined || value === false) {\n this.value = value;\n this.onceConsumed = false;\n return;\n }\n this.onceConsumed = false;\n try {\n this.attachListener(value, isListenerObject);\n this.value = value;\n }\n catch (error) {\n this.value = undefined;\n throw error;\n }\n }\n attachListener(value, isListenerObject) {\n // Accept plain functions AND EventListenerObject ({ handleEvent }). For\n // listener objects, the object itself doubles as the options bag.\n const keyFilter = this.keyFilter;\n const listener = ((event) => {\n if (this.modifiers.has('self') && event.target !== this.element)\n return;\n if (keyFilter && !matchesKeyboardFilter(event, keyFilter))\n return;\n if (this.once) {\n this.onceConsumed = true;\n this.element.removeEventListener(this.eventName, listener, listenerOptions);\n this.listener = null;\n this.listenerOptions = undefined;\n }\n if (this.modifiers.has('prevent'))\n event.preventDefault();\n if (this.modifiers.has('immediate'))\n event.stopImmediatePropagation();\n else if (this.modifiers.has('stop'))\n event.stopPropagation();\n if (isListenerObject) {\n // DOM spec: `this` inside handleEvent is the listener object itself\n value.handleEvent(event);\n return;\n }\n // Resolve the host (the custom element owning the shadow root) at dispatch\n // time, not bind time: a binding inside an initially-hidden <if>/<case>\n // branch commits while off-DOM, where getRootNode() has no host — caching\n // that null permanently would call the handler with `this = null` once the\n // branch is shown. By the time an event fires, the element is in the DOM.\n if (!this.host) {\n this.host = findRenderHost(this.element);\n }\n value.call(this.host || this.element, event);\n });\n const valueOptions = isListenerObject ? value : {};\n this.once = this.modifiers.has('once') || !!valueOptions.once;\n const listenerOptions = {\n capture: this.modifiers.has('capture') || valueOptions.capture,\n passive: this.modifiers.has('passive') || valueOptions.passive,\n signal: valueOptions.signal\n };\n this.element.addEventListener(this.eventName, listener, listenerOptions);\n this.listener = listener;\n this.listenerOptions = listenerOptions;\n }\n clear() {\n this.detachListener();\n this.value = undefined;\n this.host = null;\n this.onceConsumed = false;\n }\n detachListener() {\n if (this.listener) {\n this.element.removeEventListener(this.eventName, this.listener, this.listenerOptions);\n this.listener = null;\n this.listenerOptions = undefined;\n }\n }\n disconnected(preserveEventListeners = false) {\n if (!preserveEventListeners)\n this.detachListener();\n this.host = null;\n }\n reconnected() {\n if (!this.listener && !this.onceConsumed && this.value != null && this.value !== false) {\n const isListenerObject = typeof this.value === 'object';\n this.attachListener(this.value, isListenerObject);\n }\n }\n}\n/**\n * Parse keyboard shortcut specification\n * Examples:\n * \"enter\" -> { key: \"Enter\" }\n * \"ctrl+s\" -> { key: \"s\", ctrl: true }\n * \"ctrl+shift+s\" -> { key: \"s\", ctrl: true, shift: true }\n * \"~enter\" -> { key: \"Enter\", anyModifiers: true }\n */\n// once/preventDefault/stopPropagation/capture/passive are @on() OPTIONS, not\n// template modifiers. A dotted non-keyboard event whose suffix is one of these\n// is almost certainly a mistake (e.g. `@click.once`) — it binds a listener for\n// an event type the DOM never dispatches. Warn instead of failing silently. A\n// legitimate custom event name like `app.ready` won't match and stays quiet.\nconst MODIFIER_WORDS = new Set([\n 'once', 'prevent', 'preventdefault', 'stop', 'stoppropagation', 'capture', 'passive',\n]);\nfunction warnIfModifierMisuse(eventName) {\n const dot = eventName.lastIndexOf('.');\n if (dot < 0)\n return;\n const suffix = eventName.slice(dot + 1).toLowerCase();\n if (!MODIFIER_WORDS.has(suffix))\n return;\n console.warn(`snice: \"@${eventName}\" is not a valid modifier — once/preventDefault/` +\n `stopPropagation/capture are @on() options, not template modifiers. ` +\n `This registers a listener for event \"${eventName}\", which never fires.`);\n}\nfunction parseKeyboardFilter(spec) {\n // Handle ~ prefix for matching regardless of modifiers\n const anyModifiers = spec.startsWith('~');\n if (anyModifiers) {\n spec = spec.substring(1);\n }\n const parts = spec.split('+');\n const filter = {\n key: '',\n anyModifiers\n };\n for (const part of parts) {\n const lower = part.toLowerCase();\n if (lower === 'ctrl' || lower === 'control') {\n filter.ctrl = true;\n }\n else if (lower === 'alt') {\n filter.alt = true;\n }\n else if (lower === 'shift') {\n filter.shift = true;\n }\n else if (lower === 'meta' || lower === 'cmd' || lower === 'command') {\n filter.meta = true;\n }\n else {\n // This is the key itself - normalize common keys\n filter.key = normalizeKey(part);\n }\n }\n return filter;\n}\n/**\n * Normalize key names to match KeyboardEvent.key\n */\nfunction normalizeKey(key) {\n const keyMap = {\n 'esc': 'Escape',\n 'escape': 'Escape',\n 'enter': 'Enter',\n 'return': 'Enter',\n 'space': ' ',\n 'spacebar': ' ',\n 'up': 'ArrowUp',\n 'down': 'ArrowDown',\n 'left': 'ArrowLeft',\n 'right': 'ArrowRight',\n 'arrowup': 'ArrowUp',\n 'arrowdown': 'ArrowDown',\n 'arrowleft': 'ArrowLeft',\n 'arrowright': 'ArrowRight',\n 'delete': 'Delete',\n 'del': 'Delete',\n 'backspace': 'Backspace',\n 'tab': 'Tab',\n 'home': 'Home',\n 'end': 'End',\n 'pageup': 'PageUp',\n 'pagedown': 'PageDown'\n };\n const lower = key.toLowerCase();\n return keyMap[lower] || key;\n}\n/**\n * Check if keyboard event matches the filter\n */\nfunction matchesKeyboardFilter(event, filter) {\n // Check key match\n if (event.key !== filter.key) {\n return false;\n }\n // If anyModifiers is true, we don't care about modifiers\n if (filter.anyModifiers) {\n return true;\n }\n // Check modifiers - by default, exact match\n // If filter specifies ctrl: true, event must have ctrlKey\n // If filter doesn't specify ctrl, event must NOT have ctrlKey\n const ctrlMatch = filter.ctrl ? event.ctrlKey : !event.ctrlKey;\n const altMatch = filter.alt ? event.altKey : !event.altKey;\n const shiftMatch = filter.shift ? event.shiftKey : !event.shiftKey;\n const metaMatch = filter.meta ? event.metaKey : !event.metaKey;\n return ctrlMatch && altMatch && shiftMatch && metaMatch;\n}\n/**\n * ConditionalIfPart handles <if> conditional rendering\n * Removes/inserts DOM nodes based on condition\n */\n// Sentinel value to distinguish \"not yet set\" from undefined\nconst NOT_SET = Symbol('not-set');\nclass ConditionalIfPart extends Part {\n constructor(ifElement) {\n super();\n this.type = 'node';\n this.conditions = [NOT_SET];\n this.branches = [];\n this.defaultBranch = -1;\n this.currentBranch = -1;\n const parent = ifElement.parentNode;\n // Create comment boundary markers\n this.startNode = document.createComment('if');\n this.endNode = document.createComment('/if');\n // Insert markers where <if> is\n parent.insertBefore(this.startNode, ifElement);\n parent.insertBefore(this.endNode, ifElement.nextSibling);\n const primary = document.createDocumentFragment();\n this.branches.push(primary);\n let sawAlternative = false;\n let lastBranch = primary;\n for (const child of Array.from(ifElement.childNodes)) {\n const tag = child.nodeType === Node.ELEMENT_NODE\n ? child.tagName.toLowerCase()\n : '';\n if (tag === 'else-if' || tag === 'else') {\n sawAlternative = true;\n const wrapper = child;\n const fragment = document.createDocumentFragment();\n while (wrapper.firstChild)\n fragment.appendChild(wrapper.firstChild);\n const index = this.branches.push(fragment) - 1;\n lastBranch = fragment;\n if (tag === 'else-if') {\n if (this.defaultBranch !== -1) {\n throw new Error('snice: <else> must be the final branch inside <if>.');\n }\n this.conditions[index] = NOT_SET;\n conditionalElseIfOwners.set(wrapper, { coordinator: this, index });\n }\n else {\n if (this.defaultBranch !== -1) {\n throw new Error('snice: <if> may contain only one <else> branch.');\n }\n this.defaultBranch = index;\n }\n wrapper.remove();\n continue;\n }\n if (!sawAlternative) {\n primary.appendChild(child);\n }\n else if (child.nodeType === Node.TEXT_NODE && !child.textContent?.trim()) {\n child.remove();\n }\n else {\n lastBranch.appendChild(child);\n }\n }\n parent.removeChild(ifElement);\n }\n commit(value) {\n if (value !== noChange)\n this.conditions[0] = value;\n }\n setAlternative(index, value) {\n if (value !== noChange)\n this.conditions[index] = value;\n }\n flush() {\n let next = -1;\n for (let i = 0; i < this.conditions.length; i++) {\n if (this.conditions[i] !== NOT_SET &&\n this.conditions[i] !== nothing &&\n Boolean(this.conditions[i])) {\n next = i;\n break;\n }\n }\n if (next === -1)\n next = this.defaultBranch;\n if (next === this.currentBranch)\n return;\n this.collectCurrent();\n this.currentBranch = next;\n if (next !== -1 && this.branches[next].hasChildNodes()) {\n this.startNode.parentNode?.insertBefore(this.branches[next], this.endNode);\n }\n }\n collectCurrent() {\n if (this.currentBranch === -1)\n return;\n const fragment = this.branches[this.currentBranch];\n let node = this.startNode.nextSibling;\n while (node && node !== this.endNode) {\n const next = node.nextSibling;\n fragment.appendChild(node);\n node = next;\n }\n }\n clear() {\n this.collectCurrent();\n this.currentBranch = -1;\n }\n get isConnected() {\n return this.startNode.isConnected;\n }\n}\nconst conditionalElseIfOwners = new WeakMap();\nclass ConditionalElseIfPart extends Part {\n constructor(element) {\n super();\n this.type = 'node';\n const owner = conditionalElseIfOwners.get(element);\n if (!owner)\n throw new Error('snice: <else-if> must be a direct child of <if>.');\n this.coordinator = owner.coordinator;\n this.index = owner.index;\n }\n commit(value) {\n this.coordinator.setAlternative(this.index, value);\n }\n clear() { }\n get isConnected() {\n return this.coordinator.isConnected;\n }\n}\n/**\n * ConditionalCasePart handles <case>/<when>/<default> conditional rendering\n * Removes/inserts matching branch based on value\n */\nclass ConditionalCasePart extends Part {\n constructor(caseElement, dynamicWhenElements) {\n super();\n this.type = 'node';\n this.value = NOT_SET;\n this.branches = [];\n this.defaultBranch = -1;\n this.currentBranch = -1;\n const parent = caseElement.parentNode;\n // Create comment boundary markers\n this.startNode = document.createComment('case');\n this.endNode = document.createComment('/case');\n // Insert markers where <case> is\n parent.insertBefore(this.startNode, caseElement);\n parent.insertBefore(this.endNode, caseElement.nextSibling);\n // Extract branches from <when> and <default> children\n for (const child of Array.from(caseElement.children)) {\n const childTag = child.tagName.toLowerCase();\n if (childTag === 'when') {\n const fragment = document.createDocumentFragment();\n while (child.firstChild) {\n fragment.appendChild(child.firstChild);\n }\n const dynamic = dynamicWhenElements.has(child);\n const index = this.branches.push({\n fragment,\n dynamic,\n expected: dynamic ? NOT_SET : (child.getAttribute('value') ?? '')\n }) - 1;\n if (dynamic)\n conditionalWhenOwners.set(child, { coordinator: this, index });\n }\n else if (childTag === 'default') {\n if (this.defaultBranch !== -1) {\n throw new Error('snice: <case> may contain only one <default> branch.');\n }\n const fragment = document.createDocumentFragment();\n while (child.firstChild) {\n fragment.appendChild(child.firstChild);\n }\n this.defaultBranch = this.branches.push({\n fragment,\n dynamic: false,\n expected: NOT_SET\n }) - 1;\n }\n }\n // Remove the <case> element from DOM\n parent.removeChild(caseElement);\n }\n commit(value) {\n if (value !== noChange)\n this.value = value;\n }\n setExpected(index, value) {\n if (value !== noChange)\n this.branches[index].expected = value;\n }\n flush() {\n let next = this.branches.findIndex((branch, index) => {\n if (index === this.defaultBranch)\n return false;\n return branch.dynamic\n ? Object.is(this.value, branch.expected)\n : String(this.value) === branch.expected;\n });\n if (next === -1)\n next = this.defaultBranch;\n if (next === this.currentBranch)\n return;\n this.collectCurrent();\n this.currentBranch = next;\n if (next !== -1 && this.branches[next].fragment.hasChildNodes()) {\n this.startNode.parentNode?.insertBefore(this.branches[next].fragment, this.endNode);\n }\n }\n collectCurrent() {\n if (this.currentBranch === -1)\n return;\n const fragment = this.branches[this.currentBranch].fragment;\n let node = this.startNode.nextSibling;\n while (node && node !== this.endNode) {\n const next = node.nextSibling;\n fragment.appendChild(node);\n node = next;\n }\n }\n clear() {\n this.collectCurrent();\n this.currentBranch = -1;\n }\n get isConnected() {\n return this.startNode.isConnected;\n }\n}\nconst conditionalWhenOwners = new WeakMap();\nclass ConditionalWhenPart extends Part {\n constructor(element) {\n super();\n this.type = 'node';\n const owner = conditionalWhenOwners.get(element);\n if (!owner)\n throw new Error('snice: dynamic <when> must be a direct child of <case>.');\n this.coordinator = owner.coordinator;\n this.index = owner.index;\n }\n commit(value) {\n this.coordinator.setExpected(this.index, value);\n }\n clear() { }\n get isConnected() {\n return this.coordinator.isConnected;\n }\n}\n\n/**\n * @on decorator for listening to events\n * Use in elements or controllers to listen to DOM events or custom events\n */\nconst ON_HANDLERS = getSymbol('on-handlers');\n/**\n * @on decorator for listening to events\n *\n * Works in both elements and controllers with full event delegation support.\n *\n * @param eventName - Event name(s) to listen for\n * @param selector - Optional CSS selector for event delegation\n * @param options - Event listener options including debounce/throttle\n *\n * @example\n * ```typescript\n * // In elements\n * @element('my-button')\n * class MyButton extends HTMLElement {\n * @on('click', 'button')\n * handleClick(e: MouseEvent) {\n * console.log('Button clicked!', e);\n * }\n *\n * @on('input', 'input', { debounce: 300 })\n * handleInput(e: Event) {\n * console.log('Input changed:', (e.target as HTMLInputElement).value);\n * }\n * }\n *\n * // In controllers\n * @controller('my-controller')\n * class MyController {\n * element!: HTMLElement;\n *\n * @on('count-changed')\n * handleCountChanged(e: CustomEvent) {\n * console.log('Count changed to:', e.detail.count);\n * }\n *\n * @on('click', '.item', { throttle: 100 })\n * handleItemClick(e: MouseEvent) {\n * console.log('Item clicked');\n * }\n * }\n * ```\n */\nfunction on(eventName, selectorOrOptions, options) {\n // Parse arguments to support multiple call signatures\n let selector = null;\n let opts = {};\n if (typeof selectorOrOptions === 'string') {\n selector = selectorOrOptions;\n opts = options || {};\n }\n else if (selectorOrOptions && typeof selectorOrOptions === 'object') {\n opts = selectorOrOptions;\n }\n else if (selectorOrOptions === null && options) {\n opts = options;\n }\n return function (originalMethod, context) {\n const methodName = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // Dedup by registration identity (method + events + selector), NOT by\n // method reference alone — stacked @on decorators share one method and\n // must each register. Use hasOwnProperty so subclasses get their OWN\n // Set instead of inheriting — otherwise parent and child share state\n // and child registrations pollute parent (and vice versa) via the\n // prototype chain.\n const eventNames = Array.isArray(eventName) ? eventName : [eventName];\n const registrationKey = `${methodName}::${eventNames.join(',')}::${selector ?? ''}`;\n if (!Object.prototype.hasOwnProperty.call(constructor, ON_METHODS)) {\n constructor[ON_METHODS] = new Set();\n }\n if (constructor[ON_METHODS].has(registrationKey))\n return;\n constructor[ON_METHODS].add(registrationKey);\n if (!Object.prototype.hasOwnProperty.call(constructor, ON_HANDLERS)) {\n // Seed with parent's handlers (if any) so inherited @on still fires.\n const inherited = constructor[ON_HANDLERS];\n constructor[ON_HANDLERS] = inherited ? [...inherited] : [];\n }\n for (const event of eventNames) {\n constructor[ON_HANDLERS].push({\n eventName: event,\n selector,\n methodName,\n method: originalMethod,\n options: opts\n });\n }\n });\n return originalMethod;\n };\n}\n// Note: on.ts uses leading-edge-only throttle (no trailing call).\n// createThrottled from utils has leading+trailing, so we keep a local leading-only variant.\nfunction throttle$1(fn, delay) {\n let lastCall = 0;\n return function (...args) {\n const now = Date.now();\n if (now - lastCall >= delay) {\n lastCall = now;\n fn.apply(this, args);\n }\n };\n}\n/**\n * Events that don't bubble - these require capture phase for delegation\n */\nconst NON_BUBBLING_EVENTS = new Set([\n 'scroll',\n 'focus',\n 'blur',\n 'load',\n 'unload',\n 'error',\n 'resize',\n 'abort',\n 'mouseenter',\n 'mouseleave',\n 'pointerenter',\n 'pointerleave',\n]);\n/**\n * Setup event listeners for an element or controller instance\n * Called automatically during element connection or controller attachment\n */\nfunction setupEventHandlers(instance, targetElement) {\n const handlers = instance.constructor[ON_HANDLERS];\n if (!handlers || !Array.isArray(handlers) || handlers.length === 0) {\n return;\n }\n // Initialize cleanup object if needed\n if (!instance[CLEANUP]) {\n instance[CLEANUP] = { events: [], channels: [], observers: [] };\n }\n else if (!instance[CLEANUP].events) {\n instance[CLEANUP].events = [];\n }\n else if (instance[CLEANUP].events.length > 0) {\n // Events already set up - clean them up first to avoid duplicates\n cleanupEventHandlers(instance);\n }\n for (const handler of handlers) {\n // Get current method from instance (preserves decorator stacking)\n const currentMethod = instance[handler.methodName];\n let boundMethod = currentMethod ? currentMethod.bind(instance) : handler.method.bind(instance);\n const handlerOptions = handler.options || {};\n // Parse event name for key modifiers\n // Supports both dot notation (@keydown.enter) and colon notation (@keydown:Enter)\n // Only parse colons for keyboard events, not custom events\n const isKeyboardEvent = ['keydown', 'keyup', 'keypress'].includes(handler.eventName.split('.')[0].split(':')[0]);\n // Only keyboard events split on `.`/`:` into a key filter — a custom event\n // name may legitimately contain a dot (e.g. `app.ready`) and must be kept whole.\n const dotIndex = isKeyboardEvent ? handler.eventName.indexOf('.') : -1;\n const colonIndex = isKeyboardEvent ? handler.eventName.indexOf(':') : -1;\n const delimiterIndex = dotIndex > 0 && colonIndex > 0\n ? Math.min(dotIndex, colonIndex)\n : Math.max(dotIndex, colonIndex);\n const baseEventName = delimiterIndex > 0\n ? handler.eventName.substring(0, delimiterIndex)\n : handler.eventName;\n const keyModifier = delimiterIndex > 0\n ? handler.eventName.substring(delimiterIndex + 1)\n : null;\n if (delimiterIndex <= 0)\n warnIfModifierMisuse(handler.eventName);\n // Apply debounce (takes precedence over throttle)\n if (handlerOptions.debounce && handlerOptions.debounce > 0) {\n boundMethod = createDebounced(boundMethod, handlerOptions.debounce);\n }\n else if (handlerOptions.throttle && handlerOptions.throttle > 0) {\n boundMethod = throttle$1(boundMethod, handlerOptions.throttle);\n }\n // Create event handler with key modifier support\n // Uses shared keyboard filter implementation from parts.ts\n let keyFilter = null;\n if (keyModifier && ['keydown', 'keyup', 'keypress'].includes(baseEventName)) {\n keyFilter = parseKeyboardFilter(keyModifier);\n }\n const createKeyModifierHandler = (method) => {\n if (!keyFilter) {\n return method;\n }\n return (event) => {\n const keyEvent = event;\n if (matchesKeyboardFilter(keyEvent, keyFilter)) {\n method(event);\n }\n };\n };\n // Apply key modifier wrapper\n const keyModifierMethod = createKeyModifierHandler(boundMethod);\n // Resolve scope: explicit `scope` option redirects the listener target\n // to document / ancestor / arbitrary EventTarget. Default = host element.\n const hasExplicitScope = handlerOptions.scope !== undefined;\n let scopedTarget = null;\n if (hasExplicitScope) {\n scopedTarget = resolveScope(targetElement, handlerOptions.scope);\n if (!scopedTarget) {\n // Dev warning — listener silently dropped when scope cannot resolve.\n // Skip attachment so we don't bind to the wrong target.\n console.warn(`[snice/@on] scope did not resolve for \"${handler.eventName}\" on ${handler.methodName} — listener skipped.`);\n continue;\n }\n }\n // Main event handler with error handling and event delegation\n if (handler.selector) {\n // Delegated event handling.\n // - Default eventRoot: shadow root if present, else host element.\n // - With explicit scope: attach to the scoped target instead.\n const eventRoot = hasExplicitScope\n ? scopedTarget\n : (targetElement.shadowRoot || targetElement);\n const delegatedHandler = (event) => {\n const target = event.target;\n const matchingElement = (target.matches && target.matches(handler.selector) && target) ||\n (target.closest && target.closest(handler.selector)) ||\n null;\n if (!matchingElement)\n return;\n if (handlerOptions.preventDefault)\n event.preventDefault();\n if (handlerOptions.stopPropagation) {\n event.stopPropagation();\n event.stopImmediatePropagation();\n }\n try {\n keyModifierMethod(event);\n }\n catch (error) {\n console.error(`Error in event handler ${handler.methodName}:`, error);\n }\n };\n // Auto-enable capture for non-bubbling events when using delegation\n const needsCapture = NON_BUBBLING_EVENTS.has(baseEventName);\n const useCapture = handlerOptions.capture !== undefined\n ? handlerOptions.capture\n : needsCapture;\n const listenerOptions = {\n capture: useCapture,\n once: handlerOptions.once || false,\n passive: handlerOptions.passive || false,\n };\n eventRoot.addEventListener(baseEventName, delegatedHandler, listenerOptions);\n instance[CLEANUP].events.push({\n target: eventRoot,\n eventName: baseEventName,\n handler: delegatedHandler,\n options: listenerOptions,\n });\n }\n else {\n // Direct event handling.\n // - Default: shadow root + host element (so events inside shadow and on\n // the host itself both fire). A per-handler Symbol dedupes.\n // - With explicit scope: attach to the scoped target ONLY (no duplication).\n const shadowRoot = hasExplicitScope ? null : targetElement.shadowRoot;\n // Per-handler private Symbol so dedup is scoped to THIS handler's two\n // listeners (shadowRoot + host). Using Symbol.for() with the method name\n // would collide across components that share a method name (e.g. a parent\n // and nested child both defining `handleClick`), causing the parent's\n // handler to be silently swallowed when events bubble up through a\n // shadow boundary.\n const handledSymbol = Symbol();\n const wrappedMethod = (event) => {\n if (event[handledSymbol])\n return;\n event[handledSymbol] = true;\n if (handlerOptions.preventDefault)\n event.preventDefault();\n if (handlerOptions.stopPropagation)\n event.stopPropagation();\n try {\n keyModifierMethod(event);\n }\n catch (error) {\n console.error(`Error in event handler ${handler.methodName}:`, error);\n }\n };\n const listenerOptions = {\n capture: handlerOptions.capture || false,\n once: handlerOptions.once || false,\n passive: handlerOptions.passive || false,\n };\n if (hasExplicitScope) {\n scopedTarget.addEventListener(baseEventName, wrappedMethod, listenerOptions);\n instance[CLEANUP].events.push({\n target: scopedTarget,\n eventName: baseEventName,\n handler: wrappedMethod,\n options: listenerOptions,\n });\n continue;\n }\n if (shadowRoot) {\n // Listen on shadow root for events inside shadow DOM\n shadowRoot.addEventListener(baseEventName, wrappedMethod, listenerOptions);\n instance[CLEANUP].events.push({\n target: shadowRoot,\n eventName: baseEventName,\n handler: wrappedMethod,\n options: listenerOptions,\n });\n }\n // Also listen on host element (for clicks on host itself or when no shadow root)\n targetElement.addEventListener(baseEventName, wrappedMethod, listenerOptions);\n instance[CLEANUP].events.push({\n target: targetElement,\n eventName: baseEventName,\n handler: wrappedMethod,\n options: listenerOptions,\n });\n }\n }\n}\n/**\n * Cleanup event listeners for a controller instance\n * Called automatically by the controller system during detach\n */\nfunction cleanupEventHandlers(instance) {\n if (!instance[CLEANUP]?.events)\n return;\n for (const { target, eventName, handler, options } of instance[CLEANUP].events) {\n target.removeEventListener(eventName, handler, options);\n }\n instance[CLEANUP].events = [];\n}\n\n// Controller-scoped cleanup registry\nclass ControllerScope {\n constructor() {\n this.cleanupFns = new Map();\n this.pendingOperations = new Set();\n }\n register(key, cleanup) {\n this.cleanupFns.set(key, cleanup);\n }\n unregister(key) {\n this.cleanupFns.delete(key);\n }\n async cleanup() {\n // Wait for all pending operations\n await Promise.all(this.pendingOperations);\n // Run all cleanup functions\n for (const cleanup of this.cleanupFns.values()) {\n try {\n await cleanup();\n }\n catch (error) {\n console.error('Error during cleanup:', error);\n }\n }\n this.cleanupFns.clear();\n }\n async runOperation(operation) {\n const promise = operation();\n const voidPromise = promise.then(() => { }, () => { });\n this.pendingOperations.add(voidPromise);\n try {\n const result = await promise;\n this.pendingOperations.delete(voidPromise);\n return result;\n }\n catch (error) {\n this.pendingOperations.delete(voidPromise);\n throw error;\n }\n }\n}\n/**\n * Decorator to register a controller class with a name\n * @param name The name to register the controller under\n */\nfunction controller(name) {\n return function (constructor, _context) {\n // Access globalThis.snice directly to ensure consistency\n const registry = globalThis.snice?.controllerRegistry;\n if (!registry) {\n throw new Error('Snice global registry not initialized');\n }\n registry.set(name, constructor);\n // Mark as controller class for channel decorator detection\n constructor.prototype[IS_CONTROLLER_CLASS] = true;\n const pending = snice.pendingControllerAttachments.get(name);\n if (pending) {\n snice.pendingControllerAttachments.delete(name);\n queueMicrotask(() => {\n for (const element of pending) {\n const nativeName = element[NATIVE_CONTROLLER];\n const desiredName = nativeName === undefined\n ? element[CONTROLLER]\n : nativeName;\n if (desiredName !== name)\n continue;\n attachController(element, name).catch(error => {\n if (error?.name !== 'ControllerAttachAborted') {\n console.error(`Failed to attach controller \"${name}\":`, error);\n }\n });\n }\n });\n }\n return constructor;\n };\n}\n/** Queue an element until its controller module finishes registering. */\nfunction deferControllerAttachment(element, controllerName) {\n // Registration can win the microtask race between attachController's\n // rejected promise and this recovery path. Retry immediately in that case.\n if (snice.controllerRegistry.has(controllerName)) {\n queueMicrotask(() => {\n const nativeName = element[NATIVE_CONTROLLER];\n const desiredName = nativeName === undefined\n ? element[CONTROLLER]\n : nativeName;\n if (desiredName !== controllerName)\n return;\n attachController(element, controllerName).catch(error => {\n if (error?.name !== 'ControllerAttachAborted') {\n console.error(`Failed to attach controller \"${controllerName}\":`, error);\n }\n });\n });\n return;\n }\n let pending = snice.pendingControllerAttachments.get(controllerName);\n if (!pending) {\n pending = new Set();\n snice.pendingControllerAttachments.set(controllerName, pending);\n }\n pending.add(element);\n // Give synchronously evaluated and microtask-delayed controller modules a\n // chance to register, while keeping genuinely missing controllers loud.\n queueMicrotask(() => {\n if (snice.pendingControllerAttachments.get(controllerName)?.has(element)) {\n console.error(`Failed to attach controller \"${controllerName}\":`, new Error(`Controller \"${controllerName}\" not found in registry`));\n }\n });\n}\n/**\n * True when the value is a controller class that went through @controller().\n * The decorator is required — it registers the class, marks it, and flushes\n * pending attachments. Direct class binding only changes the attach side.\n */\nfunction isControllerClass(value) {\n return typeof value === 'function'\n && value.prototype?.[IS_CONTROLLER_CLASS] === true;\n}\n/** Human-readable label for a controller reference (registry name or class). */\nfunction controllerLabel(controller) {\n return typeof controller === 'string'\n ? controller\n : (controller?.name || '(anonymous controller class)');\n}\n/**\n * Attaches a controller to an element\n * @param element The element to attach the controller to\n * @param controller The registry name of the controller, or the decorated\n * controller class itself (classes skip the registry)\n */\nasync function attachController(element, controller) {\n if (typeof controller !== 'string') {\n if (typeof controller !== 'function') {\n throw new Error('attachController: expected a controller name or a controller class, ' +\n `got ${typeof controller}. Controller instances are not supported — pass the class itself.`);\n }\n if (!isControllerClass(controller)) {\n throw new Error(`Controller class \"${controllerLabel(controller)}\" must be decorated with ` +\n `@controller('name') before it can be attached.`);\n }\n }\n const controllerName = controllerLabel(controller);\n const existingController = element[CONTROLLER_KEY];\n const existingSource = element[CONTROLLER_NAME_KEY];\n // For attribute-managed native elements, check if this is actually the\n // desired controller. Class attachments take the element over instead.\n const nativeController = element[NATIVE_CONTROLLER];\n if (typeof controller === 'string' && nativeController !== undefined && nativeController !== controller) {\n // This attachment is outdated, skip it\n return;\n }\n if (existingSource === controller && existingController) {\n // Already attached and controller exists (name or class reference match)\n return;\n }\n // If there's an existing controller, detach it first\n if (existingController) {\n await detachController(element);\n }\n let ControllerClass;\n if (typeof controller === 'string') {\n // Access globalThis.snice directly to ensure consistency\n const registry = globalThis.snice?.controllerRegistry;\n if (!registry) {\n throw new Error('Snice global registry not initialized');\n }\n ControllerClass = registry.get(controller);\n if (!ControllerClass) {\n throw new Error(`Controller \"${controller}\" not found in registry`);\n }\n }\n else {\n ControllerClass = controller;\n // The class channel owns the element from here on: the attribute /\n // MutationObserver channel goes inert and its bookkeeping is dropped.\n element[DIRECT_CONTROLLER] = true;\n delete element[NATIVE_CONTROLLER];\n }\n // Create controller instance with unique ID and scope\n const controllerInstance = new ControllerClass();\n snice.controllerIdCounter += 1;\n const controllerId = snice.controllerIdCounter;\n const scope = new ControllerScope();\n // Mark this as a controller instance\n controllerInstance[IS_CONTROLLER_INSTANCE] = true;\n controllerInstance[CONTROLLER_ID] = controllerId;\n controllerInstance.element = element;\n // Pass router context from element to controller if it exists\n const routerContext = element[ROUTER_CONTEXT];\n if (routerContext !== undefined) {\n controllerInstance[ROUTER_CONTEXT] = routerContext;\n }\n // Store references. CONTROLLER_NAME_KEY holds the attach source — the\n // registry name string, or the class reference itself for class attaches\n // (reference equality is the dedupe key for classes).\n element[CONTROLLER_KEY] = controllerInstance;\n element[CONTROLLER_NAME_KEY] = controller;\n element[CONTROLLER_OPERATIONS] = scope;\n // Wait for element to be ready. Race against abort (detachController) and\n // a 30s deadline so a caller that forgets to append the element gets a\n // clear error instead of an unresolvable promise.\n const abort = new AbortController();\n element[CONTROLLER_ABORT] = abort;\n const ATTACH_DEADLINE_MS = 30_000;\n try {\n await Promise.race([\n element.ready,\n new Promise((_, reject) => {\n const onAbort = () => {\n // Tagged so fire-and-forget call sites can tell this designed\n // teardown path apart from real attach failures and stay quiet.\n const error = new Error(`attachController(\"${controllerName}\"): aborted before element was ready (likely detached or never connected)`);\n error.name = 'ControllerAttachAborted';\n reject(error);\n };\n if (abort.signal.aborted)\n return onAbort();\n abort.signal.addEventListener('abort', onAbort, { once: true });\n const timerId = setTimeout(() => reject(new Error(`attachController(\"${controllerName}\"): element did not become ready within ${ATTACH_DEADLINE_MS}ms (did you forget to appendChild it?)`)), ATTACH_DEADLINE_MS);\n abort.signal.addEventListener('abort', () => clearTimeout(timerId), { once: true });\n }),\n ]);\n }\n catch (error) {\n // Attach never got past `ready` (aborted or deadline). Roll back the stored\n // references so nothing is left pointing at a controller that never\n // attached — otherwise a later attach short-circuits as \"already attached\"\n // and a detach would run detach() on it.\n if (element[CONTROLLER_KEY] === controllerInstance) {\n delete element[CONTROLLER_KEY];\n delete element[CONTROLLER_NAME_KEY];\n delete element[CONTROLLER_OPERATIONS];\n if (typeof controller !== 'string') {\n delete element[DIRECT_CONTROLLER];\n }\n }\n throw error;\n }\n finally {\n if (element[CONTROLLER_ABORT] === abort) {\n delete element[CONTROLLER_ABORT];\n }\n }\n // Past `ready` — mark the controller so detach knows attach was actually run.\n controllerInstance[CONTROLLER_ATTACHED] = true;\n // Run attach in the controller's scope\n await scope.runOperation(async () => {\n await controllerInstance.attach(element);\n });\n // Setup @observe observers for controller\n setupObservers(controllerInstance, element);\n // Setup @channel handlers for controller\n setupResponseHandlers(controllerInstance, element);\n // Setup @on event handlers for controller\n setupEventHandlers(controllerInstance, element);\n element.dispatchEvent(new CustomEvent('controller-attached', {\n detail: { name: controllerName, controller: controllerInstance }\n }));\n}\n/**\n * Detaches a controller from an element\n * @param element The element to detach the controller from\n */\nasync function detachController(element) {\n // If attachController is currently awaiting `.ready`, short-circuit that\n // wait so the pending attach rejects immediately instead of hanging.\n const pendingAbort = element[CONTROLLER_ABORT];\n if (pendingAbort)\n pendingAbort.abort();\n const controllerInstance = element[CONTROLLER_KEY];\n const controllerSource = element[CONTROLLER_NAME_KEY];\n const scope = element[CONTROLLER_OPERATIONS];\n if (!controllerInstance) {\n return;\n }\n // Claim the controller immediately — before any await — so a second detach\n // that overlaps this one (e.g. disconnect's fire-and-forget detach racing a\n // controller reassignment) finds no instance and returns, instead of running\n // detach() a second time on the same controller. The rest of this function\n // works off the locals captured above.\n delete element[CONTROLLER_KEY];\n delete element[CONTROLLER_NAME_KEY];\n delete element[CONTROLLER_OPERATIONS];\n if (typeof controllerSource === 'function') {\n // Class attach owned the element — release it back to the attribute channel.\n delete element[DIRECT_CONTROLLER];\n }\n // A controller whose attach() was aborted before it ever ran must not have\n // detach() (or the teardown/event) run on it.\n if (!controllerInstance[CONTROLLER_ATTACHED]) {\n return;\n }\n // Run detach in the controller's scope\n if (scope) {\n await scope.runOperation(async () => {\n await controllerInstance.detach(element);\n });\n }\n else {\n await controllerInstance.detach(element);\n }\n controllerInstance.element = null;\n // Cleanup @observe observers for controller\n cleanupObservers(controllerInstance);\n // Cleanup @channel handlers for controller\n cleanupResponseHandlers(controllerInstance);\n // Cleanup @on event handlers for controller\n cleanupEventHandlers(controllerInstance);\n // Cleanup the controller scope\n if (scope) {\n await scope.cleanup();\n }\n // Clean up router context reference\n delete controllerInstance[ROUTER_CONTEXT];\n element.dispatchEvent(new CustomEvent('controller-detached', {\n detail: {\n name: controllerSource === undefined ? undefined : controllerLabel(controllerSource),\n controller: controllerInstance\n }\n }));\n}\n/**\n * Gets the controller instance attached to an element\n * @param element The element to get the controller from\n * @returns The controller instance or undefined\n */\nfunction getController(element) {\n return element[CONTROLLER_KEY];\n}\n/**\n * Enable controller support for native HTML elements\n * This sets up a MutationObserver to watch for controller attributes\n * on non-custom elements (elements without hyphens in their tag names)\n */\nfunction useNativeElementControllers() {\n // Return if already initialized\n if (globalThis.sniceNativeControllersInitialized) {\n return;\n }\n globalThis.sniceNativeControllersInitialized = true;\n // Process elements that already have controller attribute\n function processElement(element) {\n if (!(element instanceof HTMLElement))\n return;\n // `tagName` can briefly be null when happy-dom/native mutation observers\n // fire on a node that's been detached mid-callback. Skip cleanly.\n if (!element.tagName || element.tagName.includes('-'))\n return;\n if (element[IS_ELEMENT_CLASS])\n return;\n // A controller CLASS is attached (template binding or direct\n // attachController(el, Class)). The class channel owns the element:\n // attribute writes must not attach over it, and insertion sweeps must\n // not detach it.\n if (element[DIRECT_CONTROLLER])\n return;\n const controllerName = element.getAttribute('controller');\n const currentControllerName = element[NATIVE_CONTROLLER];\n // No change\n if (controllerName === currentControllerName)\n return;\n // No attribute and never attribute-managed — nothing for this channel to\n // do. Without this guard, every added native element (including ones a\n // class controller was imperatively attached to before insertion) would\n // fall into the removal branch and get spuriously detached.\n if (!controllerName && currentControllerName === undefined)\n return;\n // Controller removed\n if (!controllerName) {\n delete element[NATIVE_CONTROLLER];\n delete element[CONTROLLER_NAME_KEY];\n detachController(element).catch(error => {\n console.error(`Failed to detach controller from native element:`, error);\n });\n return;\n }\n // Controller added or changed\n element[NATIVE_CONTROLLER] = controllerName;\n if (!element.ready) {\n element.ready = Promise.resolve();\n }\n if (currentControllerName) {\n detachController(element).catch(error => {\n console.error(`Failed to detach old controller from native element:`, error);\n });\n }\n attachController(element, controllerName).catch(error => {\n // Detached before ready — designed teardown, not a failure\n if (error?.name === 'ControllerAttachAborted') {\n console.debug(`Controller \"${controllerName}\" attach aborted (element detached before ready)`);\n return;\n }\n if (error?.message === `Controller \"${controllerName}\" not found in registry`) {\n deferControllerAttachment(element, controllerName);\n return;\n }\n console.error(`Failed to attach controller \"${controllerName}\" to native element:`, error);\n });\n }\n // Set up MutationObserver to watch for controller attributes\n const observer = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type === 'attributes' && mutation.attributeName === 'controller') {\n processElement(mutation.target);\n }\n else if (mutation.type === 'childList') {\n // Process added nodes\n mutation.addedNodes.forEach(node => {\n if (node instanceof HTMLElement) {\n // Process the node itself\n processElement(node);\n // Process all descendants with controller attribute\n node.querySelectorAll('[controller]').forEach(processElement);\n }\n });\n }\n }\n });\n function startObserving() {\n document.querySelectorAll('[controller]').forEach(processElement);\n observer.observe(document.body, {\n attributes: true,\n attributeFilter: ['controller'],\n childList: true,\n subtree: true\n });\n }\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', startObserving);\n }\n else {\n startObserving();\n }\n // Store observer reference for cleanup if needed\n globalThis.sniceNativeControllerObserver = observer;\n}\n\n/**\n * @context decorator for receiving router context updates\n */\nconst CONTEXT_HANDLERS = getSymbol('context-handlers');\n/**\n * @context decorator for receiving router context updates\n *\n * @example\n * ```typescript\n * @element('my-layout')\n * class MyLayout extends HTMLElement {\n * @context\n * handleContext(ctx: Context) {\n * this.renderNav(ctx.placards, ctx.currentRoute);\n * }\n *\n * @context({ debounce: 300 })\n * handleContextDebounced(ctx: Context) {\n * // Called after 300ms of no updates\n * }\n * }\n * ```\n */\nfunction context$1(options = {}) {\n return function (originalMethod, context) {\n const methodName = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // hasOwnProperty guards so subclasses don't mutate parent state via\n // the prototype chain.\n if (!Object.prototype.hasOwnProperty.call(constructor, CONTEXT_METHODS)) {\n constructor[CONTEXT_METHODS] = new Set();\n }\n if (constructor[CONTEXT_METHODS].has(originalMethod))\n return;\n constructor[CONTEXT_METHODS].add(originalMethod);\n if (!Object.prototype.hasOwnProperty.call(constructor, CONTEXT_HANDLERS)) {\n const inherited = constructor[CONTEXT_HANDLERS];\n constructor[CONTEXT_HANDLERS] = inherited ? [...inherited] : [];\n }\n constructor[CONTEXT_HANDLERS].push({\n methodName,\n method: originalMethod,\n options,\n });\n });\n return originalMethod;\n };\n}\n/**\n * Setup context handler for an element instance\n * Called automatically during element connection\n */\nfunction setupContextHandler(element) {\n const handlers = element.constructor[CONTEXT_HANDLERS];\n if (!handlers || !Array.isArray(handlers) || handlers.length === 0) {\n return;\n }\n // Get the Context instance from the router\n const ctx = element[CONTEXT_HANDLER];\n if (!ctx) {\n return;\n }\n // Store the Context instance for cleanup\n element[NAVIGATION_CONTEXT_INSTANCE] = ctx;\n // Register each handler with the Context\n for (const handler of handlers) {\n const { methodName, method, options } = handler;\n const wrappedMethodName = `__wrapped_${methodName}`;\n // Create wrapped method with timing controls\n element[wrappedMethodName] = function (context) {\n // `once` is tracked PER method (not a single element-level flag) so\n // multiple once handlers on the same element each fire.\n const called = element[CONTEXT_CALLED] ||\n (element[CONTEXT_CALLED] = new Set());\n if (options.once && called.has(methodName)) {\n return;\n }\n const callMethod = () => {\n method.call(element, context);\n // Handle once option\n if (options.once) {\n called.add(methodName);\n // Unregister ONLY this handler, not the whole element — otherwise the\n // element's other @context handlers would stop receiving updates.\n const ctx = element[NAVIGATION_CONTEXT_INSTANCE];\n if (ctx && typeof ctx[CONTEXT_UNREGISTER] === 'function') {\n ctx[CONTEXT_UNREGISTER](element, wrappedMethodName);\n }\n }\n };\n // Per-handler timer slot to avoid debounce/throttle handlers on the same\n // element overwriting each other's state.\n const timerSlot = element[CONTEXT_TIMER] ||\n (element[CONTEXT_TIMER] = {});\n const timerKey = methodName;\n if (options.debounce) {\n clearTimeout(timerSlot[timerKey]?.timeout);\n timerSlot[timerKey] = {\n timeout: setTimeout(callMethod, options.debounce),\n };\n return;\n }\n if (options.throttle) {\n const now = Date.now();\n const lastCall = timerSlot[timerKey]?.lastCall || 0;\n if (now - lastCall >= options.throttle) {\n timerSlot[timerKey] = { lastCall: now };\n callMethod();\n }\n return;\n }\n callMethod();\n };\n // Register with the Context using the wrapped method name\n if (typeof ctx[CONTEXT_REGISTER] === 'function') {\n ctx[CONTEXT_REGISTER](element, wrappedMethodName);\n }\n }\n}\n/**\n * Cleanup context handler for an element instance\n * Called automatically during element disconnection\n */\nfunction cleanupContextHandler(element) {\n const handlers = element.constructor[CONTEXT_HANDLERS];\n if (!handlers || !Array.isArray(handlers) || handlers.length === 0) {\n return;\n }\n // Clear any pending debounce timers (per-handler slots)\n const timerSlot = element[CONTEXT_TIMER];\n if (timerSlot && typeof timerSlot === 'object') {\n for (const key of Object.keys(timerSlot)) {\n if (timerSlot[key]?.timeout)\n clearTimeout(timerSlot[key].timeout);\n }\n delete element[CONTEXT_TIMER];\n }\n for (const handler of handlers) {\n // Clean up wrapped method\n const wrappedMethodName = `__wrapped_${handler.methodName}`;\n delete element[wrappedMethodName];\n }\n // Unregister from Context if available\n const ctx = element[NAVIGATION_CONTEXT_INSTANCE];\n if (ctx && typeof ctx[CONTEXT_UNREGISTER] === 'function') {\n ctx[CONTEXT_UNREGISTER](element);\n }\n delete element[NAVIGATION_CONTEXT_INSTANCE];\n delete element[CONTEXT_CALLED];\n}\n\n/**\n * @render and @styles decorators for Snice v3.0.0\n * Provides automatic differential rendering on property changes\n */\n/**\n * When true, render errors are rethrown instead of logged, so tests and dev\n * environments fail loudly rather than leaving the element silently stale.\n * Production default is false (log and keep the previous DOM).\n */\nlet strictRenderErrors = false;\nfunction setStrictRenderErrors(value) {\n strictRenderErrors = value;\n}\n/**\n * Ensure the element has a pending `rendered` promise. Called whenever a\n * render is requested; resolved by performRender once the render commits.\n */\nfunction ensureRenderedPromise(element) {\n if (!element[RENDERED_RESOLVE]) {\n element[RENDERED_PROMISE] = new Promise((resolve) => {\n element[RENDERED_RESOLVE] = resolve;\n });\n }\n}\n/** Resolve the element's pending `rendered` promise, if any. */\nfunction resolveRendered(element) {\n const resolve = element[RENDERED_RESOLVE];\n if (resolve) {\n element[RENDERED_RESOLVE] = null;\n resolve();\n }\n}\n/**\n * Global render scheduler for microtask batching\n * Batches multiple property changes into a single render\n */\nclass RenderScheduler {\n constructor() {\n this.pending = new Set();\n this.scheduled = false;\n }\n /**\n * Schedule an element for rendering\n * Batches renders in a microtask unless sync option is enabled\n */\n schedule(element, options) {\n // Sync rendering - execute immediately\n if (options.sync) {\n performRender(element, options);\n return;\n }\n // Async rendering - batch in microtask\n this.pending.add(element);\n if (!this.scheduled) {\n this.scheduled = true;\n queueMicrotask(() => this.flush());\n }\n }\n /**\n * Flush all pending renders\n */\n flush() {\n const elements = Array.from(this.pending);\n this.pending.clear();\n this.scheduled = false;\n for (const element of elements) {\n // Skip elements that were disconnected between scheduling and flush, but\n // remember the dropped render so reconnect can replay it — otherwise the\n // shadow DOM stays stale for a property changed while detached. The flag\n // lives on the element, so it's GC'd with it (no leak if never reattached).\n if (!element.isConnected) {\n element[PENDING_RECONNECT_RENDER] = true;\n continue;\n }\n const options = element[RENDER_OPTIONS] || {};\n performRender(element, options);\n }\n }\n /** Remove a disconnected element from the queue */\n remove(element) {\n this.pending.delete(element);\n }\n}\nconst renderScheduler = new RenderScheduler();\nfunction hasRendered(element) {\n return Object.prototype.hasOwnProperty.call(element, RENDER_INSTANCE);\n}\nfunction flushRenderCallbacks(element) {\n const callbacks = element[RENDER_CALLBACKS];\n if (!callbacks || callbacks.length === 0)\n return;\n const cbs = [...callbacks];\n element[RENDER_CALLBACKS] = [];\n cbs.forEach(cb => cb());\n}\n/**\n * Backstop against a render() that mutates an observed property, which makes\n * the property setter request another render from inside the current one. In\n * `sync` mode that re-enters performRender synchronously and, unchecked,\n * recurses to a stack overflow. The counter caps synchronous nesting and turns\n * a silent crash into an actionable error. Normal renders never nest (child\n * renders defer to a microtask), so this stays at depth 1 in the common case.\n *\n * The depth is tracked PER ELEMENT (on RENDER_DEPTH), not globally: a runaway\n * component must not consume a shared budget and reject an unrelated component\n * that happens to render inside its call stack.\n */\nconst MAX_RENDER_DEPTH = 50;\n/**\n * Perform the actual render of an element\n */\nfunction performRender(element, options, precomputedResult) {\n const hasPrecomputedResult = arguments.length >= 3;\n const renderMethod = element[RENDER_METHOD];\n if (!renderMethod) {\n resolveRendered(element);\n return;\n }\n // If once is true and we've already rendered, skip\n if (options.once && hasRendered(element)) {\n resolveRendered(element);\n return;\n }\n const depth = (element[RENDER_DEPTH] ?? 0);\n if (depth >= MAX_RENDER_DEPTH) {\n const tag = element.tagName ? element.tagName.toLowerCase() : 'element';\n console.error(`snice: maximum render depth (${MAX_RENDER_DEPTH}) exceeded for <${tag}>. ` +\n `render() is mutating an observed property, causing an infinite render loop.`);\n resolveRendered(element);\n return;\n }\n element[RENDER_DEPTH] = depth + 1;\n try {\n const result = hasPrecomputedResult\n ? precomputedResult\n : renderMethod.call(element);\n const renderRoot = ensureRenderRoot(element);\n // Non-differential rendering (string)\n if (options.differential === false) {\n if (typeof result !== 'string') {\n console.warn('Render method with differential: false must return a string');\n return;\n }\n const template = document.createElement('template');\n template.innerHTML = result;\n const instance = element[RENDER_INSTANCE];\n instance?.clear();\n const removable = Array.from(renderRoot.childNodes).filter(node => !(node.nodeType === Node.ELEMENT_NODE &&\n node.tagName === 'STYLE' &&\n node.hasAttribute('data-snice-style')));\n for (const node of removable)\n node.remove();\n renderRoot.appendChild(template.content);\n // A present, null render instance records a successful string render so\n // `once` works without pretending the string tree is a TemplateInstance.\n element[RENDER_INSTANCE] = null;\n flushRenderCallbacks(element);\n return;\n }\n // Differential rendering (template)\n if (!isTemplateResult(result)) {\n console.warn('Render method must return html`` template result');\n return;\n }\n let instance = element[RENDER_INSTANCE];\n if (instance && instance.isSameTemplate(result.strings)) {\n instance.update(result.values);\n flushRenderCallbacks(element);\n return;\n }\n const nextInstance = new TemplateInstance(result);\n const nextFragment = nextInstance.renderFragment();\n // Commit while detached first. A malformed binding can then fail without\n // exposing a half-updated tree. Connection-aware parts are paired with\n // reconnected() immediately after the successful mount.\n try {\n nextInstance.update(result.values);\n }\n catch (error) {\n nextInstance.clear();\n throw error;\n }\n // Park the previous tree without disposing it, mount the prepared tree,\n // then run connection hooks. If reconnecting a listener or async part\n // fails, restore the still-live previous tree instead of leaving a\n // partially mounted replacement behind.\n const previousFragment = document.createDocumentFragment();\n for (const child of Array.from(renderRoot.childNodes)) {\n if (child.nodeType === Node.ELEMENT_NODE &&\n child.tagName === 'STYLE' &&\n child.hasAttribute('data-snice-style'))\n continue;\n previousFragment.appendChild(child);\n }\n renderRoot.appendChild(nextFragment);\n try {\n if (element.isConnected)\n nextInstance.reconnected();\n }\n catch (error) {\n try {\n nextInstance.clear();\n }\n catch (cleanupError) {\n console.error('snice: failed to clean up a rejected render tree:', cleanupError);\n }\n for (const child of Array.from(renderRoot.childNodes)) {\n if (child.nodeType === Node.ELEMENT_NODE &&\n child.tagName === 'STYLE' &&\n child.hasAttribute('data-snice-style'))\n continue;\n child.remove();\n }\n renderRoot.appendChild(previousFragment);\n throw error;\n }\n element[RENDER_INSTANCE] = nextInstance;\n let cleanupError;\n try {\n instance?.clear();\n }\n catch (error) {\n cleanupError = error;\n }\n flushRenderCallbacks(element);\n if (cleanupError)\n throw cleanupError;\n }\n catch (error) {\n if (strictRenderErrors)\n throw error;\n console.error('Error rendering element:', error);\n }\n finally {\n element[RENDER_DEPTH] = depth;\n resolveRendered(element);\n }\n}\n/** Commit immediately using the element's configured render options. */\nfunction renderElementNow(element) {\n ensureRenderedPromise(element);\n const options = element[RENDER_OPTIONS] || {};\n performRender(element, { ...options, once: false });\n}\n/**\n * Request a render for an element\n * Respects debounce/throttle/once/sync options\n * @param immediate - Force immediate render (used for initial render)\n */\nfunction requestRender(element, immediate = false) {\n const options = element[RENDER_OPTIONS] || {};\n // Handle once option\n if (options.once && hasRendered(element)) {\n if (element.isConnected)\n reconnectRenderTree(element);\n return;\n }\n // Arm the `rendered` promise: it resolves when this request's render\n // commits (immediately below for sync/immediate, later for batched/\n // debounced/throttled renders).\n ensureRenderedPromise(element);\n // Force immediate render (for initial render)\n if (immediate) {\n performRender(element, options);\n return;\n }\n // Handle debounce\n if (options.debounce !== undefined && options.debounce > 0) {\n if (!element[RENDER_TIMERS]) {\n element[RENDER_TIMERS] = {};\n }\n clearTimeout(element[RENDER_TIMERS].debounce);\n element[RENDER_TIMERS].debounce = setTimeout(() => {\n element[RENDER_TIMERS].debounce = null;\n renderScheduler.schedule(element, options);\n }, options.debounce);\n return;\n }\n // Handle throttle\n if (options.throttle !== undefined && options.throttle > 0) {\n if (!element[RENDER_TIMERS]) {\n element[RENDER_TIMERS] = { lastThrottle: 0 };\n }\n const timers = element[RENDER_TIMERS];\n const now = Date.now();\n if (timers.lastThrottle === 0 || now - timers.lastThrottle >= options.throttle) {\n timers.lastThrottle = now;\n renderScheduler.schedule(element, options);\n return;\n }\n if (!timers.throttleTimer) {\n const remaining = options.throttle - (now - timers.lastThrottle);\n timers.throttleTimer = setTimeout(() => {\n timers.throttleTimer = null;\n timers.lastThrottle = Date.now();\n renderScheduler.schedule(element, options);\n }, remaining);\n }\n return;\n }\n // Normal rendering (with microtask batching unless sync)\n renderScheduler.schedule(element, options);\n}\n/**\n * Clear any pending debounce/throttle render timers on an element (e.g. on\n * disconnect, so they don't fire on a dead element and retain it until they\n * expire). Returns true if a render was actually pending, so the caller can\n * arrange a replay on reconnect via PENDING_RECONNECT_RENDER.\n */\nfunction clearRenderTimers(element) {\n const timers = element[RENDER_TIMERS];\n if (!timers)\n return false;\n let hadPending = false;\n if (timers.debounce) {\n clearTimeout(timers.debounce);\n timers.debounce = null;\n hadPending = true;\n }\n if (timers.throttleTimer) {\n clearTimeout(timers.throttleTimer);\n timers.throttleTimer = null;\n hadPending = true;\n }\n // Deliberately do NOT reset timers.lastThrottle: a plain DOM move is a\n // disconnect+reconnect, and zeroing the cooldown would let the next render\n // fire inside the throttle window. Preserving it keeps throttle honest\n // across moves; on a true disconnect the element is discarded anyway.\n return hadPending;\n}\n/** Pause connection-aware render parts while an element is detached. */\nfunction disconnectRenderTree(element) {\n const instance = element[RENDER_INSTANCE];\n // A host disconnection is not the same thing as parking a conditional\n // branch. The shadow/light render tree still belongs to the host, so native\n // event listeners remain usable on retained node references. Async iteration\n // is paused, and parked branches continue to detach their listeners through\n // the ordinary Part lifecycle.\n instance?.disconnected(true);\n}\n/** Resume connection-aware render parts when an existing tree reconnects. */\nfunction reconnectRenderTree(element) {\n const instance = element[RENDER_INSTANCE];\n instance?.reconnected();\n}\n/**\n * @render decorator for component rendering\n *\n * Marks a method as the render method for the component.\n * The method should return html`...` template.\n * Automatically re-renders when properties change (unless once: true).\n *\n * @example\n * ```typescript\n * @render()\n * renderContent() {\n * return html`<div>${this.count}</div>`;\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Debounced rendering\n * @render({ debounce: 100 })\n * renderContent() {\n * return html`<div>${this.searchTerm}</div>`;\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Render only once (manual re-renders only)\n * @render({ once: true })\n * renderContent() {\n * return html`<div>Static content</div>`;\n * }\n * ```\n */\nfunction render(options = {}) {\n return function (originalMethod, context) {\n context.name;\n context.addInitializer(function () {\n // Store the render method and options\n this[RENDER_METHOD] = originalMethod;\n this[RENDER_OPTIONS] = options;\n });\n // Return wrapped method that triggers re-render when called manually\n return function (...args) {\n // Call original method to get the template\n const result = originalMethod.apply(this, args);\n // Always render when method is called manually (even if once: true)\n // Force immediate render to bypass all options, pass precomputed result to avoid calling method twice\n const configured = this[RENDER_OPTIONS] || options;\n performRender(this, { ...configured, once: false }, result);\n return result;\n };\n };\n}\n/**\n * @styles decorator for component styles\n *\n * Marks a method as the styles method for the component.\n * The method should return css`...` template.\n * Styles are applied once when the component is connected.\n *\n * @example\n * ```typescript\n * @styles()\n * styles() {\n * return css`:host { display: block; }`;\n * }\n * ```\n */\nfunction styles() {\n return function (originalMethod, context) {\n context.addInitializer(function () {\n // Collect parent styles methods before overwriting with child's\n if (this[STYLES_METHOD] && !this[PARENT_STYLES_METHODS]) {\n this[PARENT_STYLES_METHODS] = [this[STYLES_METHOD]];\n }\n else if (this[STYLES_METHOD] && this[PARENT_STYLES_METHODS]) {\n this[PARENT_STYLES_METHODS].push(this[STYLES_METHOD]);\n }\n this[STYLES_METHOD] = originalMethod;\n });\n return originalMethod;\n };\n}\n/**\n * Apply styles to an element\n * Called during element initialization\n */\nfunction applyStyles(element) {\n const stylesMethod = element[STYLES_METHOD];\n const staticResults = [];\n const constructors = [];\n let constructor = element.constructor;\n while (constructor && constructor !== HTMLElement && constructor !== Function.prototype) {\n constructors.unshift(constructor);\n constructor = Object.getPrototypeOf(constructor);\n }\n for (const current of constructors) {\n if (!Object.prototype.hasOwnProperty.call(current, 'styles'))\n continue;\n const value = current.styles;\n const values = Array.isArray(value) ? value : [value];\n for (const result of values) {\n if (isCSSResult(result))\n staticResults.push(result);\n else\n console.warn('Static styles must be a css`` result or an array of css`` results');\n }\n }\n if (!stylesMethod && staticResults.length === 0)\n return;\n // Only apply once\n if (element[STYLES_APPLIED])\n return;\n element[STYLES_APPLIED] = true;\n try {\n // Collect all CSS results: parent styles first, then child styles\n const allResults = [...staticResults];\n const parentMethods = element[PARENT_STYLES_METHODS];\n if (parentMethods) {\n for (const method of parentMethods) {\n const r = method.call(element);\n if (isCSSResult(r))\n allResults.push(r);\n }\n }\n if (stylesMethod) {\n const result = stylesMethod.call(element);\n if (!isCSSResult(result)) {\n console.warn('Styles method must return css`` template result');\n return;\n }\n allResults.push(result);\n }\n const renderRoot = ensureRenderRoot(element);\n // Retain matching framework-owned style elements instead of adding a\n // duplicate stylesheet during a repeated setup pass.\n const existingStyles = Array.from(renderRoot.childNodes).filter(node => node.nodeType === Node.ELEMENT_NODE &&\n node.tagName === 'STYLE' &&\n node.hasAttribute('data-snice-style'));\n if (existingStyles.length === allResults.length &&\n existingStyles.every((style, index) => style.textContent === allResults[index].cssText)) {\n return;\n }\n for (const style of existingStyles)\n style.remove();\n // Prefer constructable stylesheets\n if (renderRoot instanceof ShadowRoot && allResults.every(r => !!r.styleSheet) && 'adoptedStyleSheets' in renderRoot) {\n try {\n renderRoot.adoptedStyleSheets = allResults.map(r => r.styleSheet);\n return;\n }\n catch {\n // A stylesheet constructed in another Window/Document realm cannot be\n // adopted here. Fall through to equivalent <style> elements.\n }\n }\n // Fallback — one <style> tag per stylesheet, preserving cascade order.\n // Marked so the template-switch cleanup keeps these (framework styles) but\n // still removes template-emitted <style> tags (which would otherwise pile up).\n for (const r of allResults) {\n const style = document.createElement('style');\n style.setAttribute('data-snice-style', '');\n style.textContent = r.cssText;\n renderRoot.appendChild(style);\n }\n }\n catch (error) {\n console.error('Error applying styles:', error);\n }\n}\n\n// @dispatch decorator - auto-dispatches custom events from method return values\n/**\n * Decorator that automatically dispatches a custom event after a method is called.\n * The return value of the method becomes the event detail.\n *\n * @param eventName The name of the event to dispatch\n * @param options Optional configuration extending EventInit\n */\nfunction dispatch(eventName, options) {\n return function (originalMethod, _context) {\n return function (...args) {\n // Create timing wrappers for dispatch (per-instance)\n if (!this[DISPATCH_TIMERS]) {\n this[DISPATCH_TIMERS] = new Map();\n }\n const timerKey = `${eventName}_${_context.name}`;\n if (!this[DISPATCH_TIMERS].has(timerKey)) {\n this[DISPATCH_TIMERS].set(timerKey, {\n debounceTimeout: null,\n throttleLastCall: 0,\n throttleTimeout: null\n });\n }\n const timers = this[DISPATCH_TIMERS].get(timerKey);\n // Call the original method with preserved this context\n const result = originalMethod.apply(this, args);\n // Helper to dispatch the event\n const doDispatch = (detail) => {\n // Skip dispatch if result is undefined and dispatchOnUndefined is false\n if (detail === undefined && options?.dispatchOnUndefined === false) {\n return;\n }\n // Create event with spread operator for options\n const event = new CustomEvent(eventName, {\n bubbles: true, // Default to true for component events\n composed: true, // Allow crossing shadow DOM boundaries\n ...options, // Spread all EventInit options\n detail\n });\n // Resolve scope target. Default is `this` (host element).\n // Explicit scope dispatches the event on another target — useful for\n // 'global' bus events on document, or routing through an ancestor.\n if (options?.scope !== undefined) {\n const target = resolveScope(this, options.scope);\n if (!target) {\n console.warn(`[snice/@dispatch] scope did not resolve for \"${eventName}\" — event not dispatched.`);\n return;\n }\n target.dispatchEvent(event);\n return;\n }\n this.dispatchEvent(event);\n };\n // Helper to handle timed dispatch\n const timedDispatch = (detail) => {\n if (options?.debounce) {\n clearTimeout(timers.debounceTimeout);\n timers.debounceTimeout = setTimeout(() => doDispatch(detail), options.debounce);\n return;\n }\n if (!options?.throttle) {\n doDispatch(detail);\n return;\n }\n const now = Date.now();\n const remaining = options.throttle - (now - timers.throttleLastCall);\n if (remaining <= 0) {\n clearTimeout(timers.throttleTimeout);\n timers.throttleLastCall = now;\n doDispatch(detail);\n return;\n }\n // Record the LATEST detail so the trailing dispatch carries fresh\n // data, not the first-suppressed-call detail captured by closure.\n timers.latestDetail = detail;\n if (!timers.throttleTimeout) {\n timers.throttleTimeout = setTimeout(() => {\n timers.throttleLastCall = Date.now();\n timers.throttleTimeout = null;\n const d = timers.latestDetail;\n timers.latestDetail = undefined;\n doDispatch(d);\n }, remaining);\n }\n };\n // Handle async methods\n if (result instanceof Promise) {\n return result.then((resolvedResult) => {\n timedDispatch(resolvedResult);\n return resolvedResult;\n });\n }\n // Sync method\n timedDispatch(result);\n return result;\n };\n };\n}\n/**\n * Clear any pending debounce/throttle dispatch timers on an instance (e.g. on\n * disconnect, so a queued event doesn't fire into a detached node). A dispatch\n * is a one-shot signal, so pending ones are dropped, not replayed.\n */\nfunction clearDispatchTimers(instance) {\n const timers = instance[DISPATCH_TIMERS];\n if (!timers)\n return;\n for (const t of timers.values()) {\n if (t.debounceTimeout)\n clearTimeout(t.debounceTimeout);\n if (t.throttleTimeout)\n clearTimeout(t.throttleTimeout);\n t.debounceTimeout = null;\n t.throttleTimeout = null;\n t.throttleLastCall = 0;\n t.latestDetail = undefined;\n }\n}\n\n/**\n * Method decorators for common patterns\n * @debounce, @throttle, @once, @memoize\n */\nconst DEBOUNCE_TIMERS = getSymbol('debounce-timers');\nconst THROTTLE_TIMERS = getSymbol('throttle-timers');\nconst ONCE_CALLED = getSymbol('once-called');\nconst MEMOIZE_CACHE = getSymbol('memoize-cache');\n/**\n * @debounce decorator - delays function execution until after wait time has elapsed\n * since the last invocation\n *\n * @param wait - Time to wait in milliseconds (default: 300)\n * @param options - Debounce options\n * @param options.leading - Invoke on the leading edge (default: false)\n * @param options.trailing - Invoke on the trailing edge (default: true)\n * @param options.maxWait - Maximum time to wait before invoking (default: undefined)\n *\n * @example\n * ```typescript\n * @element('search-input')\n * class SearchInput extends HTMLElement {\n * @debounce(500)\n * handleSearch(query: string) {\n * // Only called 500ms after last keystroke\n * fetch(`/api/search?q=${query}`);\n * }\n * }\n * ```\n */\nfunction debounce(wait = 300, options = {}) {\n const { leading = false, trailing = true, maxWait } = options;\n return function (originalMethod, context) {\n const methodName = context.name;\n return function (...args) {\n if (!this[DEBOUNCE_TIMERS]) {\n this[DEBOUNCE_TIMERS] = {};\n }\n const timers = this[DEBOUNCE_TIMERS];\n const timerKey = methodName;\n // Clear existing timer\n if (timers[timerKey]) {\n clearTimeout(timers[timerKey].timeout);\n }\n // Track when debounce started for maxWait\n const now = Date.now();\n const isFirstCall = !timers[timerKey];\n const startTime = isFirstCall ? now : timers[timerKey].startTime;\n // Check if maxWait exceeded\n const shouldInvokeFromMaxWait = maxWait !== undefined && now - startTime >= maxWait;\n // Leading edge invocation\n if (leading && isFirstCall) {\n const result = originalMethod.apply(this, args);\n timers[timerKey] = {\n timeout: null,\n startTime,\n lastArgs: args,\n };\n return result;\n }\n // Set new timer for trailing edge\n const timeout = setTimeout(() => {\n if (trailing || shouldInvokeFromMaxWait) {\n originalMethod.apply(this, timers[timerKey].lastArgs);\n }\n delete timers[timerKey];\n }, shouldInvokeFromMaxWait ? 0 : wait);\n timers[timerKey] = {\n timeout,\n startTime,\n lastArgs: args,\n };\n };\n };\n}\n/**\n * @throttle decorator - ensures function is called at most once per specified time period\n *\n * @param wait - Time to wait in milliseconds (default: 300)\n * @param options - Throttle options\n * @param options.leading - Invoke on the leading edge (default: true)\n * @param options.trailing - Invoke on the trailing edge (default: true)\n *\n * @example\n * ```typescript\n * @element('scroll-tracker')\n * class ScrollTracker extends HTMLElement {\n * @throttle(100)\n * handleScroll(e: Event) {\n * // Called at most once every 100ms\n * this.updateScrollPosition();\n * }\n * }\n * ```\n */\nfunction throttle(wait = 300, options = {}) {\n const { leading = true, trailing = true } = options;\n return function (originalMethod, context) {\n const methodName = context.name;\n return function (...args) {\n if (!this[THROTTLE_TIMERS]) {\n this[THROTTLE_TIMERS] = {};\n }\n const timers = this[THROTTLE_TIMERS];\n const timerKey = methodName;\n const now = Date.now();\n // First call\n if (!timers[timerKey]) {\n if (leading)\n originalMethod.apply(this, args);\n timers[timerKey] = { lastInvoke: now, timeout: null, lastArgs: args };\n if (trailing && !leading) {\n timers[timerKey].timeout = setTimeout(() => {\n originalMethod.apply(this, timers[timerKey].lastArgs);\n delete timers[timerKey];\n }, wait);\n }\n return;\n }\n // Subsequent calls\n const timeSinceLastInvoke = now - timers[timerKey].lastInvoke;\n timers[timerKey].lastArgs = args;\n if (timers[timerKey].timeout) {\n clearTimeout(timers[timerKey].timeout);\n }\n // Enough time passed — invoke immediately\n if (timeSinceLastInvoke >= wait) {\n originalMethod.apply(this, args);\n timers[timerKey].lastInvoke = now;\n return;\n }\n // Set up trailing call\n if (trailing) {\n const remaining = wait - timeSinceLastInvoke;\n timers[timerKey].timeout = setTimeout(() => {\n originalMethod.apply(this, timers[timerKey].lastArgs);\n timers[timerKey].lastInvoke = Date.now();\n timers[timerKey].timeout = null;\n }, remaining);\n }\n };\n };\n}\n/**\n * @once decorator - ensures function is only called once\n * Subsequent calls return the result of the first call\n *\n * @param perInstance - If true, function can be called once per instance (default: true)\n * If false, function can only be called once globally across all instances\n *\n * @example\n * ```typescript\n * @element('data-loader')\n * class DataLoader extends HTMLElement {\n * @once()\n * async loadData() {\n * // Only loads data once, even if called multiple times\n * const data = await fetch('/api/data');\n * return data.json();\n * }\n * }\n * ```\n */\nfunction once(perInstance = true) {\n let globalCalled = false;\n let globalResult;\n return function (originalMethod, context) {\n const methodName = context.name;\n return function (...args) {\n // Per-instance tracking\n if (perInstance) {\n if (!this[ONCE_CALLED])\n this[ONCE_CALLED] = {};\n if (!this[ONCE_CALLED][methodName]) {\n this[ONCE_CALLED][methodName] = {\n called: true,\n result: originalMethod.apply(this, args),\n };\n }\n return this[ONCE_CALLED][methodName].result;\n }\n // Global tracking\n if (!globalCalled) {\n globalCalled = true;\n globalResult = originalMethod.apply(this, args);\n }\n return globalResult;\n };\n };\n}\n/**\n * @memoize decorator - caches function results based on arguments\n * Uses JSON.stringify for argument comparison by default\n *\n * @param options - Memoization options\n * @param options.keyGenerator - Custom function to generate cache key from arguments\n * @param options.maxSize - Maximum cache size (default: 100)\n * @param options.ttl - Time to live in milliseconds (default: undefined - no expiration)\n *\n * @example\n * ```typescript\n * @element('calculator')\n * class Calculator extends HTMLElement {\n * @memoize({ maxSize: 50 })\n * fibonacci(n: number): number {\n * // Results are cached, subsequent calls with same n are instant\n * if (n <= 1) return n;\n * return this.fibonacci(n - 1) + this.fibonacci(n - 2);\n * }\n * }\n * ```\n */\nfunction memoize(options = {}) {\n const { keyGenerator = (...args) => JSON.stringify(args), maxSize = 100, ttl } = options;\n return function (originalMethod, context) {\n const methodName = context.name;\n return function (...args) {\n if (!this[MEMOIZE_CACHE]) {\n this[MEMOIZE_CACHE] = {};\n }\n if (!this[MEMOIZE_CACHE][methodName]) {\n this[MEMOIZE_CACHE][methodName] = new Map();\n }\n const cache = this[MEMOIZE_CACHE][methodName];\n const key = keyGenerator(...args);\n // Check if cached\n if (cache.has(key)) {\n const cached = cache.get(key);\n const expired = ttl !== undefined && (Date.now() - cached.timestamp) > ttl;\n if (expired) {\n cache.delete(key);\n }\n else {\n return cached.value;\n }\n }\n // Compute result\n const result = originalMethod.apply(this, args);\n // Store in cache\n cache.set(key, {\n value: result,\n timestamp: Date.now(),\n });\n // Enforce max size (LRU - delete oldest)\n if (cache.size > maxSize) {\n const firstKey = cache.keys().next().value;\n cache.delete(firstKey);\n }\n return result;\n };\n };\n}\n/**\n * Clear all debounce timers for an instance\n * Useful in cleanup/disconnectedCallback\n */\nfunction clearDebounceTimers(instance) {\n if (instance[DEBOUNCE_TIMERS]) {\n for (const timerKey in instance[DEBOUNCE_TIMERS]) {\n if (instance[DEBOUNCE_TIMERS][timerKey]?.timeout) {\n clearTimeout(instance[DEBOUNCE_TIMERS][timerKey].timeout);\n }\n }\n instance[DEBOUNCE_TIMERS] = {};\n }\n}\n/**\n * Clear all throttle timers for an instance\n * Useful in cleanup/disconnectedCallback\n */\nfunction clearThrottleTimers(instance) {\n if (instance[THROTTLE_TIMERS]) {\n for (const timerKey in instance[THROTTLE_TIMERS]) {\n if (instance[THROTTLE_TIMERS][timerKey]?.timeout) {\n clearTimeout(instance[THROTTLE_TIMERS][timerKey].timeout);\n }\n }\n instance[THROTTLE_TIMERS] = {};\n }\n}\n/**\n * Clear memoize cache for an instance\n */\nfunction clearMemoizeCache(instance, methodName) {\n if (instance[MEMOIZE_CACHE]) {\n if (methodName) {\n delete instance[MEMOIZE_CACHE][methodName];\n }\n else {\n instance[MEMOIZE_CACHE] = {};\n }\n }\n}\n/**\n * Reset once-called state for an instance\n */\nfunction resetOnce(instance, methodName) {\n if (instance[ONCE_CALLED]) {\n if (methodName) {\n delete instance[ONCE_CALLED][methodName];\n }\n else {\n instance[ONCE_CALLED] = {};\n }\n }\n}\n\nfunction isPlainObject(value) {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\nfunction descriptorsEqual(first, second) {\n if (!first || !second)\n return first === second;\n const firstIsData = 'value' in first || 'writable' in first;\n const secondIsData = 'value' in second || 'writable' in second;\n return firstIsData === secondIsData &&\n first.configurable === second.configurable &&\n first.enumerable === second.enumerable &&\n (!firstIsData || (first.writable === second.writable &&\n Object.is(first.value, second.value))) &&\n (firstIsData || (first.get === second.get &&\n first.set === second.set));\n}\nfunction invariantValue(target, property) {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, property);\n if (!descriptor || descriptor.configurable)\n return { locked: false, value: undefined };\n if ('value' in descriptor && descriptor.writable === false) {\n return { locked: true, value: descriptor.value };\n }\n if (!('value' in descriptor) && descriptor.get === undefined) {\n return { locked: true, value: undefined };\n }\n return { locked: false, value: undefined };\n}\n/**\n * Wrap mutable collection/object state so nested writes can invalidate a\n * component without requiring a replacement assignment.\n */\nfunction createDeepReactive(value, changed) {\n if (!value || typeof value !== 'object')\n return value;\n const cache = new WeakMap();\n const rawByProxy = new WeakMap();\n const unwrap = (input) => input && typeof input === 'object'\n ? rawByProxy.get(input) || input\n : input;\n const wrap = (input) => {\n if (!input || typeof input !== 'object')\n return input;\n if (cache.has(input))\n return cache.get(input);\n if (input instanceof Map) {\n let proxy;\n const methods = new Map();\n proxy = new Proxy(input, {\n get(target, property) {\n const invariant = invariantValue(target, property);\n if (invariant.locked)\n return invariant.value;\n if (methods.has(property))\n return methods.get(property);\n let method;\n if (property === 'set')\n method = (key, next) => {\n key = unwrap(key);\n next = unwrap(next);\n const existed = target.has(key);\n const previous = target.get(key);\n target.set(key, next);\n if (!existed || !Object.is(previous, next))\n changed();\n return proxy;\n };\n else if (property === 'delete')\n method = (key) => {\n key = unwrap(key);\n const deleted = target.delete(key);\n if (deleted)\n changed();\n return deleted;\n };\n else if (property === 'clear')\n method = () => {\n if (target.size === 0)\n return;\n target.clear();\n changed();\n };\n else if (property === 'get')\n method = (key) => wrap(target.get(unwrap(key)));\n else if (property === 'has')\n method = (key) => target.has(unwrap(key));\n else if (property === 'forEach')\n method = (callback, thisArg) => target.forEach((entryValue, key) => callback.call(thisArg, wrap(entryValue), wrap(key), proxy));\n else if (property === 'values')\n method = function* () {\n for (const entryValue of target.values())\n yield wrap(entryValue);\n };\n else if (property === 'keys')\n method = function* () {\n for (const key of target.keys())\n yield wrap(key);\n };\n else if (property === 'entries' || property === Symbol.iterator)\n method = function* () {\n for (const [key, entryValue] of target.entries())\n yield [wrap(key), wrap(entryValue)];\n };\n else {\n const value = Reflect.get(target, property, target);\n if (typeof value !== 'function')\n return value;\n if (property === 'constructor')\n return value;\n method = value.bind(target);\n }\n methods.set(property, method);\n return method;\n }\n });\n cache.set(input, proxy);\n rawByProxy.set(proxy, input);\n return proxy;\n }\n if (input instanceof Set) {\n let proxy;\n const methods = new Map();\n proxy = new Proxy(input, {\n get(target, property) {\n const invariant = invariantValue(target, property);\n if (invariant.locked)\n return invariant.value;\n if (methods.has(property))\n return methods.get(property);\n let method;\n if (property === 'add')\n method = (entryValue) => {\n entryValue = unwrap(entryValue);\n const existed = target.has(entryValue);\n target.add(entryValue);\n if (!existed)\n changed();\n return proxy;\n };\n else if (property === 'delete')\n method = (entryValue) => {\n entryValue = unwrap(entryValue);\n const deleted = target.delete(entryValue);\n if (deleted)\n changed();\n return deleted;\n };\n else if (property === 'clear')\n method = () => {\n if (target.size === 0)\n return;\n target.clear();\n changed();\n };\n else if (property === 'has')\n method = (entryValue) => target.has(unwrap(entryValue));\n else if (property === 'forEach')\n method = (callback, thisArg) => target.forEach(entryValue => {\n const wrapped = wrap(entryValue);\n callback.call(thisArg, wrapped, wrapped, proxy);\n });\n else if (property === 'values' || property === 'keys' || property === Symbol.iterator)\n method = function* () {\n for (const entryValue of target.values())\n yield wrap(entryValue);\n };\n else if (property === 'entries')\n method = function* () {\n for (const entryValue of target.values()) {\n const wrapped = wrap(entryValue);\n yield [wrapped, wrapped];\n }\n };\n else {\n const value = Reflect.get(target, property, target);\n if (typeof value !== 'function')\n return value;\n if (property === 'constructor')\n return value;\n method = value.bind(target);\n }\n methods.set(property, method);\n return method;\n }\n });\n cache.set(input, proxy);\n rawByProxy.set(proxy, input);\n return proxy;\n }\n if (!Array.isArray(input) && !isPlainObject(input))\n return input;\n const proxy = new Proxy(input, {\n get(target, property, receiver) {\n const invariant = invariantValue(target, property);\n return invariant.locked\n ? invariant.value\n : wrap(Reflect.get(target, property, receiver));\n },\n set(target, property, next, receiver) {\n const previous = Reflect.get(target, property, receiver);\n next = unwrap(next);\n // Write directly to the wrapped target. Passing the proxy as the\n // receiver re-enters defineProperty for an ordinary assignment and\n // would report the same mutation twice.\n const result = Reflect.set(target, property, next);\n if (result && !Object.is(previous, next))\n changed();\n return result;\n },\n deleteProperty(target, property) {\n const existed = Object.prototype.hasOwnProperty.call(target, property);\n const result = Reflect.deleteProperty(target, property);\n if (result && existed)\n changed();\n return result;\n },\n defineProperty(target, property, descriptor) {\n const previous = Reflect.getOwnPropertyDescriptor(target, property);\n const nextDescriptor = 'value' in descriptor\n ? { ...descriptor, value: unwrap(descriptor.value) }\n : descriptor;\n const result = Reflect.defineProperty(target, property, nextDescriptor);\n const current = result ? Reflect.getOwnPropertyDescriptor(target, property) : previous;\n if (result && !descriptorsEqual(previous, current))\n changed();\n return result;\n }\n });\n cache.set(input, proxy);\n rawByProxy.set(proxy, input);\n return proxy;\n };\n return wrap(value);\n}\n\n/**\n * Applies core element functionality to a constructor\n * This is shared between @element and @page decorators\n */\nfunction applyElementFunctionality(constructor) {\n // Mark as element class for channel decorator detection\n constructor.prototype[IS_ELEMENT_CLASS] = true;\n // Add controller property to all elements\n const originalConnectedCallback = constructor.prototype.connectedCallback;\n const originalDisconnectedCallback = constructor.prototype.disconnectedCallback;\n const originalAttributeChangedCallback = constructor.prototype.attributeChangedCallback;\n // Add 'controller' and all reflected properties to observed attributes\n const observedAttributes = constructor.observedAttributes || [];\n if (!observedAttributes.includes('controller')) {\n observedAttributes.push('controller');\n }\n // Add all properties to observed attributes (skip attribute: false)\n const properties = constructor[PROPERTIES];\n if (properties) {\n for (const [propName, propOptions] of properties) {\n if (propOptions.attribute === false)\n continue;\n const attributeName = getAttrName(propOptions, propName);\n if (!observedAttributes.includes(attributeName)) {\n observedAttributes.push(attributeName);\n }\n }\n }\n Object.defineProperty(constructor, 'observedAttributes', {\n get() { return observedAttributes; },\n configurable: true\n });\n // Add ready property - always returns a promise\n Object.defineProperty(constructor.prototype, 'ready', {\n get() {\n if (!this[READY_PROMISE]) {\n // Create a pending promise if not yet initialized\n this[READY_PROMISE] = new Promise((resolve) => {\n this[READY_RESOLVE] = resolve;\n });\n }\n return this[READY_PROMISE];\n },\n enumerable: true,\n configurable: true\n });\n // Add rendered property - resolves when the pending render (batched,\n // debounced, or throttled) has committed to the DOM; resolves\n // immediately when no render is pending.\n Object.defineProperty(constructor.prototype, 'rendered', {\n get() {\n return this[RENDERED_RESOLVE] ? this[RENDERED_PROMISE] : Promise.resolve();\n },\n enumerable: true,\n configurable: true\n });\n // Add controller property\n Object.defineProperty(constructor.prototype, 'controller', {\n get() {\n return this[CONTROLLER];\n },\n set(value) {\n const oldValue = this[CONTROLLER];\n this[CONTROLLER] = value;\n if (value === oldValue)\n return;\n if (value) {\n const label = typeof value === 'string' ? value : (value.name || '(anonymous controller class)');\n attachController(this, value).catch(error => {\n // Detached before ready — designed teardown, not a failure\n if (error?.name === 'ControllerAttachAborted') {\n console.debug(`Controller \"${label}\" attach aborted (element detached before ready)`);\n return;\n }\n // Registry misses only apply to string names — class references\n // never go through the registry.\n if (typeof value === 'string' && error?.message === `Controller \"${value}\" not found in registry`) {\n deferControllerAttachment(this, value);\n return;\n }\n console.error(`Failed to attach controller \"${label}\":`, error);\n });\n return;\n }\n if (oldValue) {\n detachController(this).catch(error => {\n console.error(`Failed to detach controller:`, error);\n });\n }\n },\n enumerable: true,\n configurable: true\n });\n constructor.prototype.connectedCallback = async function () {\n // If ready promise was already created (controller attached before connected), use existing resolve\n // Otherwise create the ready promise now\n if (!this[READY_PROMISE]) {\n this[READY_PROMISE] = new Promise((resolve) => {\n this[READY_RESOLVE] = resolve;\n });\n }\n // Only run initialization logic once, but re-establish handlers on reconnection\n if (this[INITIALIZED]) {\n try {\n reconnectRenderTree(this);\n }\n catch (error) {\n console.error(`Error reconnecting the render tree for ${this.tagName}:`, error);\n }\n // Re-establish handlers that get cleaned up on disconnect\n setupEventHandlers(this, this);\n setupResponseHandlers(this, this);\n setupContextHandler(this);\n // Re-establish observers that get cleaned up on disconnect\n try {\n setupObservers(this, this);\n }\n catch (error) {\n console.error(`Error setting up observers for ${this.tagName} on reconnection:`, error);\n }\n // Call user's connectedCallback\n if (originalConnectedCallback) {\n originalConnectedCallback.call(this);\n }\n // Fire @reconnect handlers — for components that wire long-lived\n // global listeners or subscriptions in @ready and need to re-establish\n // them on re-connection. @ready does NOT re-fire (deliberately, to\n // preserve once-only initialization semantics).\n const reconnectHandlers = constructor[RECONNECT_HANDLERS];\n if (reconnectHandlers) {\n for (const handler of reconnectHandlers) {\n try {\n const result = handler.method.call(this);\n if (result && typeof result.then === 'function') {\n result.catch(error => {\n console.error(`Error in @reconnect handler ${handler.methodName}:`, error);\n });\n }\n }\n catch (error) {\n console.error(`Error in @reconnect handler ${handler.methodName}:`, error);\n }\n }\n }\n // Replay a render that was dropped while disconnected. The scheduler\n // sets this flag when it skips a detached element, so a property changed\n // while detached still reaches the DOM on reattach. A plain move (no\n // pending render) leaves the flag unset, so we don't re-render needlessly.\n if (this[RENDER_METHOD] && this[PENDING_RECONNECT_RENDER]) {\n this[PENDING_RECONNECT_RENDER] = false;\n requestRender(this);\n }\n return;\n }\n // Mark that properties are being initialized from attributes\n // This allows property setters to work during initialization\n this[PROPERTIES_INITIALIZED] = true;\n // Initialize properties from attributes before rendering\n const properties = constructor[PROPERTIES];\n if (properties) {\n for (const [propName, propOptions] of properties) {\n if (propOptions.attribute === false)\n continue;\n const attributeName = getAttrName(propOptions, propName);\n if (!this.hasAttribute(attributeName))\n continue;\n const attrValue = this.getAttribute(attributeName);\n ensureSet(this, EXPLICITLY_SET_PROPERTIES).add(propName);\n if (propOptions.type === Boolean && attrValue === '') {\n this.setAttribute(attributeName, 'true');\n }\n this[propName] = parseAttributeValue(attrValue, propOptions);\n }\n }\n // Clear pre-init values for properties that have HTML attributes\n if (this[PRE_INIT_PROPERTY_VALUES]) {\n for (const [propName, propValue] of Array.from(this[PRE_INIT_PROPERTY_VALUES].entries())) {\n const propOptions = properties?.get(propName);\n const attributeName = getAttrName(propOptions || {}, propName);\n this[PRE_INIT_PROPERTY_VALUES].delete(propName);\n if (!this.hasAttribute(attributeName)) {\n this[propName] = propValue;\n }\n }\n delete this[PRE_INIT_PROPERTY_VALUES];\n }\n // Pick up a controller CLASS a template bound before this element was\n // defined. The binding parks the class instead of assigning the\n // property — a pre-upgrade assignment would have shadowed this accessor\n // with an own expando property. Attach directly rather than through the\n // `controller` accessor: some DOM implementations (happy-dom) invoke\n // connectedCallback on define without swapping the prototype, so the\n // accessor may not exist on this instance yet.\n if (this[PENDING_CONTROLLER_BINDING] !== undefined) {\n const pendingControllerClass = this[PENDING_CONTROLLER_BINDING];\n delete this[PENDING_CONTROLLER_BINDING];\n if (!this[CONTROLLER]) {\n this[CONTROLLER] = pendingControllerClass;\n const pendingLabel = pendingControllerClass?.name || '(anonymous controller class)';\n attachController(this, pendingControllerClass).catch((error) => {\n if (error?.name === 'ControllerAttachAborted') {\n console.debug(`Controller \"${pendingLabel}\" attach aborted (element detached before ready)`);\n return;\n }\n console.error(`Failed to attach controller \"${pendingLabel}\":`, error);\n });\n }\n }\n // Pick up a `controller` attribute set before connection. Real browsers\n // fire attributeChangedCallback on connect for all observed attrs that\n // already existed; happy-dom doesn't always, so we read it proactively.\n if (this.hasAttribute('controller') && !this[CONTROLLER]) {\n const controllerName = this.getAttribute('controller');\n if (controllerName)\n this.controller = controllerName;\n }\n applyStyles(this);\n setupEventHandlers(this, this);\n setupResponseHandlers(this, this);\n setupContextHandler(this);\n this[INITIALIZED] = true;\n // One-time (per class) sanity check: a @watch name with no matching\n // @property never fires — surface the typo instead of staying silent.\n validateWatchedProperties(this, constructor);\n // Now that the initial value is settled, give @watch immediate handlers\n // their one init call (before the first render, so derived state is ready).\n invokeImmediateWatchers(this, constructor);\n if (originalConnectedCallback) {\n originalConnectedCallback.call(this);\n }\n // v4.16.1: Render, run @ready handlers, THEN resolve .ready promise\n // This ensures `await el.ready` waits for both initial render AND all async @ready() methods\n //\n // We await a microtask boundary (to defer render for parent property bindings),\n // then run render + @ready handlers sequentially, then resolve .ready.\n const readyHandlers = constructor[READY_HANDLERS];\n // Await one microtask to defer initial render (allows parent property bindings)\n await new Promise(r => queueMicrotask(r));\n // If the element was removed during the microtask gap, don't render,\n // don't run @ready on an orphan. Resolve ready so any awaiters don't\n // hang — the element exists, it just isn't in the DOM.\n if (!this.isConnected) {\n if (this[READY_RESOLVE]) {\n this[READY_RESOLVE]();\n this[READY_RESOLVE] = null;\n }\n return;\n }\n if (this[RENDER_METHOD]) {\n requestRender(this, true);\n }\n // Setup observers after render so shadow DOM content exists\n try {\n setupObservers(this, this);\n }\n catch (error) {\n console.error(`Error setting up observers for ${this.tagName}:`, error);\n }\n // Yield a microtask so child elements' microtask-deferred renders\n // complete before @ready handlers run. Children queued their render\n // microtask when they connected (earlier in the queue), so they\n // drain before this one.\n await new Promise(r => queueMicrotask(r));\n // Element may have been removed during the second microtask gap.\n if (!this.isConnected) {\n if (this[READY_RESOLVE]) {\n this[READY_RESOLVE]();\n this[READY_RESOLVE] = null;\n }\n return;\n }\n // Run @ready handlers serially, awaiting each\n if (readyHandlers) {\n for (const handler of readyHandlers) {\n try {\n await handler.method.call(this);\n }\n catch (error) {\n console.error(`Error in @ready handler ${handler.methodName}:`, error);\n }\n }\n }\n // NOW resolve — render done AND all @ready handlers complete\n if (this[READY_RESOLVE]) {\n this[READY_RESOLVE]();\n this[READY_RESOLVE] = null;\n }\n };\n constructor.prototype.disconnectedCallback = async function () {\n try {\n disconnectRenderTree(this);\n }\n catch (error) {\n console.error(`Error disconnecting the render tree for ${this.tagName}:`, error);\n }\n // Call @dispose handlers\n const disposeHandlers = constructor[DISPOSE_HANDLERS];\n if (disposeHandlers) {\n for (const handler of disposeHandlers) {\n try {\n await handler.method.call(this);\n }\n catch (error) {\n console.error(`Error in @dispose handler ${handler.methodName}:`, error);\n }\n }\n }\n // Call original user-defined disconnectedCallback\n if (originalDisconnectedCallback) {\n originalDisconnectedCallback.call(this);\n }\n if (this[CONTROLLER]) {\n detachController(this).catch(error => {\n console.error(`Failed to detach controller:`, error);\n });\n }\n // Cleanup @on event handlers (v2.5.4 compatibility restored!)\n cleanupEventHandlers(this);\n // Cleanup @respond handlers\n cleanupResponseHandlers(this);\n // Cleanup @context handler\n cleanupContextHandler(this);\n // Cleanup @observe observers\n cleanupObservers(this);\n // Cleanup pending @debounce / @throttle timers so they don't fire on a dead element\n clearDebounceTimers(this);\n clearThrottleTimers(this);\n // The render/dispatch debounce-throttle timers live in separate stores.\n // A pending render is replayed on reconnect (same flag the scheduler\n // uses); a pending dispatch is a one-shot signal, so it's dropped.\n if (clearRenderTimers(this)) {\n this[PENDING_RECONNECT_RENDER] = true;\n }\n clearDispatchTimers(this);\n // @moved / @adopted debounce-throttle timers, likewise dropped so they\n // don't fire on a dead element.\n clearLifecycleTimers(this, MOVED_TIMERS);\n clearLifecycleTimers(this, ADOPTED_TIMERS);\n };\n constructor.prototype.attributeChangedCallback = function (name, oldValue, newValue) {\n originalAttributeChangedCallback?.call(this, name, oldValue, newValue);\n if (name === 'controller') {\n this.controller = newValue;\n return;\n }\n const properties = constructor[PROPERTIES];\n if (!properties)\n return;\n for (const [propName, propOptions] of properties) {\n const attributeName = getAttrName(propOptions, propName);\n if (attributeName.toLowerCase() !== name.toLowerCase())\n continue;\n // A property-originated reflection already stored the authoritative\n // JS value. Do not parse the serialized attribute back into a clone.\n if (this[SETTING_FROM_PROPERTY]?.has(name.toLowerCase()))\n break;\n const currentValue = this[PROPERTY_VALUES]?.[propName];\n // A removed attribute reverts the property to its field default. Read it\n // back through the getter (attribute is already gone at this point) so the\n // watcher's newValue and PROPERTY_VALUES match what this[propName] now\n // returns — parseAttributeValue(null) would diverge to null for String/Number.\n const defaultValue = this[PROPERTY_DEFAULTS]?.[propName];\n let parsedValue = newValue === null\n ? (propOptions.type === Boolean ? false : defaultValue)\n : parseAttributeValue(newValue, propOptions, currentValue, defaultValue);\n const wrap = this[PROPERTY_WRAPPERS]?.[propName];\n if (wrap)\n parsedValue = wrap(parsedValue);\n const changed = propOptions?.hasChanged\n ? propOptions.hasChanged(parsedValue, currentValue)\n : notEqual(parsedValue, currentValue);\n if (!changed)\n break;\n ensureSet(this, EXPLICITLY_SET_PROPERTIES).add(propName);\n ensureObj(this, PROPERTY_VALUES)[propName] = parsedValue;\n // Watchers react to changes only. During upgrade the initial value\n // is not a change, so suppress until INITIALIZED; @watch immediate\n // handlers get their one init call from invokeImmediateWatchers.\n if (this[INITIALIZED]) {\n invokeWatchers(this, constructor, propName, currentValue, parsedValue);\n }\n if (this[RENDER_METHOD] && this[INITIALIZED]) {\n requestRender(this);\n }\n break;\n }\n };\n // Add connectedMoveCallback for handling DOM moves\n constructor.prototype.connectedMoveCallback = async function () {\n // Call @moved handlers via the prototype method (the debounce/throttle\n // wrapper), not the raw handler — otherwise @moved({debounce}) options\n // are ignored for real moves and only work when called directly.\n const movedHandlers = constructor[MOVED_HANDLERS];\n if (movedHandlers) {\n for (const handler of movedHandlers) {\n try {\n await this[handler.methodName]();\n }\n catch (error) {\n console.error(`Error in @moved handler ${handler.methodName}:`, error);\n }\n }\n }\n };\n // Add adoptedCallback for handling document adoption\n constructor.prototype.adoptedCallback = async function () {\n // Call @adopted handlers via the prototype method (the debounce/throttle\n // wrapper), not the raw handler — same reason as connectedMoveCallback.\n const adoptedHandlers = constructor[ADOPTED_HANDLERS];\n if (adoptedHandlers) {\n for (const handler of adoptedHandlers) {\n try {\n await this[handler.methodName]();\n }\n catch (error) {\n console.error(`Error in @adopted handler ${handler.methodName}:`, error);\n }\n }\n }\n };\n}\n/**\n * Walk the prototype chain and merge parent element metadata into the child.\n * Called once at class definition time — zero per-instance cost.\n * Skips plain HTMLElement (no metadata to merge).\n *\n * Only merges PROPERTIES (stored via context.metadata at decoration time)\n * and formAssociated. Other handler registrations (@watch, @on, @ready, etc.)\n * inherit automatically via TC39 addInitializer — parent initializers run\n * during child instance construction.\n */\nfunction mergeParentMetadata(constructor) {\n let parent = Object.getPrototypeOf(constructor);\n // Collect ancestors bottom-up, then merge top-down so the deepest parent goes first\n const ancestors = [];\n while (parent && parent !== HTMLElement && parent !== Function.prototype) {\n ancestors.push(parent);\n parent = Object.getPrototypeOf(parent);\n }\n ancestors.reverse();\n for (const ancestor of ancestors) {\n // Properties (Map) — parent first, child overrides\n if (ancestor[PROPERTIES]) {\n if (!constructor[PROPERTIES])\n constructor[PROPERTIES] = new Map();\n for (const [key, value] of ancestor[PROPERTIES]) {\n if (!constructor[PROPERTIES].has(key)) {\n constructor[PROPERTIES].set(key, value);\n }\n }\n }\n // formAssociated — inherit if parent is form-associated\n if (ancestor.formAssociated && !constructor.formAssociated) {\n constructor.formAssociated = true;\n }\n }\n}\nfunction defineElement(tagName, constructor, context, options) {\n // Merge metadata from parent @element classes (inheritance support)\n mergeParentMetadata(constructor);\n if (context.metadata && context.metadata[PROPERTIES]) {\n if (!constructor[PROPERTIES])\n constructor[PROPERTIES] = new Map();\n for (const [key, value] of context.metadata[PROPERTIES]) {\n constructor[PROPERTIES].set(key, value);\n }\n }\n else if (_pendingProperties.length > 0) {\n // Symbol.metadata unavailable — drain the pending stack\n if (!constructor[PROPERTIES])\n constructor[PROPERTIES] = new Map();\n const pending = _pendingProperties.pop();\n for (const [key, value] of pending) {\n constructor[PROPERTIES].set(key, value);\n }\n }\n if (options?.formAssociated)\n constructor.formAssociated = true;\n const inheritedOptions = {\n ...(Object.getPrototypeOf(constructor)?.[ELEMENT_OPTIONS] || {})\n };\n const ownOptions = options || {};\n if (ownOptions.renderRoot === 'light' && typeof ownOptions.shadow === 'string' ||\n ownOptions.renderRoot === 'shadow' && ownOptions.shadow === false) {\n throw new TypeError('snice: @element renderRoot and shadow options select conflicting render roots.');\n }\n const mergedOptions = { ...inheritedOptions, ...ownOptions };\n if (Object.prototype.hasOwnProperty.call(ownOptions, 'shadow')) {\n mergedOptions.renderRoot = ownOptions.shadow === false ? 'light' : 'shadow';\n }\n else if (Object.prototype.hasOwnProperty.call(ownOptions, 'renderRoot')) {\n if (ownOptions.renderRoot === 'light')\n mergedOptions.shadow = false;\n else if (mergedOptions.shadow === false)\n mergedOptions.shadow = 'open';\n }\n constructor[ELEMENT_OPTIONS] = mergedOptions;\n if (constructor.prototype[SNICE_ELEMENT_BASE] === true &&\n Object.prototype.hasOwnProperty.call(constructor.prototype, 'render') &&\n !Object.prototype.hasOwnProperty.call(constructor.prototype, RENDER_METHOD) &&\n typeof constructor.prototype.render === 'function') {\n constructor.prototype[RENDER_METHOD] = constructor.prototype.render;\n constructor.prototype[RENDER_OPTIONS] = constructor.renderOptions || {};\n }\n applyElementFunctionality(constructor);\n if (customElements.get(tagName)) {\n if (globalThis.SNICE_DEBUG)\n console.warn(`[snice] \"${tagName}\" is already registered. Skipping.`);\n return constructor;\n }\n customElements.define(tagName, constructor);\n return constructor;\n}\nfunction element(tagName, options) {\n if (options?.renderRoot !== undefined && options.renderRoot !== 'shadow' && options.renderRoot !== 'light') {\n throw new TypeError('snice: @element renderRoot must be \"shadow\" or \"light\".');\n }\n if (options?.shadow !== undefined && options.shadow !== false &&\n options.shadow !== 'open' && options.shadow !== 'closed') {\n throw new TypeError('snice: @element shadow must be \"open\", \"closed\", or false.');\n }\n return function (constructor, context) {\n return defineElement(tagName, constructor, context, options);\n };\n}\nfunction layout(tagName) {\n return function (constructor, context) {\n return defineElement(tagName, constructor, context);\n };\n}\n// Fallback stack for environments where Symbol.metadata is unavailable.\n// @property pushes entries; @element pops them. Works because field decorators\n// run synchronously before the class decorator in the same static block.\nconst _pendingProperties = [];\nconst nativeOwnPropertyDefaults = new WeakMap();\nfunction isNativeOwnPropertyDefault(instance, propertyKey, value) {\n const ownerDocument = instance?.ownerDocument;\n if (!ownerDocument?.createElement)\n return false;\n let defaults = nativeOwnPropertyDefaults.get(ownerDocument);\n if (!defaults) {\n const nativeElement = ownerDocument.createElement('div');\n defaults = new Map();\n for (const key of Reflect.ownKeys(nativeElement))\n defaults.set(key, nativeElement[key]);\n nativeOwnPropertyDefaults.set(ownerDocument, defaults);\n }\n return defaults.has(propertyKey) && Object.is(defaults.get(propertyKey), value);\n}\nfunction property(options) {\n return function (_value, context) {\n const propertyKey = context.name;\n // Use metadata to store property information at decoration time\n if (context.metadata) {\n if (!context.metadata[PROPERTIES]) {\n context.metadata[PROPERTIES] = new Map();\n }\n context.metadata[PROPERTIES].set(propertyKey, options || {});\n }\n else {\n // Symbol.metadata unavailable — use the pending stack instead\n if (_pendingProperties.length === 0)\n _pendingProperties.push(new Map());\n _pendingProperties[_pendingProperties.length - 1].set(propertyKey, options || {});\n }\n return function (initialValue) {\n // A property binding can run while this is still an unupgraded custom\n // element, creating an own data property. Preserve that value across the\n // upgrade, but remove the expando before the decorated field initializer\n // is assigned so the assignment replays through the reactive accessor.\n const markedBindings = this[PRE_UPGRADE_PROPERTY_BINDINGS];\n const wasTemplateBoundBeforeUpgrade = markedBindings?.delete(propertyKey) === true;\n if (markedBindings?.size === 0)\n delete this[PRE_UPGRADE_PROPERTY_BINDINGS];\n const hasOwnValue = Object.prototype.hasOwnProperty.call(this, propertyKey);\n const hadPreUpgradeValue = hasOwnValue && (wasTemplateBoundBeforeUpgrade || !isNativeOwnPropertyDefault(this, propertyKey, this[propertyKey]));\n const preUpgradeValue = hadPreUpgradeValue ? this[propertyKey] : initialValue;\n if (hasOwnValue)\n delete this[propertyKey];\n const constructor = this.constructor;\n if (!constructor[PROPERTIES])\n constructor[PROPERTIES] = new Map();\n const finalOptions = { ...options };\n if (!finalOptions.type && initialValue !== undefined)\n finalOptions.type = detectType(initialValue);\n if (!finalOptions.attributeNaming && constructor.propertyAttributeNaming === 'kebab') {\n finalOptions.attributeNaming = 'kebab';\n }\n constructor[PROPERTIES].set(propertyKey, finalOptions);\n ensureObj(this, PROPERTY_DEFAULTS)[propertyKey] = initialValue;\n const notifyDeepMutation = () => {\n if (!this[PROPERTIES_INITIALIZED])\n return;\n const current = this[PROPERTY_VALUES]?.[propertyKey];\n if (finalOptions.attribute !== false && finalOptions.reflect !== false) {\n const attributeName = getAttrName(finalOptions, propertyKey);\n const attributeValue = valueToAttribute(current, finalOptions, initialValue);\n const attrKey = attributeName.toLowerCase();\n ensureSet(this, SETTING_FROM_PROPERTY).add(attrKey);\n try {\n if (attributeValue === null)\n this.removeAttribute?.(attributeName);\n else\n this.setAttribute?.(attributeName, attributeValue);\n }\n finally {\n this[SETTING_FROM_PROPERTY].delete(attrKey);\n }\n }\n if (this[INITIALIZED]) {\n invokeWatchers(this, this.constructor, propertyKey, current, current);\n if (this[RENDER_METHOD])\n requestRender(this);\n }\n };\n const wrap = (value) => {\n if (!finalOptions.deep)\n return value;\n let wrapped;\n wrapped = createDeepReactive(value, () => {\n // A caller may retain an old proxied object after replacing the\n // property. Mutating that detached graph must not invalidate the\n // component or notify watchers for the current value.\n if (this[PROPERTY_VALUES]?.[propertyKey] !== wrapped)\n return;\n notifyDeepMutation();\n });\n return wrapped;\n };\n ensureObj(this, PROPERTY_WRAPPERS)[propertyKey] = wrap;\n const proto = this.constructor.prototype;\n let definers = proto[PROPERTY_DEFINERS];\n if (!definers || !Object.prototype.hasOwnProperty.call(proto, PROPERTY_DEFINERS)) {\n definers = new Map(definers);\n proto[PROPERTY_DEFINERS] = definers;\n }\n const existingDefiner = definers.get(propertyKey);\n if (!existingDefiner || existingDefiner !== options) {\n definers.set(propertyKey, options);\n Object.defineProperty(this.constructor.prototype, propertyKey, {\n get() {\n if (this[PRE_INIT_PROPERTY_VALUES]?.has(propertyKey)) {\n return this[PRE_INIT_PROPERTY_VALUES].get(propertyKey);\n }\n if (this[PROPERTY_VALUES] && propertyKey in this[PROPERTY_VALUES]) {\n return this[PROPERTY_VALUES][propertyKey];\n }\n return initialValue;\n },\n set(incomingValue) {\n const oldValue = this[propertyKey];\n const changed = finalOptions.hasChanged\n ? finalOptions.hasChanged(incomingValue, oldValue)\n : notEqual(incomingValue, oldValue);\n if (!changed)\n return;\n const instanceWrap = this[PROPERTY_WRAPPERS]?.[propertyKey] || ((value) => value);\n // Property assignments are already typed JavaScript values and\n // remain the source of truth. `type` and `converter.fromAttribute`\n // apply only at the string attribute boundary; coercing here would\n // destroy object identity and turn valid union values (for example\n // `Date | ''` or `string | string[]`) into the wrong type.\n const newValue = instanceWrap(incomingValue);\n if (!this[PROPERTIES_INITIALIZED]) {\n if (!this[PRE_INIT_PROPERTY_VALUES])\n this[PRE_INIT_PROPERTY_VALUES] = new Map();\n this[PRE_INIT_PROPERTY_VALUES].set(propertyKey, newValue);\n return;\n }\n ensureObj(this, PROPERTY_VALUES)[propertyKey] = newValue;\n if (finalOptions.attribute !== false && finalOptions.reflect !== false) {\n const attributeName = getAttrName(finalOptions, propertyKey);\n const attributeValue = valueToAttribute(newValue, finalOptions, this[PROPERTY_DEFAULTS]?.[propertyKey]);\n ensureSet(this, EXPLICITLY_SET_PROPERTIES).add(propertyKey);\n const attrKey = attributeName.toLowerCase();\n ensureSet(this, SETTING_FROM_PROPERTY).add(attrKey);\n try {\n if (attributeValue === null)\n this.removeAttribute?.(attributeName);\n else\n this.setAttribute?.(attributeName, attributeValue);\n }\n finally {\n this[SETTING_FROM_PROPERTY].delete(attrKey);\n }\n }\n if (this[INITIALIZED]) {\n invokeWatchers(this, this.constructor, propertyKey, oldValue, newValue);\n if (this[RENDER_METHOD])\n requestRender(this);\n }\n },\n configurable: true,\n enumerable: true\n });\n }\n const wrappedInitialValue = wrap(initialValue);\n ensureObj(this, PROPERTY_VALUES)[propertyKey] = wrappedInitialValue;\n ensureObj(this, PROPERTY_DEFAULTS)[propertyKey] = wrappedInitialValue;\n return hadPreUpgradeValue ? preUpgradeValue : wrappedInitialValue;\n };\n };\n}\n/** Internal reactive state: never reads from or reflects to an attribute. */\nfunction state(options = {}) {\n return property({ ...options, attribute: false, reflect: false });\n}\nfunction getQueryRoot(instance) {\n const isController = instance[IS_CONTROLLER_INSTANCE] === true;\n return isController && instance.element ? instance.element : instance;\n}\nfunction query(selector, options = {}) {\n return function (_value, context) {\n const { light = false, shadow = true } = options;\n const propertyKey = context.name;\n return function (initialValue) {\n if (!Object.hasOwn(this.constructor.prototype, propertyKey)) {\n Object.defineProperty(this.constructor.prototype, propertyKey, {\n get() {\n const root = getQueryRoot(this);\n let result = null;\n const managedRoot = root instanceof HTMLElement ? getRenderRoot(root) : null;\n if (shadow && managedRoot)\n result = managedRoot.querySelector(selector);\n else if (shadow && root.shadowRoot)\n result = root.shadowRoot.querySelector(selector);\n if (!result && light)\n result = root.querySelector(selector);\n return result || null;\n },\n set() { },\n configurable: true,\n enumerable: true\n });\n }\n return initialValue;\n };\n };\n}\nfunction queryAll(selector, options = {}) {\n return function (_value, context) {\n const { light = false, shadow = true } = options;\n const propertyKey = context.name;\n return function (initialValue) {\n if (!Object.hasOwn(this.constructor.prototype, propertyKey)) {\n Object.defineProperty(this.constructor.prototype, propertyKey, {\n get() {\n const root = getQueryRoot(this);\n const results = new Set();\n const managedRoot = root instanceof HTMLElement ? getRenderRoot(root) : null;\n if (shadow && managedRoot) {\n for (const match of managedRoot.querySelectorAll(selector))\n results.add(match);\n }\n else if (shadow && root.shadowRoot) {\n for (const match of root.shadowRoot.querySelectorAll(selector))\n results.add(match);\n }\n if (light) {\n for (const match of root.querySelectorAll(selector))\n results.add(match);\n }\n return [...results];\n },\n set() { },\n configurable: true,\n enumerable: true\n });\n }\n return initialValue;\n };\n };\n}\nfunction watch(...args) {\n // A trailing options object is separated from the watched property names.\n const propertyNames = args.filter((a) => typeof a === 'string');\n const options = args.find((a) => typeof a === 'object' && a !== null);\n // Fire on init by default; opt out of the init call with { immediate: false }.\n const immediate = options?.immediate !== false;\n return function (target, context) {\n const methodName = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // Dedup by (method reference, propertyName) so that multiple @watch\n // decorators on the same method register for each key independently,\n // while still preventing duplicate registration when child classes\n // inherit/override a method with the same name. Use hasOwnProperty so\n // subclasses get their OWN Map — otherwise child pushes into the\n // parent's PROPERTY_WATCHERS via the prototype chain.\n if (!Object.prototype.hasOwnProperty.call(constructor, WATCH_METHODS)) {\n constructor[WATCH_METHODS] = new Map();\n }\n let registered = constructor[WATCH_METHODS].get(target);\n if (!registered) {\n registered = new Set();\n constructor[WATCH_METHODS].set(target, registered);\n }\n if (!Object.prototype.hasOwnProperty.call(constructor, PROPERTY_WATCHERS)) {\n // Deep-copy the inherited Map so the child starts with the parent's\n // watchers but pushing to a propertyName's array on the child doesn't\n // mutate the parent's array.\n const inherited = constructor[PROPERTY_WATCHERS];\n const copy = new Map();\n if (inherited) {\n for (const [key, arr] of inherited)\n copy.set(key, [...arr]);\n }\n constructor[PROPERTY_WATCHERS] = copy;\n }\n for (const propertyName of propertyNames) {\n if (registered.has(propertyName))\n continue;\n registered.add(propertyName);\n if (!constructor[PROPERTY_WATCHERS].has(propertyName)) {\n constructor[PROPERTY_WATCHERS].set(propertyName, []);\n }\n constructor[PROPERTY_WATCHERS].get(propertyName).push({\n methodName,\n method: target,\n immediate\n });\n }\n });\n };\n}\n/**\n * Decorator that injects router context into a property\n * The context is automatically provided to page components by the router\n */\nfunction context() {\n return function (_value, context) {\n const propertyKey = context.name;\n // Return a field initializer function for new decorators\n return function (initialValue) {\n // Set up the property descriptor on first access\n if (!Object.hasOwn(this.constructor.prototype, propertyKey)) {\n const descriptor = {\n get() {\n // Cached context\n if (this[ROUTER_CONTEXT] !== undefined) {\n return this[ROUTER_CONTEXT];\n }\n // Resolve dispatch target\n const isController = this[IS_CONTROLLER_INSTANCE] === true;\n let targetElement = isController && this.element ? this.element : this;\n // Controller was detached\n if (!targetElement || !targetElement.dispatchEvent)\n return undefined;\n // Shadow DOM: dispatch on host for proper bubbling\n if (targetElement.getRootNode && targetElement.getRootNode() instanceof ShadowRoot) {\n targetElement = targetElement.getRootNode().host;\n }\n // Request context from parent page\n const detail = { target: this };\n targetElement.dispatchEvent(new CustomEvent('@context/request', {\n bubbles: true,\n cancelable: true,\n detail\n }));\n // No context provided\n if (detail.context === undefined)\n return undefined;\n // Cache and return\n this[ROUTER_CONTEXT] = detail.context;\n return detail.context;\n },\n set() {\n // Context is read-only\n },\n configurable: true,\n enumerable: true\n };\n Object.defineProperty(this.constructor.prototype, propertyKey, descriptor);\n }\n return initialValue;\n };\n };\n}\nfunction registerHandler(handlersSymbol, methodsSymbol, target, context, extra) {\n const methodName = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // hasOwnProperty guards so subclasses get their OWN Set/array instead of\n // mutating the parent's via the prototype chain.\n if (!Object.prototype.hasOwnProperty.call(constructor, methodsSymbol)) {\n constructor[methodsSymbol] = new Set();\n }\n if (constructor[methodsSymbol].has(target))\n return;\n constructor[methodsSymbol].add(target);\n if (!Object.prototype.hasOwnProperty.call(constructor, handlersSymbol)) {\n const inherited = constructor[handlersSymbol];\n constructor[handlersSymbol] = inherited ? [...inherited] : [];\n }\n constructor[handlersSymbol].push({ methodName, method: target, ...extra });\n });\n}\nfunction ready() {\n return function (target, context) {\n registerHandler(READY_HANDLERS, READY_METHODS, target, context);\n };\n}\nfunction dispose() {\n return function (target, context) {\n registerHandler(DISPOSE_HANDLERS, DISPOSE_METHODS, target, context);\n };\n}\n/**\n * Fires every time the element is connected AFTER the first connect.\n *\n * `@ready` only fires once (after the initial render). `@dispose` fires on\n * every disconnect. The gap between them is \"what should run on a\n * reconnect?\" For most components, framework-managed pieces (`@on`,\n * `@observe`, `@respond`, `@context`) are re-established automatically\n * and nothing else is needed.\n *\n * Use `@reconnect` only when the component wires its OWN long-lived global\n * subscription in `@ready` (e.g. a `document.addEventListener` for\n * outside-click detection) and tears it down in `@dispose`. The framework\n * doesn't track those, so they need a hook to re-attach on reconnect.\n *\n * Counterpart to `@dispose`. Symmetric.\n */\nfunction reconnect() {\n return function (target, context) {\n registerHandler(RECONNECT_HANDLERS, RECONNECT_METHODS, target, context);\n };\n}\n/**\n * Clear any pending @moved / @adopted debounce/throttle timers on an instance\n * (e.g. on disconnect), so they don't fire on a dead element.\n */\nfunction clearLifecycleTimers(instance, timersSymbol) {\n const map = instance[timersSymbol];\n if (!map)\n return;\n for (const t of map.values()) {\n if (t.debounceTimer)\n clearTimeout(t.debounceTimer);\n if (t.throttleTimer)\n clearTimeout(t.throttleTimer);\n t.debounceTimer = null;\n t.throttleTimer = null;\n t.lastThrottleCall = 0;\n }\n}\nfunction createLifecycleDecorator(handlersSymbol, timersSymbol, methodsSymbol) {\n return function (options = {}) {\n return function (originalMethod, context) {\n registerHandler(handlersSymbol, methodsSymbol, originalMethod, context, { options });\n const methodName = context.name;\n return function (...args) {\n if (!this[timersSymbol])\n this[timersSymbol] = new Map();\n if (!this[timersSymbol].has(methodName)) {\n this[timersSymbol].set(methodName, { throttleTimer: null, debounceTimer: null, lastThrottleCall: 0 });\n }\n const timers = this[timersSymbol].get(methodName);\n const exec = (...a) => originalMethod.apply(this, a);\n // Deferred (debounce/throttle) calls run inside a setTimeout, outside\n // the caller's try/catch — so catch their sync throws and async\n // rejections here and log, rather than surface an uncaught error.\n const execDeferred = (...a) => {\n try {\n const result = originalMethod.apply(this, a);\n if (result && typeof result.then === 'function') {\n result.catch((error) => console.error(`Error in deferred lifecycle handler ${methodName}:`, error));\n }\n }\n catch (error) {\n console.error(`Error in deferred lifecycle handler ${methodName}:`, error);\n }\n };\n if (options.debounce > 0) {\n clearTimeout(timers.debounceTimer);\n timers.debounceTimer = setTimeout(() => execDeferred(...args), options.debounce);\n return undefined;\n }\n if (options.throttle > 0) {\n const now = Date.now();\n if (timers.lastThrottleCall === 0 || now - timers.lastThrottleCall >= options.throttle) {\n timers.lastThrottleCall = now;\n return exec(...args);\n }\n if (!timers.throttleTimer) {\n const remaining = options.throttle - (now - timers.lastThrottleCall);\n timers.throttleTimer = setTimeout(() => {\n timers.throttleTimer = null;\n timers.lastThrottleCall = Date.now();\n execDeferred(...args);\n }, remaining);\n }\n return undefined;\n }\n return exec(...args);\n };\n };\n };\n}\nconst moved = createLifecycleDecorator(MOVED_HANDLERS, MOVED_TIMERS, MOVED_METHODS);\nconst adopted = createLifecycleDecorator(ADOPTED_HANDLERS, ADOPTED_TIMERS, ADOPTED_METHODS);\n\n/**\n * Optional authoring base for convention-driven Snice components.\n *\n * Decorators remain fully supported on plain HTMLElement subclasses. Extending\n * this class adds typed lifecycle promises, imperative invalidation, modern\n * kebab-case implicit attributes, and `render()` / static `styles` conventions.\n */\nclass SniceElement extends HTMLElement {\n static { this.propertyAttributeNaming = 'kebab'; }\n createRenderRoot() {\n const options = this.constructor[ELEMENT_OPTIONS];\n const mode = typeof options?.shadow === 'string' ? options.shadow : 'open';\n return this.attachShadow({ mode, delegatesFocus: options?.delegatesFocus });\n }\n invalidate() {\n requestRender(this);\n return this.rendered;\n }\n renderNow() {\n renderElementNow(this);\n return this.rendered;\n }\n}\n// `@element` uses this inherited marker to enable render() conventions only\n// for the opt-in base class. Plain HTMLElement components may legitimately\n// have imperative helper methods named render().\nObject.defineProperty(SniceElement.prototype, SNICE_ELEMENT_BASE, { value: true });\n\n/*!\n * pica-route v1.1.2\n * A pure URL pattern matching library compatible with route-parser API\n * (c) 2024\n * Released under the MIT License.\n */\nclass Route {\n constructor(pattern) {\n this.parsed = this.parsePattern(pattern);\n }\n get spec() {\n return this.parsed.template;\n }\n parsePattern(pattern) {\n // Handle optional query syntax (?query=:param)\n let pathPattern = pattern;\n let queryPattern = '';\n let queryOptional = false;\n const queryIndex = pattern.indexOf('?');\n if (queryIndex !== -1) {\n pathPattern = pattern.slice(0, queryIndex);\n queryPattern = pattern.slice(queryIndex + 1);\n // Check if query is wrapped in optional syntax (?...)\n if (pathPattern.endsWith('(') && queryPattern.endsWith(')')) {\n queryOptional = true;\n pathPattern = pathPattern.slice(0, -1);\n queryPattern = queryPattern.slice(0, -1);\n }\n }\n return {\n pathSegments: this.parseSegments(pathPattern),\n querySegments: queryPattern ? this.parseQuerySegments(queryPattern) : [],\n queryOptional,\n template: pattern\n };\n }\n parseSegments(pattern) {\n const segments = [];\n let i = 0;\n while (i < pattern.length) {\n const char = pattern[i];\n switch (char) {\n case '(':\n // Parse optional group\n const { segments: optionalSegments, endIndex } = this.parseOptionalGroup(pattern, i);\n segments.push({ type: 'optional', segments: optionalSegments });\n i = endIndex + 1;\n break;\n case ':':\n // Parse parameter\n const { name, endIndex: paramEndIndex } = this.parseIdentifier(pattern, i + 1);\n segments.push({ type: 'param', name });\n i = paramEndIndex;\n break;\n case '*':\n // Parse splat\n const { name: splatName, endIndex: splatEndIndex } = this.parseIdentifier(pattern, i + 1);\n segments.push({ type: 'splat', name: splatName });\n i = splatEndIndex;\n break;\n default:\n // Parse literal text\n const { value, endIndex: literalEndIndex } = this.parseLiteral(pattern, i);\n if (value) {\n segments.push({ type: 'literal', value });\n }\n i = literalEndIndex;\n break;\n }\n }\n return segments;\n }\n parseOptionalGroup(pattern, startIndex) {\n let depth = 1;\n let i = startIndex + 1;\n while (i < pattern.length && depth > 0) {\n if (pattern[i] === '(')\n depth++;\n if (pattern[i] === ')')\n depth--;\n i++;\n }\n const content = pattern.slice(startIndex + 1, i - 1);\n return {\n segments: this.parseSegments(content),\n endIndex: i - 1\n };\n }\n parseIdentifier(pattern, startIndex) {\n let i = startIndex;\n while (i < pattern.length && /[\\w-]/.test(pattern[i])) {\n i++;\n }\n return {\n name: pattern.slice(startIndex, i),\n endIndex: i\n };\n }\n parseLiteral(pattern, startIndex) {\n let i = startIndex;\n while (i < pattern.length && !'(:*('.includes(pattern[i])) {\n i++;\n }\n return {\n value: pattern.slice(startIndex, i),\n endIndex: i\n };\n }\n parseQuerySegments(queryPattern) {\n // Remove optional group syntax wrapping the query\n let cleanPattern = queryPattern;\n if (cleanPattern.startsWith('(') && cleanPattern.endsWith(')')) {\n cleanPattern = cleanPattern.slice(1, -1);\n }\n const segments = [];\n let i = 0;\n while (i < cleanPattern.length) {\n switch (cleanPattern[i]) {\n case ':':\n const { name, endIndex } = this.parseIdentifier(cleanPattern, i + 1);\n segments.push({ type: 'param', name });\n i = endIndex;\n break;\n default:\n const { value, endIndex: literalEndIndex } = this.parseQueryLiteral(cleanPattern, i);\n if (value) {\n segments.push({ type: 'literal', value });\n }\n i = literalEndIndex;\n break;\n }\n }\n return segments;\n }\n parseQueryLiteral(pattern, startIndex) {\n let i = startIndex;\n while (i < pattern.length && pattern[i] !== ':') {\n i++;\n }\n return {\n value: pattern.slice(startIndex, i),\n endIndex: i\n };\n }\n getAllParamNames() {\n const paramNames = new Set();\n const collectParams = (segments) => {\n for (const segment of segments) {\n switch (segment.type) {\n case 'param':\n case 'splat':\n paramNames.add(segment.name);\n break;\n case 'optional':\n collectParams(segment.segments);\n break;\n }\n }\n };\n collectParams(this.parsed.pathSegments);\n collectParams(this.parsed.querySegments);\n return Array.from(paramNames);\n }\n canMatchRemainingSegments(path, startIndex, segments) {\n // Quick check: try to match the remaining segments\n // This is a simplified check - we just look for literal segments that must exist\n let pathIndex = startIndex;\n for (const segment of segments) {\n if (segment.type === 'literal') {\n const literalIndex = path.indexOf(segment.value, pathIndex);\n if (literalIndex === -1) {\n return false; // Required literal not found\n }\n pathIndex = literalIndex + segment.value.length;\n }\n // For optional, param, and splat segments, we're more permissive in this quick check\n }\n return true;\n }\n match(url) {\n const [pathPart, queryPart] = url.split('?');\n const pathParams = this.matchPath(pathPart, this.parsed.pathSegments);\n if (pathParams === false) {\n return false;\n }\n const queryParams = this.matchQuery(queryPart || '', this.parsed.querySegments);\n if (queryParams === false) {\n return false;\n }\n // Initialize result with all optional parameters set to undefined\n const allParams = this.getAllParamNames();\n const result = {};\n // Set all parameters to undefined initially\n for (const paramName of allParams) {\n result[paramName] = undefined;\n }\n // Override with actual matched values\n Object.assign(result, pathParams, queryParams);\n return result;\n }\n matchPath(path, segments) {\n const result = {};\n let pathIndex = 0;\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const remainingSegments = segments.slice(i + 1);\n const matchResult = this.matchSegment(path, pathIndex, segment, remainingSegments);\n if (matchResult === false) {\n return false;\n }\n Object.assign(result, matchResult.params);\n pathIndex = matchResult.nextIndex;\n }\n // Check if we've consumed the entire path\n if (pathIndex < path.length) {\n return false;\n }\n return result;\n }\n matchSegment(path, startIndex, segment, remainingSegments = []) {\n switch (segment.type) {\n case 'literal':\n if (path.slice(startIndex, startIndex + segment.value.length) === segment.value) {\n return { params: {}, nextIndex: startIndex + segment.value.length };\n }\n return false;\n case 'param': {\n let endIndex = startIndex;\n // Check if the next segment is a literal and find where it starts\n const nextSegment = remainingSegments[0];\n let stopChars = ['/', '?'];\n if (nextSegment && nextSegment.type === 'literal') {\n // For parameters followed by literals, we need to find where the literal starts\n const literalValue = nextSegment.value;\n const literalStart = path.indexOf(literalValue, startIndex);\n if (literalStart !== -1) {\n endIndex = literalStart;\n }\n else {\n // Literal not found, this parameter can't match\n return false;\n }\n }\n else {\n // Default behavior - stop at / or ?\n while (endIndex < path.length && !stopChars.includes(path[endIndex])) {\n endIndex++;\n }\n }\n if (endIndex === startIndex)\n return false;\n let value;\n try {\n value = decodeURIComponent(path.slice(startIndex, endIndex));\n }\n catch (e) {\n // If decoding fails, use the original value\n value = path.slice(startIndex, endIndex);\n }\n // If we hit a query string, we should reject this match for path parameters\n if (endIndex < path.length && path[endIndex] === '?' && remainingSegments.length > 0) {\n return false;\n }\n // Keep values as strings to match route-parser behavior\n return {\n params: { [segment.name]: value },\n nextIndex: endIndex\n };\n }\n case 'splat': {\n // For splats, we need to find the optimal stopping point by looking ahead\n let endIndex = path.length;\n const nextSegment = remainingSegments[0];\n if (nextSegment) {\n switch (nextSegment.type) {\n case 'literal':\n // For literal dots after splats, use first occurrence (for file extensions)\n // For other literals, use last occurrence\n if (nextSegment.value === '.') {\n const firstDotIndex = path.indexOf('.', startIndex);\n if (firstDotIndex !== -1) {\n endIndex = firstDotIndex;\n }\n }\n else {\n // Find the last occurrence of the next literal\n const literalIndex = path.lastIndexOf(nextSegment.value);\n if (literalIndex !== -1 && literalIndex >= startIndex) {\n endIndex = literalIndex;\n }\n }\n break;\n case 'param':\n // For parameter after splat, find the last slash\n let lastSlashIndex = -1;\n for (let i = path.length - 1; i >= startIndex; i--) {\n if (path[i] === '/') {\n lastSlashIndex = i;\n break;\n }\n }\n if (lastSlashIndex !== -1) {\n endIndex = lastSlashIndex;\n }\n break;\n case 'splat':\n // For consecutive splats, give this splat everything up to the last slash\n // The next splat gets the last component\n let lastSlash = -1;\n for (let i = path.length - 1; i > startIndex; i--) {\n if (path[i] === '/') {\n lastSlash = i + 1; // Include the slash\n break;\n }\n }\n if (lastSlash !== -1) {\n endIndex = lastSlash;\n }\n else {\n // No slash found, this splat gets everything except the last component\n const pathSegments = path.slice(startIndex).split('/').filter(s => s);\n if (pathSegments.length > 1) {\n endIndex = startIndex + pathSegments.slice(0, -1).join('/').length + 1;\n }\n else {\n endIndex = startIndex; // Give nothing to this splat\n }\n }\n break;\n case 'optional':\n // Look for literals inside optional groups\n const findFirstLiteral = (segs) => {\n for (const seg of segs) {\n if (seg.type === 'literal')\n return seg.value;\n if (seg.type === 'optional') {\n const nested = findFirstLiteral(seg.segments);\n if (nested)\n return nested;\n }\n }\n return null;\n };\n const firstLiteral = findFirstLiteral(nextSegment.segments);\n if (firstLiteral) {\n const literalIndex = path.lastIndexOf(firstLiteral);\n if (literalIndex !== -1 && literalIndex >= startIndex) {\n endIndex = literalIndex;\n }\n }\n break;\n }\n }\n // Don't go past query parameters\n const queryIndex = path.indexOf('?', startIndex);\n if (queryIndex !== -1 && queryIndex < endIndex) {\n endIndex = queryIndex;\n }\n let value;\n try {\n value = decodeURIComponent(path.slice(startIndex, endIndex));\n }\n catch (e) {\n // If decoding fails, use the original value\n value = path.slice(startIndex, endIndex);\n }\n return {\n params: { [segment.name]: value },\n nextIndex: endIndex\n };\n }\n case 'optional': {\n // Try to match the optional segment first, with backtracking if needed\n let tempIndex = startIndex;\n let params = {};\n let allMatched = true;\n for (let i = 0; i < segment.segments.length; i++) {\n const innerSegment = segment.segments[i];\n const remainingInner = segment.segments.slice(i + 1);\n const innerResult = this.matchSegment(path, tempIndex, innerSegment, remainingInner);\n if (innerResult === false) {\n allMatched = false;\n break;\n }\n Object.assign(params, innerResult.params);\n tempIndex = innerResult.nextIndex;\n }\n if (allMatched) {\n // Check if the rest of the segments can still be matched\n const canMatchRemaining = this.canMatchRemainingSegments(path, tempIndex, remainingSegments);\n if (canMatchRemaining) {\n return {\n params,\n nextIndex: tempIndex\n };\n }\n }\n // Optional segment either didn't match or would prevent remaining segments from matching\n // So skip it and return to original position\n return { params: {}, nextIndex: startIndex };\n }\n default:\n return false;\n }\n }\n findNextLiteral(segments) {\n for (const segment of segments) {\n if (segment.type === 'literal') {\n return segment;\n }\n else if (segment.type === 'optional') {\n const nested = this.findNextLiteral(segment.segments);\n if (nested)\n return nested;\n }\n }\n return null;\n }\n matchQuery(query, segments) {\n if (segments.length === 0) {\n return {};\n }\n const result = {};\n let queryIndex = 0;\n for (const segment of segments) {\n switch (segment.type) {\n case 'literal':\n if (query.slice(queryIndex, queryIndex + segment.value.length) === segment.value) {\n queryIndex += segment.value.length;\n }\n else {\n return false;\n }\n break;\n case 'param': {\n let endIndex = queryIndex;\n while (endIndex < query.length && query[endIndex] !== '&') {\n endIndex++;\n }\n if (endIndex === queryIndex)\n return false;\n let value;\n try {\n value = decodeURIComponent(query.slice(queryIndex, endIndex));\n }\n catch (e) {\n // If decoding fails, use the original value\n value = query.slice(queryIndex, endIndex);\n }\n result[segment.name] = value;\n queryIndex = endIndex;\n break;\n }\n }\n }\n return result;\n }\n reverse(params = {}) {\n const pathResult = this.reverseSegments(this.parsed.pathSegments, params);\n if (pathResult === false) {\n return false;\n }\n let result = pathResult;\n if (this.parsed.querySegments.length > 0) {\n const queryResult = this.reverseSegments(this.parsed.querySegments, params);\n if (!this.parsed.queryOptional) {\n // Query is required - if it fails, the whole reverse fails\n if (queryResult === false) {\n return false;\n }\n }\n // Add query string if we have a result\n if (queryResult && queryResult !== '') {\n result += '?' + queryResult;\n }\n }\n return result;\n }\n reverseSegments(segments, params, inActivatedStructure = false) {\n let result = '';\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const remainingSegments = segments.slice(i + 1);\n switch (segment.type) {\n case 'literal':\n result += segment.value;\n break;\n case 'param':\n case 'splat':\n if (segment.name in params) {\n result += String(params[segment.name]);\n }\n else {\n // Missing required parameter - but for query segments, this might be optional\n return false;\n }\n break;\n case 'optional':\n // Check if this optional group should be included\n // considering dependencies from later optional groups\n const shouldInclude = this.hasAllParams(segment.segments, params, inActivatedStructure) ||\n this.hasLaterOptionalGroupNeedingParams(remainingSegments, params, segment.segments);\n if (shouldInclude) {\n const optionalResult = this.reverseSegments(segment.segments, params, true);\n if (optionalResult === false) {\n return false;\n }\n result += optionalResult;\n }\n break;\n }\n }\n return result;\n }\n // Check if any later optional groups need parameters and would require this group to be included\n hasLaterOptionalGroupNeedingParams(laterSegments, params, currentOptionalSegments) {\n // Check if any later optional group has parameters that are provided\n for (const segment of laterSegments) {\n if (segment.type === 'optional') {\n if (this.hasAnyParamInSegments(segment.segments, params)) {\n // Check if the current optional group only has literals/no required params\n // If so, it should be included as a bridge to the later group\n return this.hasOnlyLiteralsAndOptionals(currentOptionalSegments);\n }\n }\n }\n return false;\n }\n hasOnlyLiteralsAndOptionals(segments) {\n for (const segment of segments) {\n if (segment.type === 'param' || segment.type === 'splat') {\n return false;\n }\n }\n return true;\n }\n hasAllParams(segments, params, inActivatedStructure = false) {\n // Check if we can include this optional group\n let hasDirectParams = false;\n let hasNestedParams = false;\n let missingDirectParam = false;\n let hasOnlyLiteralsAndOptionals = true;\n // First pass: check direct params and literals\n for (const segment of segments) {\n switch (segment.type) {\n case 'param':\n case 'splat':\n hasOnlyLiteralsAndOptionals = false;\n if (segment.name in params && params[segment.name] !== undefined) {\n hasDirectParams = true;\n }\n else {\n missingDirectParam = true;\n }\n break;\n }\n }\n // Determine if this level will be activated and propagate to nested\n const willBeActivated = (hasDirectParams && !missingDirectParam);\n const passToNested = inActivatedStructure || willBeActivated;\n // Second pass: check nested optional groups with correct context\n for (const segment of segments) {\n if (segment.type === 'optional') {\n const shouldIncludeNested = this.hasAllParams(segment.segments, params, passToNested);\n if (shouldIncludeNested) {\n hasNestedParams = true;\n }\n }\n }\n // Include this optional group if:\n // 1. We have all direct parameters needed, OR\n // 2. We have nested parameters and no missing direct parameters, OR\n // 3. We have only literals/optionals and parent was activated\n if (hasDirectParams && !missingDirectParam) {\n return true; // We have all required params for this level\n }\n if (hasNestedParams && !missingDirectParam) {\n return true; // We need this group to reach nested parameters\n }\n // Include literal-only groups in nested structures\n if (hasOnlyLiteralsAndOptionals && inActivatedStructure) {\n return true; // Include literal paths in activated structures\n }\n return false;\n }\n hasOnlyOptionalMissingParams(segments, params) {\n // Check if all missing parameters are in nested optional groups\n for (const segment of segments) {\n switch (segment.type) {\n case 'param':\n case 'splat':\n if (!(segment.name in params)) {\n return false; // Has required missing param\n }\n break;\n }\n }\n return true;\n }\n hasAnyParamInSegments(segments, params) {\n for (const segment of segments) {\n switch (segment.type) {\n case 'param':\n case 'splat':\n if (segment.name in params) {\n return true;\n }\n break;\n case 'optional':\n if (this.hasAnyParamInSegments(segment.segments, params)) {\n return true;\n }\n break;\n }\n }\n return false;\n }\n}\n\n/**\n * Score a route pattern by specificity so that more specific routes are tried\n * first. Scoring is per-segment by ROLE, not by string length: a static segment\n * outweighs a dynamic (`:param`) segment, which outweighs a wildcard (`*` /\n * `*name`). So `/post/new` beats `/post/:id`, and a splat always ranks last —\n * regardless of how long the pattern string happens to be. This mirrors the\n * segment-scoring model mainstream routers (React Router, Remix) use.\n *\n * Sort callers descending by this score (highest = most specific = first).\n *\n * NOTE: mirrored in `src/react/route-specificity.ts` for the isolated React\n * bundle — keep the two in sync.\n */\nconst STATIC_SEGMENT = 10;\nconst DYNAMIC_SEGMENT = 3;\nconst WILDCARD_SEGMENT = -2;\nfunction routeSpecificity(spec) {\n const segments = spec.split('/').filter(Boolean);\n // Base on segment count so a deeper path outranks a shallower one on ties.\n let score = segments.length;\n for (const segment of segments) {\n if (segment.startsWith('*')) {\n score += WILDCARD_SEGMENT;\n }\n else if (segment.startsWith(':')) {\n score += DYNAMIC_SEGMENT;\n }\n else {\n score += STATIC_SEGMENT;\n }\n }\n return score;\n}\n\n/**\n * Generic transition system for animating between elements\n */\n/**\n * Parse CSS property string into an object\n */\nfunction parseStyles(styleString) {\n const styles = {};\n styleString.split(';').forEach(rule => {\n const idx = rule.indexOf(':');\n if (idx === -1)\n return;\n const prop = rule.slice(0, idx).trim();\n const value = rule.slice(idx + 1).trim();\n if (prop && value) {\n styles[prop] = value;\n }\n });\n return styles;\n}\n/**\n * Perform a transition between two elements\n */\nfunction applyBaseTransitionStyles(el, isSlotted, duration, prop) {\n el.style.position = 'absolute';\n el.style.width = '100%';\n if (isSlotted) {\n el.style.height = '100%';\n el.style.transition = `opacity ${duration}ms ease-in-out`;\n return;\n }\n el.style.top = '0';\n el.style.left = '0';\n el.style.transition = `${prop} ${duration}ms ease-in-out`;\n}\nfunction resetTransitionStyles(el, isSlotted) {\n el.style.position = '';\n el.style.width = '';\n el.style.transition = '';\n if (isSlotted) {\n el.style.height = '';\n return;\n }\n el.style.top = '';\n el.style.left = '';\n}\nasync function performTransition(container, oldElement, newElement, transition = {}, \n/**\n * Called at each async boundary — if it returns true, this transition has\n * been superseded by a newer navigation. We abort cleanup so we don't tear\n * down elements now owned by the newer transition.\n */\nisStale = () => false) {\n const outDuration = transition.outDuration ?? 300;\n const inDuration = transition.inDuration ?? 300;\n const mode = (transition.mode || 'sequential');\n const outStyles = transition.out ? parseStyles(transition.out) : { opacity: '0' };\n const inStartStyles = { opacity: '0' };\n const inEndStyles = transition.in ? parseStyles(transition.in) : { opacity: '1' };\n const containerStyle = container.style;\n const isLayoutElement = container.tagName.includes('-') && container.shadowRoot;\n // Track the position we were ORIGINALLY given, not what a concurrent\n // transition may have already written. The first transition to touch this\n // container wins; subsequent overlapping transitions reuse the same value\n // and the last one to finish restores it.\n const POS_KEY = Symbol.for('snice:transition-original-position');\n const POS_COUNT = Symbol.for('snice:transition-count');\n const c = container;\n if (!isLayoutElement) {\n if (!(POS_KEY in c)) {\n c[POS_KEY] = containerStyle.position;\n c[POS_COUNT] = 0;\n }\n c[POS_COUNT]++;\n containerStyle.position = 'relative';\n }\n const restorePosition = () => {\n if (isLayoutElement)\n return;\n c[POS_COUNT]--;\n if (c[POS_COUNT] <= 0) {\n containerStyle.position = c[POS_KEY];\n delete c[POS_KEY];\n delete c[POS_COUNT];\n }\n };\n const isSlotted = oldElement.hasAttribute('slot') || newElement.hasAttribute('slot');\n applyBaseTransitionStyles(oldElement, isSlotted, outDuration, 'all');\n applyBaseTransitionStyles(newElement, isSlotted, inDuration, 'all');\n Object.assign(newElement.style, inStartStyles);\n container.appendChild(newElement);\n void newElement.offsetHeight;\n // Animate\n switch (mode) {\n case TransitionMode.SIMULTANEOUS:\n Object.assign(oldElement.style, outStyles);\n Object.assign(newElement.style, inEndStyles);\n await new Promise(resolve => setTimeout(resolve, Math.max(outDuration, inDuration)));\n break;\n case TransitionMode.SEQUENTIAL:\n Object.assign(oldElement.style, outStyles);\n await new Promise(resolve => setTimeout(resolve, outDuration));\n if (isStale()) {\n if (newElement.parentNode === container)\n newElement.remove();\n restorePosition();\n return;\n }\n Object.assign(newElement.style, inEndStyles);\n await new Promise(resolve => setTimeout(resolve, inDuration));\n break;\n }\n if (isStale()) {\n // A newer navigation took over while we were animating. Don't touch\n // oldElement (the newer transition owns it now) and remove OUR newElement\n // since the newer transition appended its own.\n if (newElement.parentNode === container)\n newElement.remove();\n restorePosition();\n return;\n }\n // Cleanup\n oldElement.remove();\n resetTransitionStyles(newElement, isSlotted);\n Object.keys({ ...inStartStyles, ...inEndStyles }).forEach(prop => {\n newElement.style[prop] = '';\n });\n restorePosition();\n}\n\n/**\n * Possible outcomes from route resolution\n */\nvar RouteResult;\n(function (RouteResult) {\n RouteResult[\"SUCCESS\"] = \"success\";\n RouteResult[\"GUARDS_FAILED\"] = \"guards-failed\";\n RouteResult[\"NOT_FOUND\"] = \"not-found\";\n})(RouteResult || (RouteResult = {}));\n/**\n * Creates a new router instance.\n * @param {RouterOptions} options - The router configuration options.\n * @returns An object containing the router's API methods.\n */\nfunction Router(options) {\n const win = options.window ?? window;\n const doc = options.document ?? document;\n const routes = [];\n let is_sorted = false;\n let placards = []; // Store collected placards\n let _404; // the 404 page\n let _403; // the 403 forbidden page\n let home; // the home page\n let currentLayoutName = null; // Track current layout name\n let currentLayoutTimestamp = null; // Track current layout timestamp\n const context = options.context || {}; // Store context for guards\n // Create Context instance for managing router state\n const navigationContext = new Context(context, [], '', {}, options.fetcher);\n function getCurrentLayoutElement(target) {\n const noCurrentLayout = !currentLayoutName || !currentLayoutTimestamp;\n if (noCurrentLayout) {\n return null;\n }\n const layoutElements = target.querySelectorAll(currentLayoutName);\n for (const element of layoutElements) {\n const hasTimestamp = element[CREATED_AT] === currentLayoutTimestamp;\n if (hasTimestamp) {\n return element;\n }\n }\n return null;\n }\n /**\n * Decorator function for defining a page with associated routes.\n * @param {PageOptions} pageOptions - The page configuration options.\n * @returns A decorator function to apply to a custom element class.\n */\n function page(pageOptions) {\n return function (constructor, context) {\n // Transfer metadata from context to constructor (for new decorators)\n if (context?.metadata && context.metadata[PROPERTIES]) {\n if (!constructor[PROPERTIES]) {\n constructor[PROPERTIES] = new Map();\n }\n for (const [key, value] of context.metadata[PROPERTIES]) {\n constructor[PROPERTIES].set(key, value);\n }\n }\n // Apply all element functionality (properties, queries, watchers, controllers, etc.)\n applyElementFunctionality(constructor);\n // Store transition config on constructor for later use\n constructor[PAGE_TRANSITION] = pageOptions.transition;\n // Extend the connectedCallback to add router-specific functionality\n const elementConnectedCallback = constructor.prototype.connectedCallback;\n constructor.prototype.connectedCallback = function () {\n // Store the Context instance for @context decorated methods to access\n this[CONTEXT_HANDLER] = navigationContext;\n // Call the element's connectedCallback first\n elementConnectedCallback?.call(this);\n };\n // Extend the disconnectedCallback to clean up router-specific stuff\n const elementDisconnectedCallback = constructor.prototype.disconnectedCallback;\n constructor.prototype.disconnectedCallback = function () {\n // Call element's disconnectedCallback first\n elementDisconnectedCallback?.call(this);\n // Clean up context references\n delete this[ROUTER_CONTEXT];\n delete this[CONTEXT_HANDLER];\n };\n // Define the custom element (skip if already registered)\n if (!win.customElements.get(pageOptions.tag)) {\n win.customElements.define(pageOptions.tag, constructor);\n }\n // Register the routes with guards, layout, and placard\n pageOptions.routes.forEach(route => register(route, pageOptions.tag, pageOptions.transition, pageOptions.guards, pageOptions.layout, pageOptions.placard));\n return constructor;\n };\n }\n /**\n * Registers a new route with the router.\n * @param {string} route - The route path.\n * @param {string} tag - The custom element tag associated with the route.\n * @example\n * register('/custom-route', 'custom-element');\n */\n function register(route, tag, transition, guards, layout, placard) {\n routes.push({ route: new Route(route), tag, transition, guards, layout, placard });\n is_sorted = false;\n switch (route) {\n case '/404':\n _404 = tag;\n break;\n case '/403':\n _403 = tag;\n break;\n case '/':\n home = tag;\n break;\n }\n }\n function setupEventListeners() {\n const handler = () => {\n if (!doc.querySelector(options.target))\n return;\n navigate(getPath());\n };\n switch (options.type) {\n case 'hash':\n win.addEventListener('hashchange', handler);\n break;\n case 'pushstate':\n win.addEventListener('popstate', handler);\n break;\n }\n }\n /**\n * Initializes the router and sets up navigation event listeners.\n * @example\n * initialize();\n */\n function initialize() {\n const target = doc.querySelector(options.target);\n if (!target) {\n throw new Error(`Target element not found: ${options.target}`);\n }\n const needsSorting = !is_sorted;\n if (needsSorting) {\n routes.sort((a, b) => routeSpecificity(b.route.spec) - routeSpecificity(a.route.spec));\n is_sorted = true;\n }\n // Collect placards from registered routes\n collectPlacards();\n setupEventListeners();\n const path = getPath();\n navigate(path);\n }\n function collectPlacards() {\n const seen = new Set();\n placards = routes\n .filter(route => route.placard)\n .map(route => {\n const placard = route.placard;\n return typeof placard === 'function'\n ? placard(context)\n : placard;\n })\n .filter(p => {\n if (seen.has(p.name))\n return false;\n seen.add(p.name);\n return true;\n });\n }\n function emitContextUpdate(target, currentPath, routeParams) {\n // Update the navigation context and notify all registered elements\n navigationContext[CONTEXT_UPDATE](context, placards, currentPath, routeParams);\n }\n function updateLayout(layoutElement, currentPath, routeParams) {\n // Check if layout implements the update method\n if (typeof layoutElement.update === 'function') {\n layoutElement.update(context, placards, currentPath, routeParams);\n }\n }\n function getPath() {\n switch (options.type) {\n case 'hash':\n return win.location.hash.slice(1);\n case 'pushstate':\n return win.location.pathname;\n }\n }\n function renderForbiddenPage(target) {\n let newPageElement;\n if (_403) {\n newPageElement = doc.createElement(_403);\n newPageElement[ROUTER_CONTEXT] = context;\n }\n else {\n const div = doc.createElement('div');\n div.className = 'default-403';\n div.innerHTML = /*html*/ `<h1>403</h1><p>Unauthorized</p>`;\n newPageElement = div;\n }\n target.innerHTML = '';\n target.appendChild(newPageElement);\n currentLayoutName = null;\n currentLayoutTimestamp = null;\n }\n function createLoadingSpinner() {\n const container = doc.createElement('div');\n container.setAttribute('data-snice-loading', '');\n container.innerHTML = /*html*/ `\n <style>@keyframes snice-spin{to{transform:rotate(360deg)}}</style>\n <div style=\"display:flex;align-items:center;justify-content:center;height:100%;min-height:200px\">\n <div style=\"width:32px;height:32px;border:3px solid rgba(128,128,128,0.3);border-top-color:rgba(128,128,128,0.8);border-radius:50%;animation:snice-spin 0.6s linear infinite\"></div>\n </div>`;\n return container;\n }\n async function checkGuards(guards, params, target, stale) {\n const hasGuards = !!guards;\n if (!hasGuards) {\n return true;\n }\n const guardsArray = Array.isArray(guards) ? guards : [guards];\n let spinner = null;\n let spinnerTimer = null;\n // Show spinner after a short delay (avoids flash for fast sync guards).\n // Skip if a newer navigation has already superseded this one.\n spinnerTimer = setTimeout(() => {\n if (stale && stale())\n return;\n spinner = createLoadingSpinner();\n target.appendChild(spinner);\n }, 50);\n try {\n for (const guard of guardsArray) {\n const allowed = await guard(context, params);\n if (!allowed) {\n // Don't stomp the current page with a 403 if a newer navigation\n // already took over while this guard was resolving.\n if (!stale || !stale()) {\n renderForbiddenPage(target);\n }\n return false;\n }\n }\n return true;\n }\n finally {\n if (spinnerTimer)\n clearTimeout(spinnerTimer);\n // @ts-ignore — TS narrows spinner to never because it can't track setTimeout mutations\n if (spinner)\n spinner.remove();\n }\n }\n function createHomeElement() {\n const newPageElement = doc.createElement(home);\n newPageElement[ROUTER_CONTEXT] = context;\n const constructor = win.customElements.get(home);\n const transition = constructor?.[PAGE_TRANSITION];\n const homeRoute = routes.find(r => r.route.match('/'));\n return { element: newPageElement, transition, layout: homeRoute?.layout };\n }\n function create404Element() {\n const has404Page = !!_404;\n if (has404Page) {\n const newPageElement = doc.createElement(_404);\n newPageElement[ROUTER_CONTEXT] = context;\n const constructor = win.customElements.get(_404);\n const transition = constructor?.[PAGE_TRANSITION];\n return { element: newPageElement, transition, layout: undefined };\n }\n const div = doc.createElement('div');\n div.className = 'default-404';\n div.innerHTML = /*html*/ `<h1>404</h1><p>Page not found</p>`;\n return { element: div, transition: undefined, layout: undefined };\n }\n async function resolveRoute(path, target, stale) {\n for (const route of routes) {\n const params = route.route.match(path);\n const isMatch = params !== false;\n if (!isMatch) {\n continue;\n }\n const guardsAllowed = await checkGuards(route.guards, params, target, stale);\n if (!guardsAllowed) {\n return { result: RouteResult.GUARDS_FAILED };\n }\n const newPageElement = doc.createElement(route.tag);\n newPageElement[ROUTER_CONTEXT] = context;\n newPageElement[CONTEXT_HANDLER] = navigationContext;\n const routeParams = params;\n Object.keys(routeParams).forEach(key => newPageElement.setAttribute(key, routeParams[key]));\n return { result: RouteResult.SUCCESS, element: newPageElement, transition: route.transition, layout: route.layout, routeParams };\n }\n return { result: RouteResult.NOT_FOUND };\n }\n function determineLayout(pageLayout) {\n const isExplicitlyNoLayout = pageLayout === false;\n if (isExplicitlyNoLayout) {\n return null;\n }\n const hasPageLayout = !!pageLayout;\n if (hasPageLayout) {\n return pageLayout;\n }\n const hasRouterLayout = !!options.layout;\n if (hasRouterLayout) {\n return options.layout;\n }\n return null;\n }\n function setupLayout(layoutToUse) {\n const needsNewLayout = layoutToUse !== currentLayoutName;\n if (!needsNewLayout) {\n return { element: null, needsNewLayout: false };\n }\n currentLayoutName = layoutToUse;\n const shouldCreateLayout = !!layoutToUse;\n if (shouldCreateLayout) {\n const timestamp = Date.now();\n currentLayoutTimestamp = timestamp;\n const layoutElement = doc.createElement(layoutToUse);\n layoutElement[ROUTER_CONTEXT] = context;\n layoutElement[CREATED_AT] = timestamp;\n return { element: layoutElement, needsNewLayout: true };\n }\n currentLayoutTimestamp = null;\n return { element: null, needsNewLayout: true };\n }\n async function renderWithLayout(target, pageElement, transition, layoutElement, needsNewLayout, currentPath, routeParams, stale) {\n const currentLayout = layoutElement || getCurrentLayoutElement(target);\n if (!currentLayout) {\n return;\n }\n // Update layout with current context and placards\n updateLayout(currentLayout, currentPath, routeParams);\n const oldPageInLayout = currentLayout.querySelector('[slot=\"page\"]');\n const shouldTransition = !!(transition && oldPageInLayout);\n if (shouldTransition) {\n pageElement.setAttribute('slot', 'page');\n await performTransition$1(currentLayout, oldPageInLayout, pageElement, transition);\n if (stale && stale())\n return;\n if (needsNewLayout) {\n target.innerHTML = '';\n target.appendChild(currentLayout);\n }\n return;\n }\n // Guard before committing DOM changes.\n if (stale && stale())\n return;\n const existingPages = currentLayout.querySelectorAll('[slot=\"page\"]');\n existingPages.forEach(page => page.remove());\n pageElement.setAttribute('slot', 'page');\n currentLayout.appendChild(pageElement);\n if (needsNewLayout) {\n target.innerHTML = '';\n target.appendChild(currentLayout);\n }\n }\n async function renderDirect(target, pageElement, transition, stale) {\n const currentElementInTarget = target.children[0];\n const shouldTransition = !!(transition && currentElementInTarget);\n if (shouldTransition) {\n await performTransition$1(target, currentElementInTarget, pageElement, transition);\n return;\n }\n // Guard against superseded navigation before committing DOM.\n if (stale && stale())\n return;\n target.innerHTML = '';\n target.appendChild(pageElement);\n }\n async function renderPage(target, pageElement, transition, layout, path, routeParams, stale) {\n const layoutToUse = determineLayout(layout);\n const { element: layoutElement, needsNewLayout } = setupLayout(layoutToUse);\n const finalTransition = transition || options.transition;\n const hasLayout = layoutElement !== null || getCurrentLayoutElement(target) !== null;\n if (hasLayout) {\n await renderWithLayout(target, pageElement, finalTransition, layoutElement, needsNewLayout, path, routeParams, stale);\n if (stale && stale())\n return;\n emitContextUpdate(target, path, routeParams);\n return;\n }\n await renderDirect(target, pageElement, finalTransition, stale);\n if (stale && stale())\n return;\n emitContextUpdate(target, path, routeParams);\n }\n /**\n * Navigates to the specified path.\n * @param {string} path - The path to navigate to.\n * @example\n * navigate('/login');\n */\n let navGeneration = 0;\n async function navigate(path) {\n const target = doc.querySelector(options.target);\n if (!target) {\n throw new Error(`Target element not found: ${options.target}`);\n }\n const myGen = ++navGeneration;\n const stale = () => myGen !== navGeneration;\n collectPlacards();\n win.scrollTo(0, 0);\n // Home path\n const isHomePath = (path?.trim() === '' || path === '/') && !!home;\n if (isHomePath) {\n const homeRoute = routes.find(r => r.route.match('/'));\n if (!(await checkGuards(homeRoute?.guards, {}, target, stale)))\n return;\n if (stale())\n return;\n const { element, transition, layout } = createHomeElement();\n await renderPage(target, element, transition, layout, path, {}, stale);\n return;\n }\n // No path\n if (!path)\n return;\n // Resolve route\n const routeResult = await resolveRoute(path, target, stale);\n if (stale())\n return;\n // Guards failed (403 already rendered by checkGuards)\n if (routeResult.result === RouteResult.GUARDS_FAILED)\n return;\n // Route matched\n if (routeResult.result === RouteResult.SUCCESS) {\n const { element, transition, layout, routeParams = {} } = routeResult;\n await renderPage(target, element, transition, layout, path, routeParams, stale);\n return;\n }\n // 404 fallthrough\n const { element, transition, layout } = create404Element();\n await renderPage(target, element, transition, layout, path, {}, stale);\n }\n async function performTransition$1(container, oldElement, newElement, transition, atGen = navGeneration) {\n // `isStale` returns true when a newer navigate() has been kicked off.\n // The transition util checks this at each async boundary and bails so\n // we don't remove an element the newer transition now owns.\n const isStale = () => atGen !== navGeneration;\n return performTransition(container, oldElement, newElement, transition, isStale);\n }\n return {\n page,\n initialize,\n navigate,\n register\n };\n}\n\n/**\n * createRequestHandler — vanilla JS utility for handling @request channels\n * outside of the Snice element/controller decorator system.\n *\n * Listens for @request CustomEvents on a target element (or document),\n * performs the discovery/data handshake, and dispatches to your route map.\n *\n * @example\n * ```js\n * import { createRequestHandler } from 'snice';\n *\n * const cleanup = createRequestHandler(document, {\n * 'fetch-user': async (payload) => {\n * const res = await fetch(`/api/users/${payload.id}`);\n * return res.json();\n * },\n * 'save-settings': async (payload) => {\n * await fetch('/api/settings', { method: 'POST', body: JSON.stringify(payload) });\n * return { ok: true };\n * }\n * });\n *\n * // Later, to remove all listeners:\n * cleanup();\n * ```\n */\n/**\n * Attach request handlers to a DOM target.\n *\n * @param target The element or document to listen on. Events bubble, so an\n * ancestor element catches requests from any descendant.\n * @param routes Map of channel names to handler functions.\n * @param options Optional configuration.\n * @returns A cleanup function that removes all listeners.\n */\nfunction createRequestHandler(target, routes, options) {\n const cleanups = [];\n for (const [channelName, handler] of Object.entries(routes)) {\n const eventName = `@request/${channelName}`;\n const listener = (event) => {\n const ce = event;\n const { discovery, data, payload } = ce.detail;\n if (!options?.passive) {\n ce.preventDefault();\n ce.stopImmediatePropagation();\n ce.stopPropagation();\n }\n // Signal that we found the handler — clears discovery timeout\n discovery.resolve();\n // Execute the handler and wire up the data promise\n Promise.resolve()\n .then(() => handler(payload))\n .then((result) => data.resolve(result))\n .catch((error) => {\n data.reject(error);\n console.error(`createRequestHandler: error in \"${channelName}\" handler:`, error);\n });\n };\n target.addEventListener(eventName, listener);\n cleanups.push(() => target.removeEventListener(eventName, listener));\n }\n return () => {\n for (const fn of cleanups)\n fn();\n cleanups.length = 0;\n };\n}\n\n/**\n * Template binding helpers for class and style attributes.\n *\n * @example\n * ```typescript\n * html`<div class=\"${classMap({ box: true, 'box--active': this.active })}\"></div>`\n * html`<div style=\"${styleMap({ color: this.color, fontWeight: 'bold' })}\"></div>`\n * ```\n */\n/**\n * Build a class string from an object: keys with truthy values are included.\n */\nfunction classMap(classes) {\n let out = '';\n for (const name of Object.keys(classes)) {\n if (classes[name])\n out += (out ? ' ' : '') + name;\n }\n return out;\n}\n/**\n * Build a style string from an object. camelCase keys convert to kebab-case;\n * CSS custom properties (`--token`) pass through unchanged. Entries whose\n * value is null/undefined/false are dropped.\n */\nfunction styleMap(styles) {\n const decls = [];\n for (const key of Object.keys(styles)) {\n const value = styles[key];\n if (value === null || value === undefined || value === false)\n continue;\n const prop = key.startsWith('--')\n ? key\n : key.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());\n decls.push(`${prop}: ${value}`);\n }\n return decls.join('; ');\n}\n\n/**\n * Custom element readiness utilities\n * Handles waiting for custom elements to be defined with timeout warnings\n */\n/**\n * Global flag to disable custom element readiness timeout warnings\n * Set this to true in environments where slow element registration is expected\n */\nlet DISABLE_ELEMENT_READY_WARNINGS = false;\n/**\n * Set whether to disable custom element readiness timeout warnings\n */\nfunction setDisableElementReadyWarnings(value) {\n DISABLE_ELEMENT_READY_WARNINGS = value;\n}\n/**\n * Default timeout for custom element registration warning (500ms)\n */\nconst DEFAULT_WARNING_TIMEOUT = 500;\n/**\n * Wait for a custom element to be defined\n * Logs a warning if it takes longer than the warning timeout\n *\n * @param tagName - The custom element tag name\n * @param warningTimeout - Time in ms before warning (default 500ms)\n * @returns Promise that resolves when element is defined\n */\nasync function waitForElementDefined(tagName, warningTimeout = DEFAULT_WARNING_TIMEOUT) {\n // If already defined, return immediately\n if (customElements.get(tagName)) {\n return;\n }\n // Set up warning timer if not disabled\n let warningTimer = null;\n if (!DISABLE_ELEMENT_READY_WARNINGS) {\n warningTimer = setTimeout(() => {\n console.warn(`Custom element <${tagName}> is taking longer than ${warningTimeout}ms to register. ` +\n `This may indicate a missing import or circular dependency. ` +\n `Set DISABLE_ELEMENT_READY_WARNINGS=true to disable this warning.`);\n }, warningTimeout);\n }\n try {\n // Wait for element to be defined\n await customElements.whenDefined(tagName);\n }\n finally {\n // Clear warning timer\n if (warningTimer) {\n clearTimeout(warningTimer);\n }\n }\n}\n/**\n * Wait for a custom element to be defined and ready\n * First waits for the element to be registered, then waits for its ready promise\n *\n * @param element - The custom element instance\n * @param warningTimeout - Time in ms before warning about registration (default 500ms)\n * @returns Promise that resolves when element is defined and ready\n */\nasync function waitForElementReady(element, warningTimeout = DEFAULT_WARNING_TIMEOUT) {\n const tagName = element.tagName.toLowerCase();\n // Wait for element to be defined\n await waitForElementDefined(tagName, warningTimeout);\n // Wait for element's ready promise if it exists\n if ('ready' in element && typeof element.ready?.then === 'function') {\n await element.ready;\n }\n}\n/**\n * Process all custom elements in a node tree and wait for them to be ready\n * This is useful after inserting a template with custom elements\n *\n * @param node - The root node to scan for custom elements\n * @param warningTimeout - Time in ms before warning about registration (default 500ms)\n * @returns Promise that resolves when all custom elements are ready\n */\nasync function waitForAllCustomElements(node, warningTimeout = DEFAULT_WARNING_TIMEOUT) {\n const customElements = [];\n // Find all custom elements (tag names with hyphens)\n if (node instanceof Element) {\n if (node.tagName.includes('-')) {\n customElements.push(node);\n }\n // Also check in shadow DOM\n if (node.shadowRoot) {\n const shadowCustomElements = node.shadowRoot.querySelectorAll('*');\n shadowCustomElements.forEach(el => {\n if (el.tagName.includes('-')) {\n customElements.push(el);\n }\n });\n }\n }\n // If it's a DocumentFragment, check all children\n if (node instanceof DocumentFragment) {\n const elements = node.querySelectorAll('*');\n elements.forEach(el => {\n if (el.tagName.includes('-')) {\n customElements.push(el);\n }\n });\n }\n // Wait for all custom elements to be ready\n await Promise.all(customElements.map(el => waitForElementReady(el, warningTimeout)));\n}\n\n/**\n * Render debugging utilities for Snice v3.0.0\n * For testing and debugging only - not recommended for production use\n */\n/**\n * Track renders of an element using an async generator\n * Each call to tracker.next() waits for the next render to complete\n *\n * @example\n * ```typescript\n * const tracker = trackRenders(element);\n *\n * element.someProp = 'new value';\n * await tracker.next(); // Waits for render\n * // DOM is now updated\n *\n * element.someProp = 'another value';\n * await tracker.next(); // Waits for next render\n * // DOM is updated again\n * ```\n *\n * WARNING: For testing/debugging only!\n * - Do not use in production code\n * - The generator yields indefinitely - use it only in controlled test environments\n * - Each yield waits for the next render event\n */\nasync function* trackRenders(element) {\n while (true) {\n await new Promise(resolve => {\n if (!element[RENDER_CALLBACKS]) {\n element[RENDER_CALLBACKS] = [];\n }\n element[RENDER_CALLBACKS].push(resolve);\n });\n yield;\n }\n}\n\n/**\n * Shared body scroll-lock with refcounting.\n *\n * Multiple overlay components (drawer, modal, etc.) can each lock body\n * scroll independently. Without coordination, closing one overlay would\n * unlock scroll while another is still open. This utility increments\n * a module-scope counter on lock, decrements on unlock, and only mutates\n * `document.body.style.overflow` on the 0 ↔ 1 transitions. The original\n * overflow value is captured at the first lock and restored at the last\n * unlock — important because some pages set `overflow: scroll` for layout\n * and a naive `= ''` would clobber it.\n */\nlet count = 0;\nlet savedOverflow = null;\n// Test hook — `afterEach` in test suites can call `.clear()` to reset the\n// counter when document.body.innerHTML is wiped. The counter is module-scope,\n// so without this it survives across tests and the second test's first lock\n// would only increment instead of flipping `overflow: hidden`.\nconst TEST_HOOK = Symbol.for('snice:body-scroll-lock');\nglobalThis[TEST_HOOK] = {\n clear() {\n count = 0;\n savedOverflow = null;\n },\n};\nfunction lockBodyScroll() {\n if (count === 0) {\n savedOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n }\n count++;\n}\nfunction unlockBodyScroll() {\n if (count === 0)\n return;\n count--;\n if (count === 0) {\n document.body.style.overflow = savedOverflow ?? '';\n savedOverflow = null;\n }\n}\n/**\n * Test/debug only — peek at the current refcount.\n */\nfunction getBodyScrollLockCount() {\n return count;\n}\n\n/**\n * Context-aware fetch implementation with middleware support\n *\n * @example\n * ```typescript\n * const fetcher = new ContextAwareFetcher();\n *\n * fetcher.use('request', function(request, next) {\n * const token = this.application.user?.token;\n * if (token) {\n * request.headers.set('Authorization', `Bearer ${token}`);\n * }\n * return next();\n * });\n *\n * fetcher.use('response', async function(response, next) {\n * if (!response.ok) {\n * throw new Error(`HTTP ${response.status}`);\n * }\n * return next();\n * });\n *\n * const router = Router({\n * target: '#app',\n * context: { user: null },\n * fetcher\n * });\n * ```\n */\nclass ContextAwareFetcher {\n constructor() {\n this.requestMiddlewares = [];\n this.responseMiddlewares = [];\n }\n use(type, middleware) {\n if (type === 'request') {\n this.requestMiddlewares.push(middleware);\n return;\n }\n this.responseMiddlewares.push(middleware);\n }\n /**\n * Create a fetch function bound to the given Context instance\n * @param ctx - The Context instance to bind to\n * @returns A fetch function with middleware applied\n */\n create(ctx) {\n const requestMiddlewares = this.requestMiddlewares;\n const responseMiddlewares = this.responseMiddlewares;\n const fetchFn = async function (input, init) {\n const request = new Request(input, init);\n // Request middleware chain\n let reqIndex = 0;\n const nextRequest = async () => {\n if (reqIndex < requestMiddlewares.length) {\n const middleware = requestMiddlewares[reqIndex++];\n return middleware.call(this, request, nextRequest);\n }\n // Execute actual fetch\n const response = await fetch(request);\n // Response middleware chain\n let resIndex = 0;\n const nextResponse = async () => {\n if (resIndex < responseMiddlewares.length) {\n const middleware = responseMiddlewares[resIndex++];\n return middleware.call(this, response, nextResponse);\n }\n return response;\n };\n return nextResponse();\n };\n return nextRequest();\n };\n return fetchFn.bind(ctx);\n }\n}\n\n// v3.0.0 exports\n// Auto-enable native element controllers in browser environments\nif (typeof document !== 'undefined') {\n useNativeElementControllers();\n}\n// NOTE: @on decorator works in both elements AND controllers.\n// Supports event delegation, keyboard modifiers, debounce/throttle - see docs/events.md\n// Template event syntax (@click=${handler}) is also available as an alternative.\n\nexport { Context, ContextAwareFetcher, IS_CONTROLLER_INSTANCE, Router, SimpleArray, SniceElement, TransitionMode, adopted, applyElementFunctionality, attachController, classMap, clearDebounceTimers, clearMemoizeCache, clearThrottleTimers, context$1 as context, context as contextProperty, controller, createRequestHandler, css, debounce, detachController, dispatch, dispose, element, escapeAttr, escapeHtml, getBodyScrollLockCount, getController, getSymbol, html, isSafeUrl, layout, live, lockBodyScroll, memoize, moved, noChange, nothing, observe, on, once, parseDuration, property, query, queryAll, ready, reconnect, render, repeat, request, resetOnce, respond, setDisableElementReadyWarnings, setStrictRenderErrors, state, styleMap, styles, svg, throttle, trackRenders, unlockBodyScroll, unsafeHTML, useNativeElementControllers, waitForAllCustomElements, waitForElementDefined, waitForElementReady, watch };\n//# sourceMappingURL=index.esm.js.map\n","/*!\n * snice v6.1.0\n * A decorator-driven web component library with differential rendering, routing, controllers, and 130+ ready-made UI components. Use as much or as little as you want. Zero dependencies, works anywhere.\n * (c) 2024\n * Released under the MIT License.\n *\n * GENERATED FILE — DO NOT EDIT. Source: src/. Rebuild: npm run build:core\n */\n/**\n * Generic transition system for animating between elements\n */\nvar TransitionMode;\n(function (TransitionMode) {\n /** out transition completes before in transition starts */\n TransitionMode[\"SEQUENTIAL\"] = \"sequential\";\n /** both transitions happen at the same time */\n TransitionMode[\"SIMULTANEOUS\"] = \"simultaneous\";\n})(TransitionMode || (TransitionMode = {}));\n\n/**\n * Generic transition system for animating between elements\n */\n/**\n * Parse CSS property string into an object\n */\nfunction parseStyles(styleString) {\n const styles = {};\n styleString.split(';').forEach(rule => {\n const idx = rule.indexOf(':');\n if (idx === -1)\n return;\n const prop = rule.slice(0, idx).trim();\n const value = rule.slice(idx + 1).trim();\n if (prop && value) {\n styles[prop] = value;\n }\n });\n return styles;\n}\n/**\n * Perform a transition between two elements\n */\nfunction applyBaseTransitionStyles(el, isSlotted, duration, prop) {\n el.style.position = 'absolute';\n el.style.width = '100%';\n if (isSlotted) {\n el.style.height = '100%';\n el.style.transition = `opacity ${duration}ms ease-in-out`;\n return;\n }\n el.style.top = '0';\n el.style.left = '0';\n el.style.transition = `${prop} ${duration}ms ease-in-out`;\n}\nfunction resetTransitionStyles(el, isSlotted) {\n el.style.position = '';\n el.style.width = '';\n el.style.transition = '';\n if (isSlotted) {\n el.style.height = '';\n return;\n }\n el.style.top = '';\n el.style.left = '';\n}\nasync function performTransition(container, oldElement, newElement, transition = {}, \n/**\n * Called at each async boundary — if it returns true, this transition has\n * been superseded by a newer navigation. We abort cleanup so we don't tear\n * down elements now owned by the newer transition.\n */\nisStale = () => false) {\n const outDuration = transition.outDuration ?? 300;\n const inDuration = transition.inDuration ?? 300;\n const mode = (transition.mode || 'sequential');\n const outStyles = transition.out ? parseStyles(transition.out) : { opacity: '0' };\n const inStartStyles = { opacity: '0' };\n const inEndStyles = transition.in ? parseStyles(transition.in) : { opacity: '1' };\n const containerStyle = container.style;\n const isLayoutElement = container.tagName.includes('-') && container.shadowRoot;\n // Track the position we were ORIGINALLY given, not what a concurrent\n // transition may have already written. The first transition to touch this\n // container wins; subsequent overlapping transitions reuse the same value\n // and the last one to finish restores it.\n const POS_KEY = Symbol.for('snice:transition-original-position');\n const POS_COUNT = Symbol.for('snice:transition-count');\n const c = container;\n if (!isLayoutElement) {\n if (!(POS_KEY in c)) {\n c[POS_KEY] = containerStyle.position;\n c[POS_COUNT] = 0;\n }\n c[POS_COUNT]++;\n containerStyle.position = 'relative';\n }\n const restorePosition = () => {\n if (isLayoutElement)\n return;\n c[POS_COUNT]--;\n if (c[POS_COUNT] <= 0) {\n containerStyle.position = c[POS_KEY];\n delete c[POS_KEY];\n delete c[POS_COUNT];\n }\n };\n const isSlotted = oldElement.hasAttribute('slot') || newElement.hasAttribute('slot');\n applyBaseTransitionStyles(oldElement, isSlotted, outDuration, 'all');\n applyBaseTransitionStyles(newElement, isSlotted, inDuration, 'all');\n Object.assign(newElement.style, inStartStyles);\n container.appendChild(newElement);\n void newElement.offsetHeight;\n // Animate\n switch (mode) {\n case TransitionMode.SIMULTANEOUS:\n Object.assign(oldElement.style, outStyles);\n Object.assign(newElement.style, inEndStyles);\n await new Promise(resolve => setTimeout(resolve, Math.max(outDuration, inDuration)));\n break;\n case TransitionMode.SEQUENTIAL:\n Object.assign(oldElement.style, outStyles);\n await new Promise(resolve => setTimeout(resolve, outDuration));\n if (isStale()) {\n if (newElement.parentNode === container)\n newElement.remove();\n restorePosition();\n return;\n }\n Object.assign(newElement.style, inEndStyles);\n await new Promise(resolve => setTimeout(resolve, inDuration));\n break;\n }\n if (isStale()) {\n // A newer navigation took over while we were animating. Don't touch\n // oldElement (the newer transition owns it now) and remove OUR newElement\n // since the newer transition appended its own.\n if (newElement.parentNode === container)\n newElement.remove();\n restorePosition();\n return;\n }\n // Cleanup\n oldElement.remove();\n resetTransitionStyles(newElement, isSlotted);\n Object.keys({ ...inStartStyles, ...inEndStyles }).forEach(prop => {\n newElement.style[prop] = '';\n });\n restorePosition();\n}\n/**\n * Predefined transitions\n */\n// Fade transition\nconst fadeTransition = {\n name: 'fade',\n outDuration: 200,\n inDuration: 200,\n out: 'opacity: 0',\n in: 'opacity: 1',\n mode: 'simultaneous'\n};\n// Slide transition (from left)\nconst slideTransition = {\n name: 'slide',\n outDuration: 300,\n inDuration: 300,\n out: 'transform: translateX(-100%)',\n in: 'transform: translateX(0)',\n mode: 'sequential'\n};\n// Slide from right\nconst slideRightTransition = {\n name: 'slide-right',\n outDuration: 300,\n inDuration: 300,\n out: 'transform: translateX(100%)',\n in: 'transform: translateX(0)',\n mode: 'sequential'\n};\n// Slide from top\nconst slideUpTransition = {\n name: 'slide-up',\n outDuration: 300,\n inDuration: 300,\n out: 'transform: translateY(-100%)',\n in: 'transform: translateY(0)',\n mode: 'sequential'\n};\n// Slide from bottom\nconst slideDownTransition = {\n name: 'slide-down',\n outDuration: 300,\n inDuration: 300,\n out: 'transform: translateY(100%)',\n in: 'transform: translateY(0)',\n mode: 'sequential'\n};\n// Scale transition\nconst scaleTransition = {\n name: 'scale',\n outDuration: 250,\n inDuration: 250,\n out: 'transform: scale(0.9); opacity: 0',\n in: 'transform: scale(1); opacity: 1',\n mode: 'simultaneous'\n};\n// Rotate transition\nconst rotateTransition = {\n name: 'rotate',\n outDuration: 400,\n inDuration: 400,\n out: 'transform: rotate(180deg) scale(0.5); opacity: 0',\n in: 'transform: rotate(0) scale(1); opacity: 1',\n mode: 'simultaneous'\n};\n// Flip transition\nconst flipTransition = {\n name: 'flip',\n outDuration: 400,\n inDuration: 400,\n out: 'transform: rotateY(180deg); opacity: 0',\n in: 'transform: rotateY(0); opacity: 1',\n mode: 'sequential'\n};\n// Zoom transition\nconst zoomTransition = {\n name: 'zoom',\n outDuration: 300,\n inDuration: 300,\n out: 'transform: scale(2); opacity: 0',\n in: 'transform: scale(1); opacity: 1',\n mode: 'simultaneous'\n};\n// None transition (instant swap)\nconst noneTransition = {\n name: 'none',\n outDuration: 0,\n inDuration: 0,\n out: '',\n in: '',\n mode: 'simultaneous'\n};\n\nexport { TransitionMode, fadeTransition, flipTransition, noneTransition, parseStyles, performTransition, rotateTransition, scaleTransition, slideDownTransition, slideRightTransition, slideTransition, slideUpTransition, zoomTransition };\n//# sourceMappingURL=transitions.esm.js.map\n","/*!\n * snice v6.1.0\n * A decorator-driven web component library with differential rendering, routing, controllers, and 130+ ready-made UI components. Use as much or as little as you want. Zero dependencies, works anywhere.\n * (c) 2024\n * Released under the MIT License.\n *\n * GENERATED FILE — DO NOT EDIT. Source: src/. Rebuild: npm run build:core\n */\n// Global namespace for Snice framework\n// Ensures all registries and symbols are shared across different JS files/modules\n// Initialize the global Snice namespace on globalThis\n// This ensures all module instances share the same registry\nif (!globalThis.snice) {\n globalThis.snice = {\n controllerRegistry: new Map(),\n pendingControllerAttachments: new Map(),\n controllerIdCounter: 0\n };\n}\n// Multiple copies of Snice can share a global created by an older build.\nglobalThis.snice.pendingControllerAttachments ??= new Map();\n// Helper function to get or create a global symbol\n// Symbol.for() already guarantees global uniqueness, no need for a Map cache\nfunction getSymbol(name) {\n return Symbol.for(`snice:${name}`);\n}\n\n// Central file for all symbols used in the framework\n// All symbols are stored globally to ensure consistency across modules\nconst IS_CONTROLLER_CLASS = getSymbol('is-controller-class');\nconst IS_CONTROLLER_INSTANCE = getSymbol('is-controller-instance');\nconst IS_ELEMENT_CLASS = getSymbol('is-element-class');\nconst CHANNEL_HANDLERS = getSymbol('channel-handlers');\n// Internal element state symbols\nconst READY_PROMISE = getSymbol('ready-promise');\nconst READY_RESOLVE = getSymbol('ready-resolve');\nconst RENDERED_PROMISE = getSymbol('rendered-promise');\nconst RENDERED_RESOLVE = getSymbol('rendered-resolve');\n// Set when a render is requested but dropped because the element was\n// disconnected; consumed on reconnect to replay exactly the missed render.\nconst PENDING_RECONNECT_RENDER = getSymbol('pending-reconnect-render');\n// Per-element synchronous render-nesting depth, used to cap runaway re-entry\n// without a shared global counter that one element could exhaust for others.\nconst RENDER_DEPTH = getSymbol('render-depth');\nconst RENDER_ROOT = getSymbol('render-root');\nconst ELEMENT_OPTIONS = getSymbol('element-options');\nconst CONTROLLER = getSymbol('controller');\nconst INITIALIZED = getSymbol('initialized');\n// Event handler symbols\nconst ON_HANDLERS = getSymbol('on-handlers');\n// Controller symbols\nconst CONTROLLER_KEY = getSymbol('controller-key');\nconst CONTROLLER_NAME_KEY = getSymbol('controller-name');\nconst CONTROLLER_ID = getSymbol('controller-id');\nconst CONTROLLER_OPERATIONS = getSymbol('controller-operations');\nconst NATIVE_CONTROLLER = getSymbol('native-controller');\n// Set while a controller CLASS (not a registry name) is attached — the\n// attribute/MutationObserver channel must not attach over or detach it.\nconst DIRECT_CONTROLLER = getSymbol('direct-controller');\n// A controller class bound by a template before the custom element was\n// defined/upgraded. Picked up by connectedCallback on first initialization.\nconst PENDING_CONTROLLER_BINDING = getSymbol('pending-controller-binding');\n// Cleanup symbol - holds an object with all cleanup arrays\nconst CLEANUP = getSymbol('cleanup');\n// Property symbols\nconst PROPERTIES = getSymbol('properties');\nconst PROPERTY_VALUES = getSymbol('property-values');\nconst PROPERTY_DEFAULTS = getSymbol('property-defaults');\nconst PROPERTY_WRAPPERS = getSymbol('property-wrappers');\nconst PRE_INIT_PROPERTY_VALUES = getSymbol('pre-init-property-values');\nconst PRE_UPGRADE_PROPERTY_BINDINGS = getSymbol('pre-upgrade-property-bindings');\nconst PROPERTIES_INITIALIZED = getSymbol('properties-initialized');\nconst PROPERTY_WATCHERS = getSymbol('property-watchers');\nconst EXPLICITLY_SET_PROPERTIES = getSymbol('explicitly-set-properties');\n// Router context symbol\nconst ROUTER_CONTEXT = getSymbol('router-context');\nconst CURRENT_PAGE_MARKER = getSymbol('current-page-marker');\nconst CONTEXT_REQUEST_HANDLER = getSymbol('context-request-handler');\nconst PAGE_TRANSITION = getSymbol('page-transition');\nconst CREATED_AT = getSymbol('created-at');\n// Lifecycle symbols\nconst READY_HANDLERS = getSymbol('ready-handlers');\nconst DISPOSE_HANDLERS = getSymbol('dispose-handlers');\nconst RECONNECT_HANDLERS = getSymbol('reconnect-handlers');\nconst MOVED_HANDLERS = getSymbol('moved-handlers');\nconst ADOPTED_HANDLERS = getSymbol('adopted-handlers');\n// Observer symbols\nconst OBSERVERS = getSymbol('observers');\n// Part symbols\nconst PARTS = getSymbol('parts');\nconst PART_TIMERS = getSymbol('part-timers');\n// Property setter flag (prevents attributeChangedCallback re-triggering watchers)\nconst SETTING_FROM_PROPERTY = getSymbol('setting-from-property');\n// Lifecycle callback timers\nconst MOVED_TIMERS = getSymbol('moved-timers');\nconst ADOPTED_TIMERS = getSymbol('adopted-timers');\n// Dispatch timing symbols\nconst DISPATCH_TIMERS = getSymbol('dispatch-timers');\n// Render symbols (v3.0.0)\nconst RENDER_METHOD = getSymbol('render-method');\nconst RENDER_OPTIONS = getSymbol('render-options');\nconst RENDER_INSTANCE = getSymbol('render-instance');\nconst RENDER_TIMERS = getSymbol('render-timers');\nconst RENDER_CALLBACKS = getSymbol('render-callbacks');\nconst STYLES_METHOD = getSymbol('styles-method');\nconst STYLES_APPLIED = getSymbol('styles-applied');\nconst PARENT_STYLES_METHODS = getSymbol('parent-styles-methods');\nconst SNICE_ELEMENT_BASE = getSymbol('snice-element-base');\n// Navigation context symbols\nconst CONTEXT_HANDLER = getSymbol('context-handler');\nconst CONTEXT_METHOD_NAME = getSymbol('context-method-name');\nconst NAVIGATION_CONTEXT_INSTANCE = getSymbol('navigation-context-instance');\nconst REGISTERED_ELEMENTS = getSymbol('registered-elements');\nconst IS_UPDATING = getSymbol('is-updating');\nconst CONTEXT_REGISTER = getSymbol('context-register');\nconst CONTEXT_UNREGISTER = getSymbol('context-unregister');\nconst CONTEXT_NOTIFY_ELEMENT = getSymbol('context-notify-element');\nconst CONTEXT_OPTIONS = getSymbol('context-options');\nconst CONTEXT_TIMER = getSymbol('context-timer');\nconst CONTEXT_CALLED = getSymbol('context-called');\nconst CONTEXT_UPDATE = getSymbol('context-update');\n// Registration de-dup sets on the constructor — replace previous `__*Methods`\n// expando strings that violated the no-double-underscore rule.\nconst CONTEXT_METHODS = getSymbol('context-methods');\nconst WATCH_METHODS = getSymbol('watch-methods');\nconst OBSERVE_METHODS = getSymbol('observe-methods');\nconst ON_METHODS = getSymbol('on-methods');\nconst RESPOND_METHODS = getSymbol('respond-methods');\nconst READY_METHODS = getSymbol('ready-methods');\nconst DISPOSE_METHODS = getSymbol('dispose-methods');\nconst RECONNECT_METHODS = getSymbol('reconnect-methods');\nconst MOVED_METHODS = getSymbol('moved-methods');\nconst ADOPTED_METHODS = getSymbol('adopted-methods');\n// Controller attach-abort — set to an AbortController while attachController\n// is awaiting element.ready, so detachController can short-circuit the wait.\nconst CONTROLLER_ABORT = getSymbol('controller-abort');\n// Set on a controller instance once it has gotten past element.ready and is\n// being attached, so detachController knows not to run detach() on a controller\n// whose attach() was aborted before it ever ran.\nconst CONTROLLER_ATTACHED = getSymbol('controller-attached');\nconst PROPERTY_DEFINERS = getSymbol('property-definers');\n\nexport { ADOPTED_HANDLERS, ADOPTED_METHODS, ADOPTED_TIMERS, CHANNEL_HANDLERS, CLEANUP, CONTEXT_CALLED, CONTEXT_HANDLER, CONTEXT_METHODS, CONTEXT_METHOD_NAME, CONTEXT_NOTIFY_ELEMENT, CONTEXT_OPTIONS, CONTEXT_REGISTER, CONTEXT_REQUEST_HANDLER, CONTEXT_TIMER, CONTEXT_UNREGISTER, CONTEXT_UPDATE, CONTROLLER, CONTROLLER_ABORT, CONTROLLER_ATTACHED, CONTROLLER_ID, CONTROLLER_KEY, CONTROLLER_NAME_KEY, CONTROLLER_OPERATIONS, CREATED_AT, CURRENT_PAGE_MARKER, DIRECT_CONTROLLER, DISPATCH_TIMERS, DISPOSE_HANDLERS, DISPOSE_METHODS, ELEMENT_OPTIONS, EXPLICITLY_SET_PROPERTIES, INITIALIZED, IS_CONTROLLER_CLASS, IS_CONTROLLER_INSTANCE, IS_ELEMENT_CLASS, IS_UPDATING, MOVED_HANDLERS, MOVED_METHODS, MOVED_TIMERS, NATIVE_CONTROLLER, NAVIGATION_CONTEXT_INSTANCE, OBSERVERS, OBSERVE_METHODS, ON_HANDLERS, ON_METHODS, PAGE_TRANSITION, PARENT_STYLES_METHODS, PARTS, PART_TIMERS, PENDING_CONTROLLER_BINDING, PENDING_RECONNECT_RENDER, PRE_INIT_PROPERTY_VALUES, PRE_UPGRADE_PROPERTY_BINDINGS, PROPERTIES, PROPERTIES_INITIALIZED, PROPERTY_DEFAULTS, PROPERTY_DEFINERS, PROPERTY_VALUES, PROPERTY_WATCHERS, PROPERTY_WRAPPERS, READY_HANDLERS, READY_METHODS, READY_PROMISE, READY_RESOLVE, RECONNECT_HANDLERS, RECONNECT_METHODS, REGISTERED_ELEMENTS, RENDERED_PROMISE, RENDERED_RESOLVE, RENDER_CALLBACKS, RENDER_DEPTH, RENDER_INSTANCE, RENDER_METHOD, RENDER_OPTIONS, RENDER_ROOT, RENDER_TIMERS, RESPOND_METHODS, ROUTER_CONTEXT, SETTING_FROM_PROPERTY, SNICE_ELEMENT_BASE, STYLES_APPLIED, STYLES_METHOD, WATCH_METHODS, getSymbol };\n//# sourceMappingURL=symbols.esm.js.map\n"],"names":["globalThis","snice","controllerRegistry","Map","pendingControllerAttachments","controllerIdCounter","getSymbol","name","Symbol","for","IS_CONTROLLER_CLASS","IS_CONTROLLER_INSTANCE","IS_ELEMENT_CLASS","CHANNEL_HANDLERS","READY_PROMISE","READY_RESOLVE","RENDERED_PROMISE","RENDERED_RESOLVE","PENDING_RECONNECT_RENDER","RENDER_DEPTH","RENDER_ROOT","ELEMENT_OPTIONS","CONTROLLER","INITIALIZED","CONTROLLER_KEY","CONTROLLER_NAME_KEY","CONTROLLER_ID","CONTROLLER_OPERATIONS","NATIVE_CONTROLLER","DIRECT_CONTROLLER","PENDING_CONTROLLER_BINDING","CLEANUP","PROPERTIES","PROPERTY_VALUES","PROPERTY_DEFAULTS","PROPERTY_WRAPPERS","PRE_INIT_PROPERTY_VALUES","PRE_UPGRADE_PROPERTY_BINDINGS","PROPERTIES_INITIALIZED","PROPERTY_WATCHERS","EXPLICITLY_SET_PROPERTIES","ROUTER_CONTEXT","PAGE_TRANSITION","CREATED_AT","READY_HANDLERS","DISPOSE_HANDLERS","RECONNECT_HANDLERS","MOVED_HANDLERS","ADOPTED_HANDLERS","OBSERVERS","SETTING_FROM_PROPERTY","MOVED_TIMERS","ADOPTED_TIMERS","DISPATCH_TIMERS","RENDER_METHOD","RENDER_OPTIONS","RENDER_INSTANCE","RENDER_TIMERS","RENDER_CALLBACKS","STYLES_METHOD","STYLES_APPLIED","PARENT_STYLES_METHODS","SNICE_ELEMENT_BASE","CONTEXT_HANDLER","NAVIGATION_CONTEXT_INSTANCE","REGISTERED_ELEMENTS","IS_UPDATING","CONTEXT_REGISTER","CONTEXT_UNREGISTER","CONTEXT_NOTIFY_ELEMENT","CONTEXT_TIMER","CONTEXT_CALLED","CONTEXT_UPDATE","CONTEXT_METHODS","WATCH_METHODS","OBSERVE_METHODS","ON_METHODS","RESPOND_METHODS","READY_METHODS","DISPOSE_METHODS","RECONNECT_METHODS","MOVED_METHODS","ADOPTED_METHODS","CONTROLLER_ABORT","CONTROLLER_ATTACHED","PROPERTY_DEFINERS","SimpleArray","this","SEPARATOR","serialize","arr","Array","isArray","map","item","includes","Error","String","join","parse","str","split","test","num","Number","isNaN","_a","_b","_c","TransitionMode","REGISTERED_ELEMENTS_SET","contextIdCounter","Context","constructor","context","placards","currentRoute","routeParams","fetcher","WeakMap","Set","id","application","navigation","route","params","create","fetch","bind","element","methodName","names","get","set","add","undefined","delete","size","notify","update","elementsSet","elementsMap","error","console","detectType","initialValue","Boolean","Date","BigInt","parseAttributeValue","attributeValue","propertyOptions","currentValue","typeToUse","type","converter","fromAttribute","endsWith","slice","JSON","Object","notEqual","value","old","getAttrName","opts","propName","attribute","toLowerCase","attributeNaming","replace","ensureSet","obj","sym","ensureObj","invokeWatchers","instance","oldValue","newValue","watchers","keys","propOpts","attrName","push","key","has","w","method","call","e","createDebounced","fn","delay","timer","args","clearTimeout","setTimeout","apply","createThrottled","lastCall","now","remaining","resolveScope","host","scope","document","closest","addEventListener","valueToAttribute","length","toAttribute","toISOString","toString","stringify","validatedWatchClasses","WeakSet","mediaQueryCache","setupObservers","observers","events","channels","observer","callback","options","throttle","setupIntersectionObserver","setupResizeObserver","setupMediaQueryObserver","setupMutationObserver","warn","threshold","rootMargin","root","IntersectionObserver","io","entries","entry","unobserve","target","targets","selector","from","shadowRoot","querySelectorAll","forEach","observe","takeRecords","disconnect","box","ResizeObserver","ro","_element","mediaQuery","mql","window","matchMedia","wrappedCallback","event","matches","changeHandler","removeEventListener","addListener","removeListener","parts","mutationType","attributeName","childList","attributes","attributeFilter","subtree","maxDepth","needsDepthFilter","mo","MutationObserver","mutations","filtered","filter","mutation","depth","current","parentNode","isController","cleanupObservers","cleanup","setupResponseHandlers","handlers","handler","boundMethod","eventName","channelName","debounceTimeout","throttleTimeout","throttleLastCall","throttleTrailingResolvers","throttleLatestArgs","timedMethod","originalMethod","debounce","Promise","resolve","reject","async","orphaned","splice","result","then","r","x","resolvers","finalArgs","createTimedMethod","responseHandler","data","discovery","payload","detail","preventDefault","stopImmediatePropagation","stopPropagation","catch","cleanupResponseHandlers","HTML_RESULT","CSS_RESULT","cssResultCache","isTemplateResult","_$litType$","isCSSResult","nothing","UNSAFE_HTML","isUnsafeHTML","REPEAT_RESULT","renderHosts","getRenderRoot","ensureRenderRoot","existing","renderRoot","shadow","createRenderRoot","attachShadow","mode","delegatesFocus","ShadowRoot","TypeError","findRenderHost","node","getRootNode","HTMLElement","marker","Math","random","toFixed","markerMatch","nodeMarker","markerRegex","RegExp","templateCache","NOT_COMMITTED","markPreUpgradePropertyBinding","propertyName","tagName","localName","registry","ownerDocument","defaultView","customElements","noChange","LIVE_MARKER","isPrimitive","isAsyncIterable","asyncIterator","Template","attrNamesForParts","keyIndex","walker","createTreeWalker","content","NodeFilter","SHOW_ELEMENT","SHOW_COMMENT","SHOW_TEXT","partIndex","nodesToRemove","nextNode","nodeType","Node","ELEMENT_NODE","parentTag","parentElement","valueAttr","getAttribute","removeAttribute","index","child","childNodes","branchTag","TEXT_NODE","textContent","trim","COMMENT_NODE","hasAttributes","attrsToRemove","i","attr","originalName","attrStrings","expressionCount","startsWith","hasStaticText","some","s","spreadName","comment","parent","endNode","createComment","insertBefore","nextSibling","startNode","commentStrings","text","lastIndex","createTextNode","removeChild","part","prepareTemplate","strings","cached","htmlParts","inTag","inAttrValue","inComment","attrQuoteChar","currentAttrName","j","char","attrStart","substring","trimmed","trimEnd","match","html","template","createElement","svg","innerHTML","wrapper","firstElementChild","firstChild","tmpl","getItemKey","values","TemplateInstance","fragment","conditionalParts","regularParts","isSameTemplate","renderFragment","cloneNode","SHOW_ALL","clonedWalker","nodeMap","templateNode","currentNode","clonedNode","dynamicWhenElements","definition","partDef","NodePart","attrElement","AttributePart","propElement","PropertyPart","boolElement","BooleanAttributePart","eventElement","EventPart","classElement","ClassPart","styleElement","StylePart","spreadElement","SpreadPart","controllerElement","ControllerPart","conditionalIfElement","ConditionalIfPart","conditionalElseIfElement","ConditionalElseIfPart","conditionalCaseElement","ConditionalCasePart","conditionalWhenElement","ConditionalWhenPart","commentNode","CommentPart","render","commit","flushed","coordinator","flush","lifecycleError","isConnected","reconnected","disconnected","clear","destroy","preserveEventListeners","Part","_preserveEventListeners","super","_committedValue","_itemKeys","_asyncSource","_asyncVersion","_asyncIterator","_asyncRunning","_asyncStarted","_asyncCompleted","_asyncPaused","_committingAsyncValue","isPromiseLike","_commitAsync","_cancelAsync","_commitText","_commitTemplateResult","_$repeat$","isRepeatResult","empty","_commitIterable","_commitUnsafeHTML","iterator","isIterable","_commitNode","cleanupError","_clear","textNode","_insertBefore","committedInstance","cachedTemplate","previousValue","previousKeys","previousFragment","createDocumentFragment","previousNode","next","appendChild","remove","_disposeCommitted","explicitKeys","items","newKeys","definedKeys","allKeyed","every","k","oldKeys","_reconcileKeyed","itemParts","itemPart","startMarker","endMarker","oldParts","oldByKey","reused","newParts","fill","candidate","ref","range","stop","prev","temp","source","_startAsyncSource","forceConnected","version","done","_commitAsyncValue","clearSource","return","committed","lastValues","lastValueIndex","valueIndex","finalValue","change","committedValues","v","_commitValue","setAttribute","_committedValues","startIndex","vals","enabled","classList","toggle","is","style","removeProperty","setProperty","listeners","consumedOnce","commitEvents","commitProperties","commitAttributes","prototype","hasOwnProperty","label","rawName","handleEvent","validateSpreadEvents","find","listener","listenerObject","once","resolveHost","detachListeners","_$liveMarker$","isLive","first","previous","el","controller","_detach","hasAttribute","_apply","controllerClass","_attach","ready","attachController","detachController","boolValue","listenerOptions","keyFilter","modifiers","onceConsumed","eventSpec","modifierSpecs","aliases","preventdefault","stoppropagation","stopimmediatepropagation","allowed","raw","normalized","isKeyboardEvent","dotIndex","indexOf","colonIndex","delimiterIndex","min","max","baseEvent","keySpec","parseKeyboardFilter","warnIfModifierMisuse","isListenerObject","passive","attachListener","matchesKeyboardFilter","valueOptions","capture","signal","detachListener","MODIFIER_WORDS","dot","lastIndexOf","suffix","spec","anyModifiers","lower","ctrl","alt","shift","meta","normalizeKey","esc","escape","enter","space","spacebar","up","down","left","right","arrowup","arrowdown","arrowleft","arrowright","del","backspace","tab","home","end","pageup","pagedown","ctrlKey","altKey","shiftKey","metaKey","NOT_SET","ifElement","conditions","branches","defaultBranch","currentBranch","primary","sawAlternative","lastBranch","tag","conditionalElseIfOwners","setAlternative","collectCurrent","hasChildNodes","owner","caseElement","children","childTag","dynamic","expected","conditionalWhenOwners","setExpected","findIndex","branch","ON_HANDLERS","throttle$1","NON_BUBBLING_EVENTS","setupEventHandlers","targetElement","cleanupEventHandlers","currentMethod","handlerOptions","baseEventName","keyModifier","keyModifierMethod","createKeyModifierHandler","hasExplicitScope","scopedTarget","eventRoot","delegatedHandler","needsCapture","handledSymbol","wrappedMethod","ControllerScope","cleanupFns","pendingOperations","register","unregister","all","runOperation","operation","promise","voidPromise","deferControllerAttachment","controllerName","queueMicrotask","nativeName","pending","controllerLabel","existingController","nativeController","ControllerClass","controllerInstance","controllerId","routerContext","abort","AbortController","race","_","onAbort","aborted","timerId","attach","dispatchEvent","CustomEvent","pendingAbort","controllerSource","detach","useNativeElementControllers","sniceNativeControllersInitialized","processElement","currentControllerName","message","debug","addedNodes","startObserving","body","readyState","sniceNativeControllerObserver","CONTEXT_HANDLERS","setupContextHandler","ctx","wrappedMethodName","called","callMethod","timerSlot","timerKey","timeout","strictRenderErrors","ensureRenderedPromise","resolveRendered","renderScheduler","scheduled","schedule","sync","performRender","elements","hasRendered","flushRenderCallbacks","callbacks","cbs","cb","MAX_RENDER_DEPTH","precomputedResult","hasPrecomputedResult","arguments","renderMethod","differential","removable","nextInstance","nextFragment","requestRender","immediate","reconnectRenderTree","lastThrottle","timers","throttleTimer","DEBOUNCE_TIMERS","THROTTLE_TIMERS","ONCE_CALLED","MEMOIZE_CACHE","clearDebounceTimers","clearThrottleTimers","invariantValue","property","descriptor","Reflect","getOwnPropertyDescriptor","configurable","locked","writable","applyElementFunctionality","originalConnectedCallback","connectedCallback","originalDisconnectedCallback","disconnectedCallback","originalAttributeChangedCallback","attributeChangedCallback","observedAttributes","properties","propOptions","defineProperty","enumerable","reconnectHandlers","attrValue","propValue","pendingControllerClass","pendingLabel","stylesMethod","staticResults","constructors","Function","unshift","getPrototypeOf","styles","allResults","parentMethods","existingStyles","cssText","styleSheet","adoptedStyleSheets","applyStyles","valid","known","validateWatchedProperties","invokeImmediateWatchers","readyHandlers","disconnectRenderTree","disposeHandlers","cleanupContextHandler","hadPending","clearRenderTimers","t","latestDetail","clearDispatchTimers","clearLifecycleTimers","defaultValue","parsedValue","wrap","hasChanged","connectedMoveCallback","movedHandlers","adoptedCallback","adoptedHandlers","defineElement","ancestors","reverse","ancestor","formAssociated","mergeParentMetadata","metadata","_pendingProperties","pop","inheritedOptions","ownOptions","mergedOptions","renderOptions","SNICE_DEBUG","define","nativeOwnPropertyDefaults","_value","propertyKey","markedBindings","wasTemplateBoundBeforeUpgrade","hasOwnValue","hadPreUpgradeValue","defaults","nativeElement","ownKeys","isNativeOwnPropertyDefault","preUpgradeValue","finalOptions","propertyAttributeNaming","notifyDeepMutation","reflect","attrKey","deep","wrapped","changed","cache","rawByProxy","unwrap","input","proxy","methods","Proxy","invariant","existed","deleted","thisArg","entryValue","isPlainObject","receiver","deleteProperty","nextDescriptor","second","firstIsData","descriptorsEqual","createDeepReactive","proto","definers","existingDefiner","incomingValue","wrappedInitialValue","getQueryRoot","registerHandler","handlersSymbol","methodsSymbol","extra","addInitializer","inherited","timersSymbol","debounceTimer","lastThrottleCall","createLifecycleDecorator","exec","a","execDeferred","moved","adopted","SniceElement","invalidate","rendered","renderNow","Route","pattern","parsed","parsePattern","pathPattern","queryPattern","queryOptional","queryIndex","pathSegments","parseSegments","querySegments","parseQuerySegments","segments","optionalSegments","endIndex","parseOptionalGroup","paramEndIndex","parseIdentifier","splatName","splatEndIndex","literalEndIndex","parseLiteral","cleanPattern","parseQueryLiteral","getAllParamNames","paramNames","collectParams","segment","canMatchRemainingSegments","path","pathIndex","literalIndex","url","pathPart","queryPart","pathParams","matchPath","queryParams","matchQuery","allParams","paramName","assign","remainingSegments","matchResult","matchSegment","nextIndex","nextSegment","stopChars","literalStart","decodeURIComponent","firstDotIndex","lastSlashIndex","lastSlash","findFirstLiteral","segs","seg","nested","firstLiteral","tempIndex","allMatched","innerSegment","remainingInner","innerResult","findNextLiteral","query","pathResult","reverseSegments","queryResult","inActivatedStructure","hasAllParams","hasLaterOptionalGroupNeedingParams","optionalResult","laterSegments","currentOptionalSegments","hasAnyParamInSegments","hasOnlyLiteralsAndOptionals","hasDirectParams","hasNestedParams","missingDirectParam","passToNested","hasOnlyOptionalMissingParams","routeSpecificity","score","parseStyles","styleString","rule","idx","prop","applyBaseTransitionStyles","isSlotted","duration","position","width","height","transition","top","RouteResult","DISABLE_ELEMENT_READY_WARNINGS","waitForElementDefined","warningTimeout","warningTimer","whenDefined","waitForElementReady","count","savedOverflow","TEST_HOOK","requestMiddlewares","responseMiddlewares","use","middleware","init","request","Request","reqIndex","nextRequest","response","resIndex","nextResponse","win","doc","routes","_404","_403","is_sorted","currentLayoutName","currentLayoutTimestamp","navigationContext","getCurrentLayoutElement","layoutElements","guards","layout","placard","collectPlacards","seen","p","emitContextUpdate","currentPath","getPath","location","hash","pathname","renderForbiddenPage","newPageElement","div","className","checkGuards","stale","guardsArray","spinner","spinnerTimer","container","createLoadingSpinner","guard","renderPage","pageElement","layoutToUse","pageLayout","layoutElement","needsNewLayout","timestamp","setupLayout","finalTransition","currentLayout","updateLayout","oldPageInLayout","querySelector","performTransition$1","page","renderWithLayout","currentElementInTarget","renderDirect","navGeneration","navigate","myGen","scrollTo","homeRoute","createHomeElement","routeResult","GUARDS_FAILED","SUCCESS","NOT_FOUND","resolveRoute","create404Element","oldElement","newElement","atGen","isStale","outDuration","inDuration","outStyles","out","opacity","inStartStyles","inEndStyles","in","containerStyle","isLayoutElement","POS_KEY","POS_COUNT","c","restorePosition","SIMULTANEOUS","SEQUENTIAL","resetTransitionStyles","performTransition","pageOptions","elementConnectedCallback","elementDisconnectedCallback","initialize","sort","b","setupEventListeners","classes","hasOwn","bubbles","cancelable","_context","cleanups","ce","CSSStyleSheet","Document","sheet","replaceSync","wait","leading","trailing","maxWait","isFirstCall","startTime","shouldInvokeFromMaxWait","lastArgs","doDispatch","dispatchOnUndefined","composed","timedDispatch","d","resolvedResult","URL","hasExplicitScheme","isNetworkPathReference","protocol","overflow","keyGenerator","maxSize","ttl","firstKey","observeTarget","selectorOrOptions","observeTargets","targetString","targetStr","eventNames","registrationKey","perInstance","globalResult","globalCalled","parseFloat","ms","milliseconds","seconds","minutes","light","managedRoot","results","array","requestName","actualRequest","responseTimeout","discoveryTimeout","generator","dataResolve","dataReject","dataPromise","discoveryResolve","discoveryReject","discoveryTimeoutId","discovered","discoveryPromise","responseTimeoutId","optional","recovered","throw","decls","lastInvoke","timeSinceLastInvoke","Element","DocumentFragment","propertyNames","registered","copy"],"mappings":"mCAYKA,WAAWC,QACZD,WAAWC,MAAQ,CACfC,mBAAoB,IAAIC,IACxBC,6BAA8B,IAAID,IAClCE,oBAAqB,IAI7BL,WAAWC,MAAMG,+BAAiC,IAAID,IAEtD,MAAMF,EAAQD,WAAWC,MAGzB,SAASK,EAAUC,GAC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slB,UAC3B,OAAO,SAAUvkB,EAAQ5H,GACrB,MAAMgB,EAAahB,EAAQ3G,KAC3B2G,EAAQ40B,eAAe,WACnB,MAAM70B,EAAc1B,KAAK0B,YAOpB+C,OAAO4b,UAAUC,eAAeja,KAAK3E,EAAavC,MACnDuC,EAAYvC,IAAiB,IAAIvE,KAErC,IAAI0uC,EAAa5nC,EAAYvC,IAAe0D,IAAI0G,GAKhD,GAJK+/B,IACDA,EAAa,IAAIrnC,IACjBP,EAAYvC,IAAe2D,IAAIyG,EAAQ+/B,KAEtC7kC,OAAO4b,UAAUC,eAAeja,KAAK3E,EAAa1E,GAAoB,CAIvE,MAAMw5B,EAAY90B,EAAY1E,GACxBusC,EAAO,IAAI3uC,IACjB,GAAI47B,EACA,IAAK,MAAOvwB,EAAK9F,KAAQq2B,EACrB+S,EAAKzmC,IAAImD,EAAK,IAAI9F,IAE1BuB,EAAY1E,GAAqBusC,CACrC,CACA,IAAK,MAAMx4B,KAAgBs4B,EACnBC,EAAWpjC,IAAI6K,KAEnBu4B,EAAWvmC,IAAIgO,GACVrP,EAAY1E,GAAmBkJ,IAAI6K,IACpCrP,EAAY1E,GAAmB8F,IAAIiO,EAAc,IAErDrP,EAAY1E,GAAmB6F,IAAIkO,GAAc/K,KAAK,CAClDrD,aACAyD,OAAQmD,EACRukB,cAGZ,EACJ,CACJ"}
1
+ {"version":3,"file":"snice-runtime.min.js","sources":["../../index.esm.js","../../transitions.esm.js","../../symbols.esm.js"],"sourcesContent":["/*!\n * snice v7.0.1\n * A decorator-driven web component library with differential rendering, routing, controllers, and 130+ ready-made UI components. Use as much or as little as you want. Zero dependencies, works anywhere.\n * (c) 2024\n * Released under the MIT License.\n *\n * GENERATED FILE — DO NOT EDIT. Source: src/. Rebuild: npm run build:core\n */\n// Global namespace for Snice framework\n// Ensures all registries and symbols are shared across different JS files/modules\n// Initialize the global Snice namespace on globalThis\n// This ensures all module instances share the same registry\nif (!globalThis.snice) {\n globalThis.snice = {\n controllerRegistry: new Map(),\n pendingControllerAttachments: new Map(),\n controllerIdCounter: 0\n };\n}\n// Multiple copies of Snice can share a global created by an older build.\nglobalThis.snice.pendingControllerAttachments ??= new Map();\n// Export direct reference to globalThis.snice\nconst snice = globalThis.snice;\n// Helper function to get or create a global symbol\n// Symbol.for() already guarantees global uniqueness, no need for a Map cache\nfunction getSymbol(name) {\n return Symbol.for(`snice:${name}`);\n}\n\n// Central file for all symbols used in the framework\n// All symbols are stored globally to ensure consistency across modules\nconst IS_CONTROLLER_CLASS = getSymbol('is-controller-class');\nconst IS_CONTROLLER_INSTANCE = getSymbol('is-controller-instance');\nconst IS_ELEMENT_CLASS = getSymbol('is-element-class');\nconst CHANNEL_HANDLERS = getSymbol('channel-handlers');\n// Internal element state symbols\nconst READY_PROMISE = getSymbol('ready-promise');\nconst READY_RESOLVE = getSymbol('ready-resolve');\nconst RENDERED_PROMISE = getSymbol('rendered-promise');\nconst RENDERED_RESOLVE = getSymbol('rendered-resolve');\n// Set when a render is requested but dropped because the element was\n// disconnected; consumed on reconnect to replay exactly the missed render.\nconst PENDING_RECONNECT_RENDER = getSymbol('pending-reconnect-render');\n// Per-element synchronous render-nesting depth, used to cap runaway re-entry\n// without a shared global counter that one element could exhaust for others.\nconst RENDER_DEPTH = getSymbol('render-depth');\nconst RENDER_ROOT = getSymbol('render-root');\nconst ELEMENT_OPTIONS = getSymbol('element-options');\nconst CONTROLLER = getSymbol('controller');\nconst INITIALIZED = getSymbol('initialized');\n// Controller symbols\nconst CONTROLLER_KEY = getSymbol('controller-key');\nconst CONTROLLER_NAME_KEY = getSymbol('controller-name');\nconst CONTROLLER_ID = getSymbol('controller-id');\nconst CONTROLLER_OPERATIONS = getSymbol('controller-operations');\nconst NATIVE_CONTROLLER = getSymbol('native-controller');\n// Set while a controller CLASS (not a registry name) is attached — the\n// attribute/MutationObserver channel must not attach over or detach it.\nconst DIRECT_CONTROLLER = getSymbol('direct-controller');\n// A controller class bound by a template before the custom element was\n// defined/upgraded. Picked up by connectedCallback on first initialization.\nconst PENDING_CONTROLLER_BINDING = getSymbol('pending-controller-binding');\n// Cleanup symbol - holds an object with all cleanup arrays\nconst CLEANUP = getSymbol('cleanup');\n// Property symbols\nconst PROPERTIES = getSymbol('properties');\nconst PROPERTY_VALUES = getSymbol('property-values');\nconst PROPERTY_DEFAULTS = getSymbol('property-defaults');\nconst PROPERTY_WRAPPERS = getSymbol('property-wrappers');\nconst PRE_INIT_PROPERTY_VALUES = getSymbol('pre-init-property-values');\nconst PRE_UPGRADE_PROPERTY_BINDINGS = getSymbol('pre-upgrade-property-bindings');\nconst PROPERTIES_INITIALIZED = getSymbol('properties-initialized');\nconst PROPERTY_WATCHERS = getSymbol('property-watchers');\nconst EXPLICITLY_SET_PROPERTIES = getSymbol('explicitly-set-properties');\n// Router context symbol\nconst ROUTER_CONTEXT = getSymbol('router-context');\nconst PAGE_TRANSITION = getSymbol('page-transition');\nconst CREATED_AT = getSymbol('created-at');\n// Lifecycle symbols\nconst READY_HANDLERS = getSymbol('ready-handlers');\nconst DISPOSE_HANDLERS = getSymbol('dispose-handlers');\nconst RECONNECT_HANDLERS = getSymbol('reconnect-handlers');\nconst MOVED_HANDLERS = getSymbol('moved-handlers');\nconst ADOPTED_HANDLERS = getSymbol('adopted-handlers');\n// Observer symbols\nconst OBSERVERS = getSymbol('observers');\n// Property setter flag (prevents attributeChangedCallback re-triggering watchers)\nconst SETTING_FROM_PROPERTY = getSymbol('setting-from-property');\n// Lifecycle callback timers\nconst MOVED_TIMERS = getSymbol('moved-timers');\nconst ADOPTED_TIMERS = getSymbol('adopted-timers');\n// Dispatch timing symbols\nconst DISPATCH_TIMERS = getSymbol('dispatch-timers');\n// Render symbols (v3.0.0)\nconst RENDER_METHOD = getSymbol('render-method');\nconst RENDER_OPTIONS = getSymbol('render-options');\nconst RENDER_INSTANCE = getSymbol('render-instance');\nconst RENDER_TIMERS = getSymbol('render-timers');\nconst RENDER_CALLBACKS = getSymbol('render-callbacks');\nconst STYLES_METHOD = getSymbol('styles-method');\nconst STYLES_APPLIED = getSymbol('styles-applied');\nconst PARENT_STYLES_METHODS = getSymbol('parent-styles-methods');\nconst SNICE_ELEMENT_BASE = getSymbol('snice-element-base');\n// Navigation context symbols\nconst CONTEXT_HANDLER = getSymbol('context-handler');\nconst NAVIGATION_CONTEXT_INSTANCE = getSymbol('navigation-context-instance');\nconst REGISTERED_ELEMENTS = getSymbol('registered-elements');\nconst IS_UPDATING = getSymbol('is-updating');\nconst CONTEXT_REGISTER = getSymbol('context-register');\nconst CONTEXT_UNREGISTER = getSymbol('context-unregister');\nconst CONTEXT_NOTIFY_ELEMENT = getSymbol('context-notify-element');\nconst CONTEXT_TIMER = getSymbol('context-timer');\nconst CONTEXT_CALLED = getSymbol('context-called');\nconst CONTEXT_UPDATE = getSymbol('context-update');\n// Registration de-dup sets on the constructor — replace previous `__*Methods`\n// expando strings that violated the no-double-underscore rule.\nconst CONTEXT_METHODS = getSymbol('context-methods');\nconst WATCH_METHODS = getSymbol('watch-methods');\nconst OBSERVE_METHODS = getSymbol('observe-methods');\nconst ON_METHODS = getSymbol('on-methods');\nconst RESPOND_METHODS = getSymbol('respond-methods');\nconst READY_METHODS = getSymbol('ready-methods');\nconst DISPOSE_METHODS = getSymbol('dispose-methods');\nconst RECONNECT_METHODS = getSymbol('reconnect-methods');\nconst MOVED_METHODS = getSymbol('moved-methods');\nconst ADOPTED_METHODS = getSymbol('adopted-methods');\n// Controller attach-abort — set to an AbortController while attachController\n// is awaiting element.ready, so detachController can short-circuit the wait.\nconst CONTROLLER_ABORT = getSymbol('controller-abort');\n// Set on a controller instance once it has gotten past element.ready and is\n// being attached, so detachController knows not to run detach() on a controller\n// whose attach() was aborted before it ever ran.\nconst CONTROLLER_ATTACHED = getSymbol('controller-attached');\nconst PROPERTY_DEFINERS = getSymbol('property-definers');\n\n/**\n * SimpleArray type for arrays that can be safely reflected to attributes\n * Supports arrays of: string, number, boolean\n * Uses full-width comma (,) as separator to avoid conflicts\n * Strings cannot contain the full-width comma character\n */\nclass SimpleArray {\n static { this.SEPARATOR = ','; } // U+FF0C Full-width comma\n /**\n * Serialize array to string for attribute storage\n */\n static serialize(arr) {\n if (!Array.isArray(arr))\n return '';\n return arr.map(item => {\n if (typeof item === 'string') {\n // Validate string doesn't contain our separator\n if (item.includes(SimpleArray.SEPARATOR)) {\n throw new Error(`SimpleArray strings cannot contain the character \"${SimpleArray.SEPARATOR}\" (U+FF0C)`);\n }\n return item;\n }\n else if (typeof item === 'number' || typeof item === 'boolean') {\n return String(item);\n }\n else {\n throw new Error(`SimpleArray only supports string, number, and boolean types. Got: ${typeof item}`);\n }\n }).join(SimpleArray.SEPARATOR);\n }\n /**\n * Parse string from attribute back to array\n */\n static parse(str) {\n if (str === null || str === undefined)\n return [];\n // Empty string should not be parsed as containing an empty string\n // since empty arrays don't get reflected (handled by the reflection logic)\n if (str === '')\n return [];\n return str.split(SimpleArray.SEPARATOR).map(item => {\n // Try to parse as number\n if (/^-?\\d+\\.?\\d*$/.test(item)) {\n const num = Number(item);\n if (!isNaN(num))\n return num;\n }\n // Parse as boolean\n if (item === 'true')\n return true;\n if (item === 'false')\n return false;\n // Default to string\n return item;\n });\n }\n}\n\n/**\n * Generic transition system for animating between elements\n */\nvar TransitionMode;\n(function (TransitionMode) {\n /** out transition completes before in transition starts */\n TransitionMode[\"SEQUENTIAL\"] = \"sequential\";\n /** both transitions happen at the same time */\n TransitionMode[\"SIMULTANEOUS\"] = \"simultaneous\";\n})(TransitionMode || (TransitionMode = {}));\n\nvar _a, _b, _c;\n// Symbol for storing the Set of elements\n// Use Symbol.for() to ensure symbols are shared across multiple Snice instances\nconst REGISTERED_ELEMENTS_SET = Symbol.for('snice:registered-elements-set');\n// Counter for generating unique context IDs\nlet contextIdCounter = 0;\n/**\n * Represents the bundled router state that can notify registered elements of changes\n */\nclass Context {\n constructor(context = {}, placards = [], currentRoute = '', routeParams = {}, fetcher) {\n // Stores the SET of wrapped-method names per element so that classes with\n // multiple @context() handlers register every method, not just the last one.\n this[_a] = new WeakMap();\n this[_b] = new Set();\n this[_c] = false;\n this.id = contextIdCounter++;\n this.application = context;\n this.navigation = {\n placards,\n route: currentRoute,\n params: routeParams\n };\n // Initialize fetch with middleware support or fallback to native fetch\n if (fetcher && typeof fetcher.create === 'function') {\n this.fetch = fetcher.create(this);\n }\n else if (typeof fetch === 'function') {\n this.fetch = fetch.bind(this);\n }\n else {\n throw new Error('No fetch implementation available');\n }\n }\n /**\n * Register an element to receive context updates\n * @internal Used by @context decorator\n */\n [(_a = REGISTERED_ELEMENTS, _b = REGISTERED_ELEMENTS_SET, _c = IS_UPDATING, CONTEXT_REGISTER)](element, methodName) {\n const map = this[REGISTERED_ELEMENTS];\n let names = map.get(element);\n if (!names) {\n names = new Set();\n map.set(element, names);\n }\n names.add(methodName);\n this[REGISTERED_ELEMENTS_SET].add(element);\n }\n /**\n * Unregister an element from receiving context updates. With a methodName,\n * removes only that one handler (so a `once` handler tearing itself down\n * doesn't kill the element's other @context handlers); without one, removes\n * the element entirely (used on disconnect).\n * @internal Used by @context decorator cleanup\n */\n [CONTEXT_UNREGISTER](element, methodName) {\n const map = this[REGISTERED_ELEMENTS];\n if (methodName !== undefined) {\n const names = map.get(element);\n if (!names)\n return;\n names.delete(methodName);\n if (names.size > 0)\n return; // other handlers remain — keep the element\n }\n map.delete(element);\n this[REGISTERED_ELEMENTS_SET].delete(element);\n }\n /**\n * Update the context and notify all registered elements\n * Prevents infinite loops by tracking update state\n * @internal Used by Router during navigation\n */\n [CONTEXT_UPDATE](context, placards, currentRoute, routeParams) {\n this.application = context;\n this.navigation.placards = placards;\n this.navigation.route = currentRoute;\n this.navigation.params = routeParams;\n this.notify();\n }\n /**\n * Signal all @context() subscribers to re-read context\n * Does not modify any state — just notifies listeners with current values\n */\n update() {\n this.notify();\n }\n notify() {\n // Prevent infinite loops\n if (this[IS_UPDATING]) {\n return;\n }\n this[IS_UPDATING] = true;\n // Notify all registered elements by calling EVERY registered method\n // name on each. Classes with multiple @context() methods get all fired.\n const elementsSet = this[REGISTERED_ELEMENTS_SET];\n const elementsMap = this[REGISTERED_ELEMENTS];\n for (const element of elementsSet) {\n const names = elementsMap.get(element);\n if (!names)\n continue;\n for (const methodName of names) {\n if (typeof element[methodName] === 'function') {\n try {\n element[methodName](this);\n }\n catch (error) {\n console.error(`Error calling @context method ${methodName}:`, error);\n }\n }\n }\n }\n this[IS_UPDATING] = false;\n }\n /**\n * Notify a specific element of the current context state\n * @internal Used by @context decorator\n */\n [CONTEXT_NOTIFY_ELEMENT](element) {\n const names = this[REGISTERED_ELEMENTS].get(element);\n if (!names)\n return;\n for (const methodName of names) {\n if (typeof element[methodName] === 'function') {\n element[methodName](this);\n }\n }\n }\n}\n\n/**\n * Detects the type constructor from an initial value\n * @param initialValue - The default value assigned to a property field (e.g., `name = \"default\"` -> \"default\")\n * @returns The constructor function (String, Number, Boolean, etc.) or undefined if type can't be determined\n */\nfunction detectType(initialValue) {\n if (initialValue === null || initialValue === undefined) {\n return undefined;\n }\n if (typeof initialValue === 'string') {\n return String;\n }\n if (typeof initialValue === 'number') {\n return Number;\n }\n if (typeof initialValue === 'boolean') {\n return Boolean;\n }\n if (initialValue instanceof Date) {\n return Date;\n }\n if (typeof initialValue === 'bigint') {\n return BigInt;\n }\n if (Array.isArray(initialValue)) {\n return Array;\n }\n return undefined;\n}\n/**\n * Parses an attribute value based on the property type\n * @param attributeValue - The raw string value from the HTML attribute (e.g., \"123\", \"true\", \"hello\")\n * @param propertyOptions - The options from @property decorator (contains explicit type, attribute name, etc.)\n * @param currentValue - The current stored value of the property (used for type inference when no explicit type)\n * @param initialValue - The default value assigned to the property field (used for type detection as fallback)\n * @returns The parsed value in the correct JavaScript type\n */\nfunction parseAttributeValue(attributeValue, propertyOptions, currentValue, initialValue) {\n // Use explicit type or detect from initial value\n const typeToUse = propertyOptions.type || detectType(initialValue);\n if (propertyOptions.converter?.fromAttribute) {\n return propertyOptions.converter.fromAttribute(attributeValue, typeToUse);\n }\n switch (typeToUse) {\n case Boolean:\n // Boolean semantics per user specification:\n // - No attribute = false\n // - String \"false\" = false\n // - String \"true\" = true\n // - Empty string = true (attribute exists like <element bool-attr>)\n // - Any other value = true\n if (attributeValue === null)\n return false; // No attribute\n if (attributeValue === 'false')\n return false; // String \"false\"\n // All other cases (including empty string) = true (attribute exists)\n return true;\n case Number:\n return attributeValue !== null ? Number(attributeValue) : null;\n case String:\n return attributeValue;\n case Date:\n return attributeValue ? new Date(attributeValue) : null;\n case BigInt:\n if (attributeValue && attributeValue.endsWith('n')) {\n return BigInt(attributeValue.slice(0, -1));\n }\n else {\n return attributeValue ? BigInt(attributeValue) : null;\n }\n case SimpleArray:\n return SimpleArray.parse(attributeValue);\n case Array:\n try {\n return attributeValue ? JSON.parse(attributeValue) : [];\n }\n catch {\n return [];\n }\n case Object:\n try {\n return attributeValue ? JSON.parse(attributeValue) : {};\n }\n catch {\n return {};\n }\n default:\n // If no type specified and can't detect, try to infer from current value type\n if (typeof currentValue === 'number' && attributeValue !== null) {\n return Number(attributeValue);\n }\n else {\n return attributeValue;\n }\n }\n}\n/**\n * Converts a property value to its attribute string representation\n * @param value - The property value to convert\n * @param propertyOptions - The options from @property decorator\n * @param initialValue - The default value assigned to the property field (used for type detection)\n * @returns The string representation for the HTML attribute, or null if value should remove attribute\n */\n/**\n * Default property dirty-check: has the value changed? Like `!==`, but treats\n * NaN → NaN as unchanged (NaN !== NaN would otherwise re-fire forever).\n */\nfunction notEqual(value, old) {\n // Changed unless strictly equal, or both are NaN (each self-unequal).\n return value !== old && (value === value || old === old);\n}\n/**\n * Extract attribute name from property options\n */\nfunction getAttrName(opts, propName) {\n // Lowercase always: the DOM stores attribute names lowercase, so an explicit\n // camelCase `attribute:` would otherwise never match observedAttributes and\n // attributeChangedCallback would never fire. get/setAttribute are already\n // case-insensitive, so this is safe for every caller.\n if (typeof opts.attribute === 'string')\n return opts.attribute.toLowerCase();\n if (opts.attribute === true || opts.attributeNaming === 'kebab') {\n return propName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n }\n return propName.toLowerCase();\n}\n/**\n * Escape HTML text-node content. Use for text that will be interpolated\n * into an HTML string (not an attribute value).\n */\nfunction escapeHtml(value) {\n return String(value ?? '')\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\n}\n/**\n * Escape HTML attribute value. Use for anything interpolated inside a\n * quoted attribute (e.g. `href=\"${...}\"`). Escapes both quote styles so\n * the value cannot close the attribute or the surrounding tag.\n */\nfunction escapeAttr(value) {\n return String(value ?? '')\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n/**\n * Validate a URL's scheme against a safe-list. Relative references are\n * accepted after parsing, while absolute and network-path references must\n * resolve to an allowed protocol. Raw ASCII control characters are rejected\n * before parsing so they cannot be stripped out to disguise a scheme.\n *\n * Rejects `javascript:`, `data:`, `vbscript:`, and any scheme not in the\n * allowed set by default. Pass to `window.open`, `iframe.src`, `<a href>`,\n * etc. when the URL originates from user input.\n *\n * @example\n * if (!isSafeUrl(url)) return;\n * window.open(url, '_blank');\n */\nfunction isSafeUrl(url, opts = {}) {\n let raw;\n try {\n raw = String(url ?? '');\n }\n catch {\n return false;\n }\n if (!raw || /[\\u0000-\\u001f\\u007f]/.test(raw))\n return false;\n const s = raw.trim();\n if (!s)\n return false;\n const allowed = opts.allowed ?? ['http:', 'https:', 'mailto:', 'tel:'];\n try {\n const parsed = new URL(s, 'http://__snice-relative.invalid/');\n const hasExplicitScheme = /^[a-z][a-z\\d+.-]*:/i.test(s);\n const isNetworkPathReference = /^[\\\\/]{2}/.test(s);\n // Paths, hashes, and query-only references inherit the embedding page's\n // protocol and are safe independently of the absolute-protocol allowlist.\n if (!hasExplicitScheme && !isNetworkPathReference)\n return true;\n return allowed.some(protocol => typeof protocol === 'string'\n && protocol.toLowerCase() === parsed.protocol);\n }\n catch {\n return false;\n }\n}\n/**\n * Parse a duration string into a unit-aware Duration.\n * Recognized suffixes: `ms` (milliseconds), `s` (seconds), `m` (minutes),\n * `h` (hours). Plain numbers with no suffix are treated as milliseconds.\n * Unparseable input yields a zero-duration.\n *\n * @example\n * parseDuration('200ms').milliseconds() // 200\n * parseDuration('0.4s').milliseconds() // 400\n * parseDuration('0.4s').seconds() // 0.4\n */\nfunction parseDuration(value) {\n const v = String(value).trim();\n const num = parseFloat(v);\n let ms;\n if (isNaN(num)) {\n ms = 0;\n }\n else if (/ms$/i.test(v)) {\n ms = num;\n }\n else if (/s$/i.test(v)) {\n ms = num * 1000;\n }\n else if (/m$/i.test(v)) {\n ms = num * 60000;\n }\n else if (/h$/i.test(v)) {\n ms = num * 3600000;\n }\n else {\n ms = num;\n }\n return {\n milliseconds: () => ms,\n seconds: () => ms / 1000,\n minutes: () => ms / 60000,\n };\n}\n/**\n * Lazy-init a Set on a symbol key\n */\nfunction ensureSet(obj, sym) {\n if (!obj[sym])\n obj[sym] = new Set();\n return obj[sym];\n}\n/**\n * Lazy-init an object on a symbol key\n */\nfunction ensureObj(obj, sym) {\n if (!obj[sym])\n obj[sym] = {};\n return obj[sym];\n}\n/**\n * Invoke property watchers for a given property change\n */\nfunction invokeWatchers(instance, constructor, propName, oldValue, newValue) {\n const watchers = constructor[PROPERTY_WATCHERS];\n if (!watchers)\n return;\n // Look up watchers by the JS property name AND the explicit `attribute:`\n // name (if declared). Lets `@watch('show-dropdown')` match a property\n // declared as `@property({ attribute: 'show-dropdown' }) showDropdown`.\n const keys = [propName];\n const propOpts = constructor[PROPERTIES]?.get(propName);\n const attrName = propOpts && typeof propOpts.attribute === 'string' ? propOpts.attribute : null;\n if (attrName && attrName !== propName)\n keys.push(attrName);\n for (const key of keys) {\n if (watchers.has(key)) {\n for (const w of watchers.get(key)) {\n try {\n w.method.call(instance, oldValue, newValue, propName);\n }\n catch (e) {\n console.error(`Error in @watch('${key}') method ${w.methodName}:`, e);\n }\n }\n }\n }\n if (watchers.has('*')) {\n for (const w of watchers.get('*')) {\n try {\n w.method.call(instance, oldValue, newValue, propName);\n }\n catch (e) {\n console.error(`Error in @watch('*') method ${w.methodName}:`, e);\n }\n }\n }\n}\n/**\n * Fire the one-time initialization call for `@watch(..., { immediate: true })`\n * handlers. Runs once per declared property after the element is initialized,\n * passing the effective initial value with `oldValue` undefined. Non-immediate\n * watchers are untouched — they only react to later changes.\n */\nfunction invokeImmediateWatchers(instance, constructor) {\n const watchers = constructor[PROPERTY_WATCHERS];\n const properties = constructor[PROPERTIES];\n if (!watchers || !properties)\n return;\n for (const [propName, propOptions] of properties) {\n // A watcher may be registered under the JS name, the explicit `attribute:`\n // name, or the `*` wildcard; fire each immediate one exactly once, keyed to\n // this property's current value.\n const keys = [propName];\n const attrName = propOptions && typeof propOptions.attribute === 'string' ? propOptions.attribute : null;\n if (attrName && attrName !== propName)\n keys.push(attrName);\n keys.push('*');\n for (const key of keys) {\n if (!watchers.has(key))\n continue;\n for (const w of watchers.get(key)) {\n if (!w.immediate)\n continue;\n try {\n w.method.call(instance, undefined, instance[propName], propName);\n }\n catch (e) {\n console.error(`Error in @watch('${key}') method ${w.methodName}:`, e);\n }\n }\n }\n }\n}\n/**\n * Create a debounced version of a function\n */\nfunction createDebounced(fn, delay) {\n let timer = null;\n return function (...args) {\n if (timer !== null)\n clearTimeout(timer);\n timer = setTimeout(() => { fn.apply(this, args); timer = null; }, delay);\n };\n}\n/**\n * Create a throttled version of a function (leading + trailing edge)\n */\nfunction createThrottled(fn, delay) {\n let lastCall = 0;\n let timer = null;\n return function (...args) {\n const now = Date.now();\n const remaining = delay - (now - lastCall);\n if (remaining <= 0) {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n lastCall = now;\n return fn.apply(this, args);\n }\n if (!timer) {\n timer = setTimeout(() => { lastCall = Date.now(); timer = null; fn.apply(this, args); }, remaining);\n }\n };\n}\n/**\n * Resolve a scope option to a concrete EventTarget.\n *\n * - undefined → host element (default behavior)\n * - 'global' → `document`\n * - string → `host.closest(selector)` (nearest matching ancestor)\n * - EventTarget instance → that target directly\n * - resolver function → called with host as `this`, returns target or null\n *\n * Returns null when the scope cannot be resolved (e.g. selector matches no\n * ancestor, resolver returns null). Caller decides how to handle null —\n * typically warn in dev and skip listener attachment.\n */\nfunction resolveScope(host, scope) {\n if (scope === undefined || scope === null)\n return host;\n if (scope === 'global')\n return typeof document !== 'undefined' ? document : null;\n if (typeof scope === 'function') {\n try {\n return scope.call(host) || null;\n }\n catch {\n return null;\n }\n }\n if (typeof scope === 'string') {\n return host.closest?.(scope) || null;\n }\n // Direct EventTarget instance.\n if (scope && typeof scope.addEventListener === 'function') {\n return scope;\n }\n return null;\n}\nfunction valueToAttribute(value, propertyOptions, initialValue) {\n // Handle null/undefined/false values and empty arrays\n if (value === null || value === undefined || value === false ||\n (propertyOptions?.type === SimpleArray && Array.isArray(value) && value.length === 0)) {\n return null;\n }\n // Use custom converter if provided\n if (propertyOptions.converter?.toAttribute) {\n return propertyOptions.converter.toAttribute(value, propertyOptions.type);\n }\n // Use explicit type or detect from initial value\n const typeToUse = propertyOptions.type || detectType(initialValue);\n switch (typeToUse) {\n case Boolean:\n // For boolean attributes, return \"true\" when true\n // (false is already handled above - returns null to remove attribute)\n return 'true';\n case Date:\n return value instanceof Date ? value.toISOString() : String(value);\n case BigInt:\n return typeof value === 'bigint' ? value.toString() + 'n' : String(value);\n case SimpleArray:\n return Array.isArray(value) ? SimpleArray.serialize(value) : String(value);\n case Array:\n return Array.isArray(value) ? JSON.stringify(value) : String(value);\n case Object:\n return typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value);\n default:\n return String(value);\n }\n}\n/**\n * Warn (once per class) about @watch targets that match no @property —\n * such watchers can never fire, and the typo is otherwise silent.\n * Valid targets: property names, their attribute forms, and the '*' wildcard.\n */\nconst validatedWatchClasses = new WeakSet();\nfunction validateWatchedProperties(instance, constructor) {\n if (validatedWatchClasses.has(constructor))\n return;\n validatedWatchClasses.add(constructor);\n const watchers = constructor[PROPERTY_WATCHERS];\n if (!watchers || watchers.size === 0)\n return;\n const properties = constructor[PROPERTIES];\n // invokeWatchers matches exactly: the property name, or an EXPLICIT\n // `attribute:` string. A derived/lowercased attribute name is NOT watchable,\n // so it must not be treated as valid here.\n const valid = new Set(['*']);\n if (properties) {\n for (const [name, opts] of properties) {\n valid.add(name);\n if (typeof opts?.attribute === 'string')\n valid.add(opts.attribute);\n }\n }\n for (const key of watchers.keys()) {\n if (valid.has(key))\n continue;\n const tag = instance.tagName ? instance.tagName.toLowerCase() : 'element';\n const known = properties ? [...properties.keys()].join(', ') : '(none)';\n console.warn(`@watch('${key}') on <${tag}> matches no @property — it will never fire. ` +\n `Known properties: ${known}.`);\n }\n}\n\n// Global cache for MediaQueryList objects\nconst mediaQueryCache = new Map();\n/**\n * Decorator for observing external changes like viewport intersection, resize, media queries, and DOM mutations\n *\n * @param target - The observation target (e.g., 'intersection', 'resize', 'media:(min-width: 768px)', 'mutation:childList') or array of targets\n * @param selectorOrOptions - CSS selector for element to observe OR options object\n * @param options - Options object (when second parameter is a selector)\n */\nfunction observe(observeTarget, selectorOrOptions, options) {\n // Handle overloaded parameters\n let selector;\n let opts;\n if (typeof selectorOrOptions === 'string') {\n selector = selectorOrOptions;\n opts = options;\n }\n else {\n selector = undefined;\n opts = selectorOrOptions;\n }\n return function (target, context) {\n const propertyKey = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // hasOwnProperty guards so subclasses don't mutate parent state via\n // the prototype chain. Without this, instantiating a child pushes into\n // the parent's OBSERVERS array and fires child observers on fresh\n // parent instances.\n if (!Object.prototype.hasOwnProperty.call(constructor, OBSERVE_METHODS)) {\n constructor[OBSERVE_METHODS] = new Set();\n }\n if (constructor[OBSERVE_METHODS].has(target))\n return;\n constructor[OBSERVE_METHODS].add(target);\n if (!Object.prototype.hasOwnProperty.call(constructor, OBSERVERS)) {\n const inherited = constructor[OBSERVERS];\n constructor[OBSERVERS] = inherited ? [...inherited] : [];\n }\n const observeTargets = Array.isArray(observeTarget) ? observeTarget : [observeTarget];\n for (const targetString of observeTargets) {\n const [type, ...modifiers] = targetString.split(':');\n const targetStr = modifiers.join(':');\n constructor[OBSERVERS].push({\n type,\n target: targetStr,\n selector,\n methodName: propertyKey,\n method: target,\n options: opts\n });\n }\n });\n };\n}\n// Helper to setup observers for elements\nfunction setupObservers(instance, element) {\n const observers = instance.constructor[OBSERVERS];\n if (!observers || !Array.isArray(observers) || observers.length === 0) {\n return;\n }\n // Initialize cleanup object if needed\n if (!instance[CLEANUP]) {\n instance[CLEANUP] = { events: [], channels: [], observers: [] };\n }\n else if (!instance[CLEANUP].observers) {\n instance[CLEANUP].observers = [];\n }\n for (const observer of observers) {\n const method = observer.method.bind(instance);\n // Apply throttling if specified\n const callback = observer.options?.throttle\n ? createThrottled(method, observer.options.throttle)\n : method;\n switch (observer.type) {\n case 'intersection':\n setupIntersectionObserver(instance, element, observer, callback);\n break;\n case 'resize':\n setupResizeObserver(instance, element, observer, callback);\n break;\n case 'media':\n setupMediaQueryObserver(instance, element, observer, callback);\n break;\n case 'mutation':\n setupMutationObserver(instance, element, observer, callback);\n break;\n default:\n console.warn(`Unknown observer type: ${observer.type}`);\n }\n }\n}\nfunction setupIntersectionObserver(instance, element, observer, callback) {\n const options = {\n threshold: observer.options?.threshold ?? 0,\n rootMargin: observer.options?.rootMargin ?? '0px',\n root: observer.options?.root ?? null\n };\n // Wrap callback to handle return value\n const wrappedCallback = (entries) => {\n for (const entry of entries) {\n try {\n const result = callback(entry);\n if (result === false && io) {\n io.unobserve(entry.target);\n }\n }\n catch (error) {\n console.error(`Error in intersection observer ${observer.methodName}:`, error);\n }\n }\n };\n if (typeof IntersectionObserver === 'undefined') {\n console.warn('IntersectionObserver is not available in this environment');\n return;\n }\n const io = new IntersectionObserver(wrappedCallback, options);\n // Find target elements\n const targets = observer.selector\n ? Array.from(element.shadowRoot?.querySelectorAll(observer.selector) || [])\n : [element];\n // Start observing\n targets.forEach(target => io.observe(target));\n // Store cleanup\n instance[CLEANUP].observers.push(() => {\n targets.forEach(target => io.unobserve(target));\n // Only disconnect if no more targets\n if (io.takeRecords().length === 0) {\n io.disconnect();\n }\n });\n}\nfunction setupResizeObserver(instance, element, observer, callback) {\n const box = observer.options?.box || 'content-box';\n // Wrap callback with error handling\n const wrappedCallback = (entries) => {\n for (const entry of entries) {\n try {\n callback(entry);\n }\n catch (error) {\n console.error(`Error in resize observer ${observer.methodName}:`, error);\n }\n }\n };\n // Check if ResizeObserver is available\n if (typeof ResizeObserver === 'undefined') {\n console.warn('ResizeObserver is not available in this environment');\n return;\n }\n // Create ResizeObserver\n const ro = new ResizeObserver(wrappedCallback);\n // Find target elements\n const targets = observer.selector\n ? Array.from(element.shadowRoot?.querySelectorAll(observer.selector) || [])\n : [element];\n // Start observing with options\n targets.forEach(target => {\n ro.observe(target, { box });\n });\n // Store cleanup\n instance[CLEANUP].observers.push(() => {\n ro.disconnect();\n });\n}\nfunction setupMediaQueryObserver(instance, _element, observer, callback) {\n // Extract media query from target (e.g., \"media:(min-width: 768px)\" -> \"(min-width: 768px)\")\n const mediaQuery = observer.target;\n if (!mediaQuery) {\n console.warn('Media query observer requires a query string');\n return;\n }\n // Get or create MediaQueryList (cached globally)\n let mql = mediaQueryCache.get(mediaQuery);\n if (!mql) {\n try {\n mql = window.matchMedia(mediaQuery);\n mediaQueryCache.set(mediaQuery, mql);\n }\n catch (error) {\n console.error(`Invalid media query: ${mediaQuery}`, error);\n return;\n }\n }\n // Wrap callback with error handling\n const wrappedCallback = (event) => {\n try {\n callback('matches' in event ? event.matches : event.matches);\n }\n catch (error) {\n console.error(`Error in media query observer ${observer.methodName}:`, error);\n }\n };\n // Call immediately with current state\n wrappedCallback(mql);\n // Listen for changes\n const changeHandler = (e) => wrappedCallback(e);\n // Modern browsers use addEventListener\n if (mql.addEventListener) {\n mql.addEventListener('change', changeHandler);\n instance[CLEANUP].observers.push(() => {\n mql.removeEventListener('change', changeHandler);\n });\n }\n else {\n // Fallback for older browsers\n mql.addListener(changeHandler);\n instance[CLEANUP].observers.push(() => {\n mql.removeListener(changeHandler);\n });\n }\n}\nfunction setupMutationObserver(instance, element, observer, callback) {\n // Parse mutation type and attribute from target\n // e.g., \"childList\", \"attributes:class\", \"attributes:data-state\"\n const parts = observer.target.split(':');\n const mutationType = parts[0] || 'childList';\n const attributeName = parts[1];\n // Build MutationObserver options\n const options = {};\n switch (mutationType) {\n case 'childList':\n options.childList = true;\n break;\n case 'attributes':\n options.attributes = true;\n if (attributeName) {\n options.attributeFilter = [attributeName];\n }\n break;\n default: {\n // A leading . # or [ means the author put a CSS selector where the\n // mutation type goes — point at the correct two-argument form.\n if (/^[.#[]/.test(mutationType)) {\n console.warn(`@observe: \"mutation:${mutationType}\" — \"${mutationType}\" looks like a selector. ` +\n `Selectors are the second argument — did you mean ` +\n `@observe('mutation:childList', '${mutationType}')?`);\n }\n else {\n console.warn(`Unknown mutation type: ${mutationType} (expected childList or attributes)`);\n }\n return;\n }\n }\n // Apply subtree with safety limits\n if (observer.options?.subtree) {\n options.subtree = true;\n // Could implement maxDepth checking in the callback\n if (observer.options.maxDepth) {\n console.warn('maxDepth is set but requires custom implementation');\n }\n }\n // Wrap callback with error handling and optional depth filtering\n const needsDepthFilter = !!(observer.options?.maxDepth && observer.options.subtree);\n const wrappedCallback = (mutations) => {\n try {\n if (!needsDepthFilter) {\n callback(mutations);\n return;\n }\n const maxDepth = observer.options.maxDepth;\n const root = element.shadowRoot || element;\n const filtered = mutations.filter(mutation => {\n let depth = 0;\n let current = mutation.target;\n while (current && current !== root && depth < maxDepth) {\n current = current.parentNode;\n depth++;\n }\n return depth < maxDepth;\n });\n if (filtered.length > 0)\n callback(filtered);\n }\n catch (error) {\n console.error(`Error in mutation observer ${observer.methodName}:`, error);\n }\n };\n // Create MutationObserver\n const mo = new MutationObserver(wrappedCallback);\n // Find target elements\n const isController = instance[IS_CONTROLLER_INSTANCE] === true;\n // For mutation observers without selector:\n // - Controllers: observe the shadow DOM of the element they're attached to (if it exists)\n // - Elements: observe the element itself (light DOM) to avoid infinite loops\n const targets = observer.selector\n ? Array.from(element.shadowRoot?.querySelectorAll(observer.selector) || [])\n : isController && element.shadowRoot\n ? [element.shadowRoot]\n : [element];\n // Start observing\n targets.forEach(target => {\n mo.observe(target, options);\n });\n // Store cleanup\n instance[CLEANUP].observers.push(() => {\n mo.disconnect();\n });\n}\n// Helper to cleanup observers\nfunction cleanupObservers(instance) {\n if (instance[CLEANUP]?.observers) {\n for (const cleanup of instance[CLEANUP].observers) {\n cleanup();\n }\n instance[CLEANUP].observers = [];\n }\n}\n\n// @request decorator transforms methods to return Promise<T>\n/**\n * Decorator for making requests from elements or controllers.\n * Uses async generator pattern for bidirectional communication.\n *\n * @param requestName The name of the request\n * @param options Optional configuration\n */\nfunction request(requestName, options) {\n return function (originalMethod, _context) {\n // Create timing variables for debounce/throttle\n let debounceTimeout;\n let throttleLastCall = 0;\n let throttleTimeout;\n const throttleTrailingResolvers = [];\n return async function (...args) {\n const actualRequest = async () => {\n // @request always acts as requester (client side)\n const responseTimeout = options?.timeout ?? 120000; // Default 2 minute timeout\n const discoveryTimeout = options?.discoveryTimeout ?? 50; // Default 50ms discovery timeout\n // Create the generator\n const generator = originalMethod.apply(this, args);\n // Get the first yield (the request payload)\n const { value: payload, done } = await generator.next();\n if (done) {\n // Generator returned without yielding\n return payload;\n }\n // Create data promise and expose resolve/reject\n let dataResolve;\n let dataReject;\n const dataPromise = new Promise((resolve, reject) => {\n dataResolve = resolve;\n dataReject = reject;\n });\n // Create discovery timeout promise and expose resolve/reject\n let discoveryResolve;\n let discoveryReject;\n let discoveryTimeoutId;\n let discovered = false;\n const discoveryPromise = new Promise((resolve, reject) => {\n discoveryResolve = resolve;\n discoveryReject = reject;\n discoveryTimeoutId = setTimeout(() => {\n reject(new Error(`Request \"${requestName}\" found no @respond('${requestName}') handler within ${discoveryTimeout}ms — ` +\n `attach a responding controller/element, or pass { optional: true } to resolve undefined when unhandled.`));\n }, discoveryTimeout);\n });\n // Dispatch event with promises\n const eventName = `@request/${requestName}`;\n const event = new CustomEvent(eventName, {\n bubbles: options?.bubbles !== undefined ? options.bubbles : true,\n cancelable: options?.cancelable || false,\n composed: true, // Allow crossing shadow DOM boundaries\n detail: {\n payload,\n discovery: {\n resolve: () => {\n discovered = true;\n clearTimeout(discoveryTimeoutId);\n discoveryResolve();\n },\n reject: discoveryReject\n },\n data: {\n resolve: dataResolve,\n reject: dataReject\n }\n }\n });\n // Check if this is a controller instance using the symbol\n const isController = this[IS_CONTROLLER_INSTANCE] === true;\n const dispatcher = isController && this.element ? this.element : this;\n dispatcher.dispatchEvent(event);\n try {\n // Wait for discovery timeout to be cleared (handler found) or discovery timeout to reject (no handler)\n await discoveryPromise;\n // If we get here, a handler was found and discovery timeout was cleared\n // Now wait for the actual data response with the full response timeout\n const responseTimeoutId = setTimeout(() => {\n dataReject(new Error(`Request \"${requestName}\" timed out after ${responseTimeout}ms`));\n }, responseTimeout);\n const response = await dataPromise;\n clearTimeout(responseTimeoutId);\n // Send response back to generator and get final return value\n const { value: finalValue } = await generator.next(response);\n return finalValue;\n }\n catch (error) {\n // optional: an unhandled request isn't an error — resume the generator\n // with undefined so `const data = await (yield payload)` sees no data.\n // A response TIMEOUT (handler exists but is slow) still throws.\n if (options?.optional && !discovered) {\n const { value: finalValue } = await generator.next(undefined);\n return finalValue;\n }\n // Drive the generator's own catch block and return whatever it recovers\n // with (e.g. a cached fallback). If the generator re-throws instead,\n // generator.throw rejects and the error propagates to the caller.\n const { value: recovered } = await generator.throw(error);\n return recovered;\n }\n }; // Close actualRequest function\n // Debounce\n if (options?.debounce) {\n return new Promise((resolve, reject) => {\n clearTimeout(debounceTimeout);\n debounceTimeout = setTimeout(async () => {\n try {\n resolve(await actualRequest());\n }\n catch (error) {\n reject(error);\n }\n }, options.debounce);\n });\n }\n // No throttle — execute immediately\n if (!options?.throttle)\n return actualRequest();\n // Throttle: time elapsed — invoke now\n const now = Date.now();\n const remaining = options.throttle - (now - throttleLastCall);\n if (remaining <= 0) {\n // Cancelling the scheduled trailing call must not orphan the promises\n // queued for it — settle them with this fresh result. Also reset\n // throttleTimeout so later within-window calls don't attach to a dead\n // timer and hang.\n clearTimeout(throttleTimeout);\n throttleTimeout = null;\n throttleLastCall = now;\n const orphaned = throttleTrailingResolvers.splice(0);\n const p = actualRequest();\n if (orphaned.length) {\n p.then((r) => { for (const x of orphaned)\n x.resolve(r); }, (e) => { for (const x of orphaned)\n x.reject(e); });\n }\n return p;\n }\n // Throttle: already has pending trailing call — attach to it\n if (throttleTimeout) {\n return new Promise((resolve, reject) => {\n throttleTrailingResolvers.push({ resolve, reject });\n });\n }\n // Throttle: schedule trailing call\n return new Promise((resolve, reject) => {\n throttleTrailingResolvers.push({ resolve, reject });\n throttleTimeout = setTimeout(async () => {\n throttleLastCall = Date.now();\n throttleTimeout = null;\n const resolvers = throttleTrailingResolvers.splice(0);\n try {\n const result = await actualRequest();\n for (const r of resolvers)\n r.resolve(result);\n }\n catch (error) {\n for (const r of resolvers)\n r.reject(error);\n }\n }, remaining);\n });\n };\n };\n}\n/**\n * Decorator for responding to requests in elements or controllers.\n *\n * @param requestName The name of the request to respond to\n * @param options Optional configuration\n */\nfunction respond(requestName, options) {\n return function (target, context) {\n const propertyKey = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // hasOwnProperty guards so subclasses don't mutate parent state via\n // the prototype chain.\n if (!Object.prototype.hasOwnProperty.call(constructor, RESPOND_METHODS)) {\n constructor[RESPOND_METHODS] = new Set();\n }\n if (constructor[RESPOND_METHODS].has(target))\n return;\n constructor[RESPOND_METHODS].add(target);\n if (!Object.prototype.hasOwnProperty.call(constructor, CHANNEL_HANDLERS)) {\n const inherited = constructor[CHANNEL_HANDLERS];\n constructor[CHANNEL_HANDLERS] = inherited ? [...inherited] : [];\n }\n constructor[CHANNEL_HANDLERS].push({\n channelName: requestName,\n methodName: propertyKey,\n method: target,\n options: options\n });\n });\n };\n}\n// Helper to setup response handlers for elements and controllers\nfunction setupResponseHandlers(instance, element) {\n const handlers = instance.constructor[CHANNEL_HANDLERS];\n if (!handlers)\n return;\n // Store cleanup functions\n // Initialize cleanup object if needed\n if (!instance[CLEANUP]) {\n instance[CLEANUP] = { events: [], channels: [] };\n }\n for (const handler of handlers) {\n const boundMethod = handler.method.bind(instance);\n const eventName = `@request/${handler.channelName}`;\n // Create timing variables for debounce/throttle per handler\n let debounceTimeout;\n let throttleLastCall = 0;\n let throttleTimeout;\n const throttleTrailingResolvers = [];\n let throttleLatestArgs = null;\n // Create wrapped method with timing if needed\n const createTimedMethod = (originalMethod) => {\n if (handler.options?.debounce) {\n return (...args) => new Promise((resolve, reject) => {\n clearTimeout(debounceTimeout);\n debounceTimeout = setTimeout(async () => {\n try {\n resolve(await originalMethod(...args));\n }\n catch (error) {\n reject(error);\n }\n }, handler.options.debounce);\n });\n }\n if (!handler.options?.throttle)\n return originalMethod;\n return (...args) => {\n const now = Date.now();\n const remaining = handler.options.throttle - (now - throttleLastCall);\n if (remaining <= 0) {\n // Same as the @request side: settle any queued trailing callers with\n // this fresh result rather than orphaning their promises.\n clearTimeout(throttleTimeout);\n throttleTimeout = null;\n throttleLastCall = now;\n const orphaned = throttleTrailingResolvers.splice(0);\n throttleLatestArgs = null;\n const result = originalMethod(...args);\n if (orphaned.length) {\n Promise.resolve(result).then((r) => { for (const x of orphaned)\n x.resolve(r); }, (e) => { for (const x of orphaned)\n x.reject(e); });\n }\n return result;\n }\n // Remember the LATEST args so the trailing call uses fresh input,\n // and queue every suppressed caller's resolver so they all receive\n // the trailing result instead of `undefined`.\n throttleLatestArgs = args;\n return new Promise((resolve, reject) => {\n throttleTrailingResolvers.push({ resolve, reject });\n if (throttleTimeout)\n return; // already scheduled\n throttleTimeout = setTimeout(async () => {\n throttleLastCall = Date.now();\n throttleTimeout = null;\n const resolvers = throttleTrailingResolvers.splice(0);\n const finalArgs = throttleLatestArgs ?? args;\n throttleLatestArgs = null;\n try {\n const result = await originalMethod(...finalArgs);\n for (const r of resolvers)\n r.resolve(result);\n }\n catch (error) {\n for (const r of resolvers)\n r.reject(error);\n }\n }, remaining);\n });\n };\n };\n const timedMethod = createTimedMethod(boundMethod);\n // Setup response handler\n const responseHandler = (event) => {\n // Extract promises and payload\n const { data, discovery, payload } = event.detail;\n // Prevent other responders from responding\n event.preventDefault();\n event.stopImmediatePropagation();\n event.stopPropagation();\n // Clear the discovery timeout immediately - we found a handler\n discovery.resolve();\n // Call the timed responder method and handle the result\n Promise.resolve(timedMethod(payload))\n .then(result => {\n data.resolve(result);\n })\n .catch(error => {\n data.reject(error);\n console.error(`Error in response handler ${handler.methodName}:`, error);\n });\n };\n element.addEventListener(eventName, responseHandler);\n instance[CLEANUP].channels.push(() => {\n element.removeEventListener(eventName, responseHandler);\n });\n }\n}\n// Helper to cleanup response handlers\nfunction cleanupResponseHandlers(instance) {\n if (instance[CLEANUP]?.channels) {\n for (const cleanup of instance[CLEANUP].channels) {\n cleanup();\n }\n instance[CLEANUP].channels = [];\n }\n}\n\n/**\n * Template system for Snice v3.0.0\n * Provides html`` and css`` tagged template processors with differential rendering\n */\n// Unique symbols for type checking\n// Use Symbol.for() to ensure symbols are shared across multiple Snice instances\nconst HTML_RESULT = Symbol.for('snice:html-result');\nconst CSS_RESULT = Symbol.for('snice:css-result');\n// Static css`` sites are the common stylesheet path and can be reused forever.\n// Interpolated sites are intentionally not retained: caching every distinct\n// primitive interpolation would turn a dynamic css`` call into an unbounded\n// per-callsite value history.\nconst cssResultCache = new WeakMap();\n/**\n * Tagged template function for creating HTML templates\n *\n * @example\n * ```typescript\n * html`<div class=\"card\">\n * <h1>${this.title}</h1>\n * <button @click=${this.handleClick}>Click me</button>\n * </div>`\n * ```\n */\nfunction html(strings, ...values) {\n return {\n _$litType$: HTML_RESULT,\n strings,\n values\n };\n}\n/**\n * Tagged template function for SVG fragments.\n *\n * Bare SVG elements (<circle>, <path>, ...) parse as unknown elements in an\n * HTML context. Use svg`` for fragments composed into a surrounding <svg>:\n *\n * @example\n * ```typescript\n * html`<svg viewBox=\"0 0 100 100\">${svg`<circle cx=\"50\" cy=\"50\" r=${r}></circle>`}</svg>`\n * ```\n */\nfunction svg(strings, ...values) {\n return {\n _$litType$: HTML_RESULT,\n strings,\n values,\n svg: true\n };\n}\n/**\n * Tagged template function for creating CSS\n *\n * @example\n * ```typescript\n * css`:host {\n * display: block;\n * padding: 1rem;\n * }`\n * ```\n */\nfunction css(strings, ...values) {\n const cached = values.length === 0 ? cssResultCache.get(strings) : undefined;\n if (cached)\n return cached;\n // Combine strings and values into final CSS text\n let cssText = strings[0];\n for (let i = 0; i < values.length; i++) {\n // Inline a nested css`` result by its text so style fragments compose;\n // String() on a CSSResult object would yield \"[object Object]\".\n const value = values[i];\n cssText += (isCSSResult(value) ? value.cssText : String(value)) + strings[i + 1];\n }\n const result = {\n _$litType$: CSS_RESULT,\n cssText\n };\n // Try to create constructable stylesheet for better performance\n // This will be cached and reused across instances. Guard against envs\n // without a Document global (for example, workers).\n if (typeof CSSStyleSheet !== 'undefined' &&\n typeof Document !== 'undefined' &&\n 'adoptedStyleSheets' in Document.prototype) {\n try {\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(cssText);\n result.styleSheet = sheet;\n }\n catch (e) {\n // Fall back to regular <style> tag if constructable stylesheets fail\n }\n }\n if (values.length === 0)\n cssResultCache.set(strings, result);\n return result;\n}\n/**\n * Check if a value is a TemplateResult\n */\nfunction isTemplateResult(value) {\n return value && value._$litType$ === HTML_RESULT;\n}\n/**\n * Check if a value is a CSSResult\n */\nfunction isCSSResult(value) {\n return value && value._$litType$ === CSS_RESULT;\n}\n/**\n * Nothing - represents no value (different from null/undefined)\n * Used to remove content from templates\n * Use Symbol.for() to ensure symbols are shared across multiple Snice instances\n */\nconst nothing = Symbol.for('snice:nothing');\n// Unique symbol for unsafe HTML\n// Use Symbol.for() to ensure symbols are shared across multiple Snice instances\nconst UNSAFE_HTML = Symbol.for('snice:unsafe-html');\n/**\n * Mark a string as raw HTML that should not be escaped\n * WARNING: Only use with sanitized content - using user input can lead to XSS!\n *\n * @example\n * ```typescript\n * const htmlString = '<span class=\"bold\">Hello</span>';\n * html`<div>${unsafeHTML(htmlString)}</div>`\n * ```\n */\nfunction unsafeHTML(html) {\n return {\n _$litType$: UNSAFE_HTML,\n html\n };\n}\n/**\n * Check if a value is an UnsafeHTML wrapper\n */\nfunction isUnsafeHTML(value) {\n return value && value._$litType$ === UNSAFE_HTML;\n}\n\nconst REPEAT_RESULT = Symbol.for('snice:repeat-result');\n/**\n * Render a keyed collection without adding wrapper elements.\n *\n * Keys are mandatory because repeat() is the explicit identity-preserving list\n * API. Duplicate keys throw before DOM reconciliation rather than silently\n * reusing the wrong row.\n */\nfunction repeat(items, options) {\n if (!options || typeof options.key !== 'function' || typeof options.render !== 'function') {\n throw new TypeError('snice: repeat() requires { key, render }.');\n }\n const array = items == null ? [] : Array.from(items);\n const keys = array.map(options.key);\n const seen = new Set();\n for (const key of keys) {\n if (seen.has(key)) {\n throw new Error(`snice: repeat() received duplicate key ${String(key)}.`);\n }\n seen.add(key);\n }\n return {\n _$repeat$: REPEAT_RESULT,\n items: array,\n keys,\n values: array.map(options.render),\n empty: array.length === 0\n ? typeof options.empty === 'function'\n ? options.empty()\n : options.empty\n : undefined\n };\n}\nfunction isRepeatResult(value) {\n return !!value && value._$repeat$ === REPEAT_RESULT;\n}\n\nconst renderHosts = new WeakSet();\nfunction getRenderRoot(element) {\n return element[RENDER_ROOT] || element.shadowRoot || null;\n}\nfunction ensureRenderRoot(element) {\n const existing = getRenderRoot(element);\n if (existing)\n return existing;\n const options = element.constructor[ELEMENT_OPTIONS];\n let root;\n if (options?.renderRoot === 'light' || options?.shadow === false) {\n root = element;\n }\n else if (typeof element.createRenderRoot === 'function') {\n root = element.createRenderRoot();\n }\n else {\n const mode = typeof options?.shadow === 'string' ? options.shadow : 'open';\n root = element.attachShadow({ mode, delegatesFocus: options?.delegatesFocus });\n }\n if (root !== element && !(root instanceof ShadowRoot)) {\n throw new TypeError('snice: createRenderRoot() must return the host element or a ShadowRoot.');\n }\n element[RENDER_ROOT] = root;\n renderHosts.add(element);\n return root;\n}\nfunction findRenderHost(node) {\n const root = node.getRootNode();\n if (root instanceof ShadowRoot)\n return root.host;\n let current = node;\n while (current) {\n if (current instanceof HTMLElement && renderHosts.has(current))\n return current;\n current = current.parentNode;\n }\n return null;\n}\n\n// Unique marker for dynamic parts\n// This parses as a comment node but doesn't get escaped in attributes\nconst marker = `snice$${Math.random().toFixed(9).slice(2)}$`;\nconst markerMatch = '?' + marker;\n// A true comment, not a processing instruction (<?...>): in HTML content both\n// parse to the same comment node, but PIs are dropped inside foreign content\n// (<svg>), which would silently kill any node binding inside an svg block.\nconst nodeMarker = `<!--${markerMatch}-->`;\n// Escape the `$` chars — as a bare RegExp they'd be end anchors and the\n// pattern would never match, so marker-bearing text/comments never split.\nconst markerRegex = new RegExp(marker.replace(/\\$/g, '\\\\$'), 'g');\n// Template cache - templates with same string array can be reused\nconst templateCache = new WeakMap();\n// Sentinel for \"not yet set\" - distinct from undefined/null\nconst NOT_COMMITTED = Symbol('not-committed');\nfunction markPreUpgradePropertyBinding(element, propertyName) {\n const tagName = element.localName;\n if (!tagName?.includes('-'))\n return;\n const registry = element.ownerDocument?.defaultView?.customElements ?? globalThis.customElements;\n if (registry?.get(tagName))\n return;\n const target = element;\n if (!target[PRE_UPGRADE_PROPERTY_BINDINGS])\n target[PRE_UPGRADE_PROPERTY_BINDINGS] = new Set();\n target[PRE_UPGRADE_PROPERTY_BINDINGS].add(propertyName);\n}\n// noChange sentinel - preserves the currently committed value\nconst noChange = Symbol.for('snice:no-change');\n// live() wrapper - marks a property binding value for comparison against the\n// actual DOM property instead of the last committed value\nconst LIVE_MARKER = Symbol.for('snice:live');\n/**\n * Wrap a property binding value so the commit compares against the element's\n * CURRENT DOM property rather than the last committed value. Use for inputs\n * whose DOM state the user can change out from under the binding:\n *\n * ```typescript\n * html`<input .value=${live(this.text)} />`\n * ```\n *\n * Without live(), re-rendering with an unchanged bound value skips the DOM\n * write, leaving user-typed text in place.\n */\nfunction live(value) {\n return { _$liveMarker$: LIVE_MARKER, value };\n}\nfunction isLive(value) {\n return value && value._$liveMarker$ === LIVE_MARKER;\n}\n/**\n * Check if value is a primitive (can be compared with ===)\n */\nconst isPrimitive = (value) => value === null || (typeof value !== 'object' && typeof value !== 'function');\n/**\n * Check if value is iterable (array or has Symbol.iterator)\n */\nconst isIterable = (value) => Array.isArray(value) || typeof value?.[Symbol.iterator] === 'function';\nconst isPromiseLike = (value) => !!value && typeof value.then === 'function';\nconst isAsyncIterable = (value) => !!value && typeof value[Symbol.asyncIterator] === 'function';\n/**\n * A prepared template ready for rendering\n */\nclass Template {\n constructor(result, element, attrNamesForParts) {\n this.parts = [];\n /**\n * Value index of a `key=${...}` binding in this template, or -1 if unkeyed.\n * Used by keyed list reconciliation in NodePart._commitIterable.\n */\n this.keyIndex = -1;\n this.element = element;\n const walker = document.createTreeWalker(element.content, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT);\n let partIndex = 0;\n const nodesToRemove = [];\n let node;\n while ((node = walker.nextNode()) !== null) {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const element = node;\n const tagName = element.tagName.toLowerCase();\n const parentTag = element.parentElement?.tagName.toLowerCase();\n if ((tagName === 'else' || tagName === 'else-if') && parentTag !== 'if') {\n throw new Error(`snice: <${tagName}> must be a direct child of <if>.`);\n }\n if ((tagName === 'when' || tagName === 'default') && parentTag !== 'case') {\n throw new Error(`snice: <${tagName}> must be a direct child of <case>.`);\n }\n // Handle virtual elements: <if>, <else-if>, <case>, <when>\n // Keep them in the DOM with display:contents for now\n // Will optimize later with proper template extraction\n if (tagName === 'if') {\n // <if value=\"${condition}\">children</if>\n const valueAttr = element.getAttribute('value');\n if (valueAttr && valueAttr.includes(marker)) {\n // Remove the value attribute\n element.removeAttribute('value');\n this.parts.push({\n type: 'conditional-if',\n index: partIndex++,\n element // Keep the <if> element\n });\n // Continue processing children normally\n }\n else {\n throw new Error('snice: <if> requires a condition expression.');\n }\n continue;\n }\n // Handle <case> element\n if (tagName === 'case') {\n // <case value=\"${value}\">children</case>\n const valueAttr = element.getAttribute('value');\n if (valueAttr && valueAttr.includes(marker)) {\n for (const child of Array.from(element.childNodes)) {\n if (child.nodeType === Node.ELEMENT_NODE) {\n const branchTag = child.tagName.toLowerCase();\n if (branchTag !== 'when' && branchTag !== 'default') {\n throw new Error('snice: <case> may contain only direct <when> and <default> branches.');\n }\n }\n else if (child.nodeType === Node.TEXT_NODE && child.textContent?.trim() ||\n child.nodeType === Node.COMMENT_NODE && child.data.includes(marker)) {\n throw new Error('snice: content inside <case> must be nested in a <when> or <default> branch.');\n }\n }\n // Remove the value attribute\n element.removeAttribute('value');\n this.parts.push({\n type: 'conditional-case',\n index: partIndex++,\n element // Keep the <case> element\n });\n // Continue processing children normally\n }\n else {\n throw new Error('snice: <case> requires a value expression.');\n }\n continue;\n }\n if (tagName === 'else-if') {\n const valueAttr = element.getAttribute('value');\n if (valueAttr && valueAttr.includes(marker)) {\n element.removeAttribute('value');\n this.parts.push({\n type: 'conditional-else-if',\n index: partIndex++,\n element\n });\n }\n else {\n throw new Error('snice: <else-if> requires a condition expression.');\n }\n continue;\n }\n if (tagName === 'when') {\n const valueAttr = element.getAttribute('value');\n if (valueAttr && valueAttr.includes(marker)) {\n element.removeAttribute('value');\n this.parts.push({\n type: 'conditional-when',\n index: partIndex++,\n element\n });\n }\n continue;\n }\n if (element.hasAttributes()) {\n const attributes = element.attributes;\n const attrsToRemove = [];\n for (let i = 0; i < attributes.length; i++) {\n const attr = attributes[i];\n const value = attr.value;\n // Check for attribute bindings\n if (value.includes(marker)) {\n attrsToRemove.push(attr);\n // Get original attribute name with preserved case\n const originalName = attrNamesForParts[partIndex] || attr.name;\n // Extract static string segments by splitting on marker\n const attrStrings = value.split(marker);\n // Number of expressions = number of markers = attrStrings.length - 1\n const expressionCount = attrStrings.length - 1;\n // Property/boolean/event bindings take a SINGLE expression — they\n // can't concatenate static text (a `.prop` is an object, not a\n // string). They consume the first expression; any static text or\n // extra expressions are ignored. But the value index must still\n // advance by the true marker count, or every later binding shifts.\n const isSingleExpressionBinding = /^@@?|^[.?]/.test(originalName) ||\n originalName.startsWith('...') ||\n originalName.startsWith('class:') ||\n originalName.startsWith('style:');\n if (isSingleExpressionBinding) {\n const hasStaticText = attrStrings.some((s) => s !== '');\n if (expressionCount > 1 || hasStaticText) {\n console.warn(`snice: binding \"${originalName}\" takes a single expression; ` +\n `static text and extra interpolations are ignored. ` +\n `Use a plain attribute for string interpolation.`);\n }\n }\n if (originalName.startsWith('...')) {\n const spreadName = originalName.slice(3).toLowerCase();\n if (!['props', 'properties', 'attrs', 'attributes', 'events'].includes(spreadName)) {\n throw new Error(`snice: unknown spread binding \"${originalName}\". ` +\n 'Use ...props, ...attrs, or ...events.');\n }\n this.parts.push({\n type: 'spread',\n index: partIndex,\n name: spreadName,\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('class:')) {\n if (!originalName.slice(6))\n throw new Error('snice: class: binding requires a class name.');\n this.parts.push({\n type: 'class',\n index: partIndex,\n name: originalName.slice(6),\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('style:')) {\n if (!originalName.slice(6))\n throw new Error('snice: style: binding requires a CSS property name.');\n this.parts.push({\n type: 'style',\n index: partIndex,\n name: originalName.slice(6),\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('@@')) {\n if (!originalName.slice(2).split('|')[0])\n throw new Error('snice: event binding requires an event name.');\n // Escaped event binding for events with @ in the name (e.g., @@snice/event -> @snice/event)\n this.parts.push({\n type: 'event',\n index: partIndex,\n name: originalName.slice(1), // Keep the @ in the event name\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('@')) {\n if (!originalName.slice(1).split('|')[0])\n throw new Error('snice: event binding requires an event name.');\n // Event binding (single value only)\n this.parts.push({\n type: 'event',\n index: partIndex,\n name: originalName.slice(1),\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('.')) {\n if (!originalName.slice(1))\n throw new Error('snice: property binding requires a property name.');\n // Property binding (single value only)\n this.parts.push({\n type: 'property',\n index: partIndex,\n name: originalName.slice(1),\n element\n });\n partIndex += expressionCount;\n }\n else if (originalName.startsWith('?')) {\n if (!originalName.slice(1))\n throw new Error('snice: boolean binding requires an attribute name.');\n // Boolean attribute (single value only)\n this.parts.push({\n type: 'boolean-attribute',\n index: partIndex,\n name: originalName.slice(1),\n element\n });\n partIndex += expressionCount;\n }\n else if (attr.name === 'controller' &&\n attrStrings.length === 2 && attrStrings[0] === '' && attrStrings[1] === '') {\n // Bare controller=${...} binding: accepts a decorated\n // controller class directly, or a registry name string.\n // Interpolated forms (controller=\"a-${x}\") stay plain\n // string attributes.\n this.parts.push({\n type: 'controller',\n index: partIndex,\n element\n });\n partIndex += expressionCount;\n }\n else {\n // Regular attribute - supports multiple interpolations\n // Store static string segments for interpolation\n this.parts.push({\n type: 'attribute',\n index: partIndex,\n name: attr.name,\n element,\n attrStrings\n });\n // Increment by number of expressions consumed\n partIndex += expressionCount;\n }\n }\n }\n // Remove marker attributes\n for (const attr of attrsToRemove) {\n element.removeAttribute(attr.name);\n }\n }\n }\n else if (node.nodeType === Node.COMMENT_NODE) {\n const comment = node;\n // Check for marker match (processing instruction becomes comment)\n if (comment.data === markerMatch) {\n // Node part\n const parent = comment.parentNode;\n const endNode = document.createComment('');\n parent.insertBefore(endNode, comment.nextSibling);\n this.parts.push({\n type: 'node',\n index: partIndex++,\n startNode: comment,\n endNode\n });\n }\n else if (comment.data.includes(marker)) {\n // Binding(s) inside an authored HTML comment (<!-- ${x} -->).\n // Render values into the comment text; critically, consume the\n // right number of value indices so later parts stay aligned.\n const commentStrings = comment.data.split(markerRegex);\n this.parts.push({\n type: 'comment',\n index: partIndex,\n startNode: comment,\n attrStrings: commentStrings\n });\n partIndex += commentStrings.length - 1;\n }\n }\n else if (node.nodeType === Node.TEXT_NODE) {\n const text = node;\n const data = text.data;\n if (data.includes(marker)) {\n // Split text node at markers\n const parent = text.parentNode;\n const parts = data.split(markerRegex);\n const lastIndex = parts.length - 1;\n for (let i = 0; i < lastIndex; i++) {\n parent.insertBefore(document.createTextNode(parts[i]), text);\n const comment = document.createComment('');\n const endNode = document.createComment('');\n parent.insertBefore(comment, text);\n parent.insertBefore(endNode, text);\n this.parts.push({\n type: 'node',\n index: partIndex++,\n startNode: comment,\n endNode\n });\n }\n // Last part\n if (parts[lastIndex] !== '') {\n text.data = parts[lastIndex];\n }\n else {\n nodesToRemove.push(text);\n }\n }\n }\n }\n // Remove marker nodes\n for (const node of nodesToRemove) {\n node.parentNode?.removeChild(node);\n }\n // Record the value index of a `key=${...}` binding (first one wins) so\n // list rendering can associate DOM with keys instead of indices.\n for (const part of this.parts) {\n if (part.type === 'attribute' && part.name === 'key') {\n this.keyIndex = part.index;\n break;\n }\n }\n }\n}\n/**\n * Prepare a template for rendering\n *\n * Uses state tracking to correctly handle multi-interpolation in attributes.\n * Tracks whether we're inside a tag and inside a quoted attribute value.\n */\nfunction prepareTemplate(result) {\n // Check cache first\n const { strings } = result;\n const cached = templateCache.get(strings);\n if (cached) {\n return cached;\n }\n // Build HTML with markers and extract original attribute names\n const htmlParts = [];\n const attrNamesForParts = [];\n // State tracking for multi-interpolation support\n let inTag = false; // Inside a tag (between < and >)\n let inAttrValue = false; // Inside a quoted attribute value\n let inComment = false; // Inside an HTML comment (<!-- ... -->)\n let attrQuoteChar = ''; // The quote character (' or \")\n let currentAttrName = ''; // The current attribute name\n for (let i = 0; i < strings.length; i++) {\n const str = strings[i];\n htmlParts.push(str);\n if (i < strings.length - 1) {\n // Update state by scanning the string\n for (let j = 0; j < str.length; j++) {\n const char = str[j];\n if (inComment) {\n // Only the closing --> matters inside a comment\n if (char === '-' && str.startsWith('-->', j)) {\n inComment = false;\n j += 2;\n }\n }\n else if (!inTag) {\n // Looking for tag start (or comment start)\n if (char === '<') {\n if (str.startsWith('<!--', j)) {\n inComment = true;\n j += 3;\n }\n else if (/[A-Za-z!/?]/.test(str[j + 1] || '')) {\n inTag = true;\n }\n }\n }\n else if (!inAttrValue) {\n // Inside tag, but not in attribute value\n if (char === '>') {\n inTag = false;\n }\n else if (char === '\"' || char === \"'\") {\n inAttrValue = true;\n attrQuoteChar = char;\n }\n else if (char === '=') {\n // Extract attribute name (look backwards for it).\n // Includes `~` for the \"any-modifier\" keyboard prefix\n // (e.g. `@keydown.~enter`) so it isn't truncated to `.enter`.\n let attrStart = j - 1;\n while (attrStart >= 0 && /[\\w\\-\\.@\\?/:\\+~|]/.test(str[attrStart])) {\n attrStart--;\n }\n currentAttrName = str.substring(attrStart + 1, j).trim();\n }\n }\n else {\n // Inside quoted attribute value\n if (char === attrQuoteChar) {\n inAttrValue = false;\n attrQuoteChar = '';\n }\n }\n }\n // Now determine what kind of marker to insert based on current state\n if (inComment) {\n // Binding inside an HTML comment — insert a plain marker into the\n // comment text. The Template scanner turns it into a CommentPart so\n // the value index stays aligned (a swallowed marker would shift every\n // binding after the comment).\n attrNamesForParts.push('');\n htmlParts.push(marker);\n }\n else if (inAttrValue) {\n // We're inside a quoted attribute value - this is an attribute binding\n // For subsequent interpolations in same attribute, keep using same attr name\n attrNamesForParts.push(currentAttrName);\n htmlParts.push(marker);\n }\n else if (inTag) {\n // Inside tag but not in attr value - check for special cases\n // Check if this is start of attribute value (= at end of string)\n const trimmed = str.trimEnd();\n if (trimmed.endsWith('=')) {\n // Extract attribute name (same `~` inclusion as the in-tag branch\n // above — supports `@keydown.~enter` keyboard modifier prefix).\n let attrStart = trimmed.length - 2;\n while (attrStart >= 0 && /[\\w\\-\\.@\\?\\/:\\+~|]/.test(trimmed[attrStart])) {\n attrStart--;\n }\n currentAttrName = trimmed.substring(attrStart + 1, trimmed.length - 1).trim();\n attrNamesForParts.push(currentAttrName);\n htmlParts.push(marker);\n }\n else {\n // Check if this is a meta element (<if> or <case>)\n const metaElementMatch = str.match(/<(if|else-if|case|when)\\s*$/);\n if (metaElementMatch) {\n currentAttrName = 'value';\n attrNamesForParts.push('value');\n htmlParts.push(`value=\"${marker}\"`);\n }\n else {\n throw new Error('snice: expressions directly in opening tags are not supported; ' +\n 'use an explicit attribute, property, event, class, style, or named spread binding.');\n }\n }\n }\n else {\n // Outside any tag - this is node content\n attrNamesForParts.push('');\n htmlParts.push(nodeMarker);\n }\n }\n }\n const html = htmlParts.join('');\n const template = document.createElement('template');\n if (result.svg) {\n // Parse in the SVG namespace by wrapping, then unwrap: the parsed nodes\n // keep their namespace when moved out of the temporary <svg> element.\n template.innerHTML = `<svg>${html}</svg>`;\n const wrapper = template.content.firstElementChild;\n while (wrapper.firstChild) {\n template.content.insertBefore(wrapper.firstChild, wrapper);\n }\n template.content.removeChild(wrapper);\n }\n else {\n template.innerHTML = html;\n }\n const tmpl = new Template(result, template, attrNamesForParts);\n // Cache the template for reuse\n templateCache.set(strings, tmpl);\n return tmpl;\n}\n/**\n * Extract the key of a list item rendered from a template with a\n * `key=${...}` binding. Returns undefined for unkeyed items.\n */\nfunction getItemKey(item) {\n if (!isTemplateResult(item))\n return undefined;\n const tmpl = prepareTemplate(item);\n return tmpl.keyIndex === -1 ? undefined : item.values[tmpl.keyIndex];\n}\n/**\n * Instance of a rendered template\n */\nclass TemplateInstance {\n constructor(result) {\n this.parts = [];\n this.fragment = null;\n this.conditionalParts = []; // if/case parts with their indices\n this.regularParts = []; // all other parts with their indices\n this.template = prepareTemplate(result);\n this.strings = result.strings;\n }\n /**\n * Check if this instance uses the same template strings\n * (template identity is based on the strings array reference)\n */\n isSameTemplate(strings) {\n return this.strings === strings;\n }\n renderFragment() {\n if (!this.fragment) {\n // First render - clone template and create parts\n this.fragment = this.template.element.content.cloneNode(true);\n // Build a map of nodes from template to cloned fragment\n const walker = document.createTreeWalker(this.template.element.content, NodeFilter.SHOW_ALL);\n const clonedWalker = document.createTreeWalker(this.fragment, NodeFilter.SHOW_ALL);\n const nodeMap = new Map();\n let templateNode = walker.currentNode;\n let clonedNode = clonedWalker.currentNode;\n while (templateNode && clonedNode) {\n nodeMap.set(templateNode, clonedNode);\n templateNode = walker.nextNode();\n clonedNode = clonedWalker.nextNode();\n }\n const dynamicWhenElements = new Set();\n for (const definition of this.template.parts) {\n if (definition.type === 'conditional-when') {\n dynamicWhenElements.add(nodeMap.get(definition.element));\n }\n }\n for (let i = 0; i < this.template.parts.length; i++) {\n const partDef = this.template.parts[i];\n let part;\n switch (partDef.type) {\n case 'node':\n const startNode = nodeMap.get(partDef.startNode);\n const endNode = nodeMap.get(partDef.endNode);\n part = new NodePart(startNode, endNode);\n break;\n case 'attribute':\n const attrElement = nodeMap.get(partDef.element);\n part = new AttributePart(attrElement, partDef.name, partDef.attrStrings);\n break;\n case 'property':\n const propElement = nodeMap.get(partDef.element);\n part = new PropertyPart(propElement, partDef.name);\n break;\n case 'boolean-attribute':\n const boolElement = nodeMap.get(partDef.element);\n part = new BooleanAttributePart(boolElement, partDef.name);\n break;\n case 'event':\n const eventElement = nodeMap.get(partDef.element);\n part = new EventPart(eventElement, partDef.name);\n break;\n case 'class':\n const classElement = nodeMap.get(partDef.element);\n part = new ClassPart(classElement, partDef.name);\n break;\n case 'style':\n const styleElement = nodeMap.get(partDef.element);\n part = new StylePart(styleElement, partDef.name);\n break;\n case 'spread':\n const spreadElement = nodeMap.get(partDef.element);\n part = new SpreadPart(spreadElement, partDef.name);\n break;\n case 'controller':\n const controllerElement = nodeMap.get(partDef.element);\n part = new ControllerPart(controllerElement);\n break;\n case 'conditional-if':\n const conditionalIfElement = nodeMap.get(partDef.element);\n part = new ConditionalIfPart(conditionalIfElement);\n break;\n case 'conditional-else-if':\n const conditionalElseIfElement = nodeMap.get(partDef.element);\n part = new ConditionalElseIfPart(conditionalElseIfElement);\n break;\n case 'conditional-case':\n const conditionalCaseElement = nodeMap.get(partDef.element);\n part = new ConditionalCasePart(conditionalCaseElement, dynamicWhenElements);\n break;\n case 'conditional-when':\n const conditionalWhenElement = nodeMap.get(partDef.element);\n part = new ConditionalWhenPart(conditionalWhenElement);\n break;\n case 'comment':\n const commentNode = nodeMap.get(partDef.startNode);\n part = new CommentPart(commentNode, partDef.attrStrings);\n break;\n default:\n throw new Error(`Unknown part type: ${partDef.type}`);\n }\n this.parts.push(part);\n // Separate conditional parts from regular parts for optimized update\n // Use partDef.index (the VALUE index) not i (the part array index)\n if (part instanceof ConditionalIfPart ||\n part instanceof ConditionalElseIfPart ||\n part instanceof ConditionalCasePart ||\n part instanceof ConditionalWhenPart) {\n this.conditionalParts.push({ part, index: partDef.index });\n }\n else {\n this.regularParts.push({ part, index: partDef.index });\n }\n }\n }\n return this.fragment;\n }\n render(values) {\n const fragment = this.renderFragment();\n // Commit values to parts\n this.update(values);\n return fragment;\n }\n update(values) {\n // Optimized: Process conditional parts first (if any), then regular parts\n // Using pre-separated arrays with cached indices avoids instanceof and indexOf calls\n // Process conditional parts first (they control visibility)\n for (const { part, index } of this.conditionalParts) {\n part.commit(values[index]);\n }\n // Conditions are staged above, then flushed once. This avoids transiently\n // mounting an else/default branch while later else-if/when expressions in\n // the same update are still being committed.\n const flushed = new Set();\n for (const { part } of this.conditionalParts) {\n const coordinator = part instanceof ConditionalElseIfPart\n ? part.coordinator\n : part instanceof ConditionalWhenPart\n ? part.coordinator\n : part;\n if (flushed.has(coordinator))\n continue;\n flushed.add(coordinator);\n if (coordinator instanceof ConditionalIfPart || coordinator instanceof ConditionalCasePart) {\n coordinator.flush();\n }\n }\n for (const { part, index } of this.regularParts) {\n // AttributeParts with interpolation consume multiple values\n if (part instanceof AttributePart && part.strings !== undefined) {\n // Pass full values array and starting index for interpolation\n part.commit(values, index);\n // The part consumes (strings.length - 1) values\n // But since we're iterating by template part index, this is handled by the Template\n }\n else if (part instanceof CommentPart) {\n // CommentParts also consume (strings.length - 1) values\n part.commit(values, index);\n }\n else {\n part.commit(values[index]);\n }\n }\n // Branch switches can move event-bearing nodes between the live DOM and\n // parked fragments. Reconcile connection state after every update so\n // listeners detach while parked and reattach when their branch returns.\n let lifecycleError;\n for (const part of this.parts) {\n try {\n if (part.isConnected)\n part.reconnected();\n else\n part.disconnected();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n clear() {\n let lifecycleError;\n for (const part of this.parts) {\n try {\n part.destroy();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n disconnected(preserveEventListeners = false) {\n let lifecycleError;\n for (const part of this.parts) {\n try {\n part.disconnected(preserveEventListeners);\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n reconnected() {\n let lifecycleError;\n for (const part of this.parts) {\n try {\n part.reconnected();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n}\n/**\n * Base class for all parts\n */\nclass Part {\n get isConnected() {\n return this.element?.isConnected ?? false;\n }\n disconnected(_preserveEventListeners = false) { }\n reconnected() { }\n destroy() {\n let lifecycleError;\n try {\n this.clear();\n }\n catch (error) {\n lifecycleError = error;\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n}\n/**\n * NodePart handles text content and nested templates\n *\n * Lit-HTML style optimizations:\n * - Reuses TemplateInstance when same template strings are rendered\n * - Reuses text nodes when updating primitive → primitive\n * - Reuses child NodeParts when rendering arrays\n */\nclass NodePart extends Part {\n constructor(startNode, endNode) {\n super();\n this.type = 'node';\n this._committedValue = NOT_COMMITTED;\n this._itemKeys = null; // keys of the last committed iterable, when fully keyed\n this._asyncSource = null;\n this._asyncVersion = 0;\n this._asyncIterator = null;\n this._asyncRunning = false;\n this._asyncStarted = false;\n this._asyncCompleted = false;\n this._asyncPaused = false;\n this._committingAsyncValue = false;\n this.startNode = startNode;\n this.endNode = endNode;\n }\n commit(value) {\n // Handle noChange sentinel\n if (value === noChange) {\n return;\n }\n if (isPromiseLike(value) || isAsyncIterable(value)) {\n this._commitAsync(value);\n return;\n }\n if (!this._committingAsyncValue && this._asyncSource)\n this._cancelAsync(true);\n // Handle nothing/null/undefined/empty - clear content\n if (value === nothing || value == null || value === '') {\n if (this._committedValue !== nothing) {\n const cleanupError = this._clear();\n this._committedValue = nothing;\n if (cleanupError)\n throw cleanupError;\n }\n this._committedValue = nothing;\n return;\n }\n // Handle primitives (string, number, boolean, bigint, symbol)\n if (isPrimitive(value)) {\n if (value !== this._committedValue) {\n this._commitText(value);\n }\n return;\n }\n // Handle nested templates\n if (isTemplateResult(value)) {\n this._commitTemplateResult(value);\n return;\n }\n // Explicit keyed repeat() result. It feeds keys directly into the list\n // reconciler, so rendered roots do not need a synthetic key attribute or\n // wrapper element.\n if (isRepeatResult(value)) {\n if (value.values.length === 0) {\n this.commit(value.empty ?? nothing);\n }\n else {\n this._commitIterable(value.values, value.keys);\n }\n return;\n }\n // Handle unsafe HTML\n if (isUnsafeHTML(value)) {\n this._commitUnsafeHTML(value);\n return;\n }\n // Handle DOM nodes\n if (value.nodeType !== undefined) {\n this._commitNode(value);\n return;\n }\n // Handle iterables (arrays, etc.)\n if (isIterable(value)) {\n this._commitIterable(value);\n return;\n }\n // Fallback: convert to string\n this._commitText(value);\n }\n /**\n * Commit a primitive value as text\n * OPTIMIZATION: Reuses existing text node if previous value was also primitive\n */\n _commitText(value) {\n // Try to reuse existing text node\n const canReuse = this._committedValue !== NOT_COMMITTED &&\n this._committedValue !== nothing &&\n isPrimitive(this._committedValue) &&\n !Array.isArray(this._committedValue);\n if (canReuse) {\n const textNode = this.startNode.nextSibling;\n if (textNode && textNode.nodeType === Node.TEXT_NODE) {\n textNode.data = String(value);\n this._committedValue = value;\n return;\n }\n }\n const cleanupError = this._clear();\n this._insertBefore(document.createTextNode(String(value)));\n this._committedValue = value;\n if (cleanupError)\n throw cleanupError;\n }\n /**\n * Commit a TemplateResult\n * OPTIMIZATION: Reuses TemplateInstance if same template strings\n */\n _commitTemplateResult(result) {\n // Check if we can reuse the existing TemplateInstance\n const committedInstance = this._committedValue;\n if (committedInstance instanceof TemplateInstance) {\n // Check if same template by comparing strings reference\n const cachedTemplate = templateCache.get(result.strings);\n if (cachedTemplate && committedInstance.template === cachedTemplate) {\n // SAME TEMPLATE - just update values (efficient path!)\n committedInstance.update(result.values);\n return;\n }\n }\n // Different template or first render: prepare and validate the replacement\n // while it is detached. If a binding throws, the currently\n // committed range remains intact and its lifecycle stays connected.\n const instance = new TemplateInstance(result);\n const fragment = instance.renderFragment();\n try {\n instance.update(result.values);\n }\n catch (error) {\n instance.clear();\n throw error;\n }\n const previousValue = this._committedValue;\n const previousKeys = this._itemKeys;\n const previousFragment = this.endNode.ownerDocument.createDocumentFragment();\n let previousNode = this.startNode.nextSibling;\n while (previousNode && previousNode !== this.endNode) {\n const next = previousNode.nextSibling;\n previousFragment.appendChild(previousNode);\n previousNode = next;\n }\n this._insertBefore(fragment);\n this._committedValue = instance;\n this._itemKeys = null;\n try {\n if (this.isConnected)\n instance.reconnected();\n }\n catch (error) {\n try {\n instance.clear();\n }\n catch (cleanupError) {\n console.error('snice: failed to clean up a rejected nested template:', cleanupError);\n }\n let node = this.startNode.nextSibling;\n while (node && node !== this.endNode) {\n const next = node.nextSibling;\n node.remove();\n node = next;\n }\n this._insertBefore(previousFragment);\n this._committedValue = previousValue;\n this._itemKeys = previousKeys;\n throw error;\n }\n this._disposeCommitted(previousValue);\n }\n /**\n * Commit an iterable (array, Set, etc.)\n * OPTIMIZATION: Reuses existing NodeParts for items\n */\n _commitIterable(value, explicitKeys) {\n const items = Array.isArray(value) ? value : Array.from(value);\n const newKeys = explicitKeys ? Array.from(explicitKeys) : items.map(getItemKey);\n if (newKeys.length !== items.length) {\n throw new Error('snice: keyed iterable produced a different number of keys and values.');\n }\n const definedKeys = newKeys.filter(key => key !== undefined);\n if (definedKeys.length > 0 && definedKeys.length !== newKeys.length) {\n console.warn('snice: a list mixes keyed and unkeyed items. Identity falls back to position; ' +\n 'use repeat(items, { key, render }) for deterministic updates.');\n }\n if (definedKeys.length > 0 && new Set(definedKeys).size !== definedKeys.length) {\n throw new Error('snice: a keyed list contains duplicate keys.');\n }\n let cleanupError;\n // If previous value wasn't an array of parts, start fresh\n if (!Array.isArray(this._committedValue) ||\n !(this._committedValue[0] instanceof NodePart)) {\n cleanupError = this._clear();\n this._committedValue = [];\n this._itemKeys = null;\n }\n const allKeyed = items.length > 0 && newKeys.every(k => k !== undefined);\n const oldKeys = this._itemKeys;\n // Keyed reconciliation: when every item carries a key=${...} binding and\n // the key order changed, DOM (and its state) follows the key, not the\n // index. Unchanged key order falls through to the cheap index path.\n if (allKeyed && oldKeys && this._committedValue.length > 0) {\n const sameOrder = oldKeys.length === newKeys.length &&\n newKeys.every((k, i) => k === oldKeys[i]);\n if (!sameOrder) {\n cleanupError ??= this._reconcileKeyed(items, newKeys, this._committedValue, oldKeys);\n this._itemKeys = newKeys;\n if (cleanupError)\n throw cleanupError;\n return;\n }\n }\n const itemParts = this._committedValue;\n let partIndex = 0;\n for (const item of items) {\n let itemPart;\n if (partIndex >= itemParts.length) {\n // Need new NodePart - create with markers\n const startMarker = document.createComment('');\n const endMarker = document.createComment('');\n this._insertBefore(startMarker);\n this._insertBefore(endMarker);\n itemPart = new NodePart(startMarker, endMarker);\n itemParts.push(itemPart);\n }\n else {\n // Reuse existing NodePart\n itemPart = itemParts[partIndex];\n }\n // Set value on this part (recursively handles templates, text, etc.)\n itemPart.commit(item);\n partIndex++;\n }\n // Cleanup excess parts from previous render\n if (partIndex < itemParts.length) {\n // Clear DOM for removed items\n for (let i = partIndex; i < itemParts.length; i++) {\n const part = itemParts[i];\n // Dispose async state as well as removing the content. These item parts\n // are leaving the list permanently, not merely being moved.\n try {\n part.destroy();\n }\n catch (error) {\n cleanupError ??= error;\n }\n // Remove the markers themselves\n part.startNode.remove();\n part.endNode.remove();\n }\n // Truncate array\n itemParts.length = partIndex;\n }\n // Remember keys so the next commit can reconcile by key\n this._itemKeys = allKeyed ? newKeys : null;\n if (cleanupError)\n throw cleanupError;\n }\n /**\n * Reorder/reuse item parts so each key keeps its DOM.\n * Old parts whose keys disappeared are removed; new keys get fresh parts.\n */\n _reconcileKeyed(items, newKeys, oldParts, oldKeys) {\n const parent = this.endNode.parentNode;\n let cleanupError;\n // Map old parts by key (first occurrence wins on duplicate keys)\n const oldByKey = new Map();\n for (let i = 0; i < oldParts.length; i++) {\n if (!oldByKey.has(oldKeys[i]))\n oldByKey.set(oldKeys[i], oldParts[i]);\n }\n // Choose a part for each new item: reuse by key, or create during placement\n const reused = new Set();\n const newParts = new Array(items.length).fill(null);\n for (let i = 0; i < items.length; i++) {\n const candidate = oldByKey.get(newKeys[i]);\n if (candidate && !reused.has(candidate)) {\n reused.add(candidate);\n newParts[i] = candidate;\n }\n }\n // Remove parts whose keys are gone (before placement, so the DOM walk\n // below only ever sees surviving nodes)\n for (const part of oldParts) {\n if (!reused.has(part)) {\n try {\n part.destroy();\n }\n catch (error) {\n cleanupError ??= error;\n }\n part.startNode.remove();\n part.endNode.remove();\n }\n }\n // Place parts in order. `ref` walks the surviving DOM; a part already\n // sitting at `ref` is skipped, anything else is moved (or created) there.\n let ref = this.startNode.nextSibling;\n for (let i = 0; i < newParts.length; i++) {\n let part = newParts[i];\n if (part) {\n if (part.startNode === ref) {\n // Already in position — advance past its range\n ref = part.endNode.nextSibling;\n }\n else {\n // Move the part's whole range [startNode..endNode] before ref.\n // Detach into a fragment first, then insert in one operation —\n // node identity (and any state inside) is preserved either way.\n const range = document.createDocumentFragment();\n let node = part.startNode;\n const stop = part.endNode.nextSibling;\n while (node && node !== stop) {\n const next = node.nextSibling;\n range.appendChild(node);\n node = next;\n }\n parent.insertBefore(range, ref);\n }\n }\n else {\n // New key — fresh part inserted at the current position\n const startMarker = document.createComment('');\n const endMarker = document.createComment('');\n parent.insertBefore(startMarker, ref);\n parent.insertBefore(endMarker, ref);\n part = new NodePart(startMarker, endMarker);\n newParts[i] = part;\n }\n part.commit(items[i]);\n }\n this._committedValue = newParts;\n return cleanupError;\n }\n /**\n * Commit a DOM node directly\n */\n _commitNode(node) {\n if (this._committedValue !== node) {\n const cleanupError = this._clear();\n this._insertBefore(node);\n this._committedValue = node;\n if (cleanupError)\n throw cleanupError;\n }\n }\n /**\n * Commit unsafe HTML string\n */\n _commitUnsafeHTML(value) {\n // Can't diff arbitrary HTML, but when the STRING is unchanged the DOM is\n // already correct — skip the clear+reparse so live state (typed input\n // values, focus, scroll) inside the block survives unrelated re-renders.\n const prev = this._committedValue;\n if (isUnsafeHTML(prev) && prev.html === value.html) {\n return;\n }\n const cleanupError = this._clear();\n const temp = document.createElement('template');\n temp.innerHTML = value.html;\n this._insertBefore(temp.content);\n this._committedValue = value;\n if (cleanupError)\n throw cleanupError;\n }\n _commitAsync(source) {\n // A Promise/stream object is the identity of the async operation. Once it\n // settles, unrelated parent renders must keep the committed result rather\n // than clearing it and subscribing to the same source again.\n if (source === this._asyncSource)\n return;\n this._cancelAsync(false);\n this._asyncSource = source;\n this._asyncStarted = false;\n this._asyncCompleted = false;\n this._asyncPaused = false;\n const cleanupError = this._clear();\n this._committedValue = nothing;\n this._startAsyncSource();\n if (cleanupError)\n throw cleanupError;\n }\n _startAsyncSource(forceConnected = false) {\n const source = this._asyncSource;\n if (!source || this._asyncRunning || this._asyncCompleted ||\n (!forceConnected && !this.isConnected))\n return;\n this._asyncRunning = true;\n this._asyncStarted = true;\n this._asyncPaused = false;\n const version = ++this._asyncVersion;\n if (isAsyncIterable(source)) {\n try {\n this._asyncIterator = source[Symbol.asyncIterator]();\n }\n catch (error) {\n this._asyncRunning = false;\n this._asyncCompleted = true;\n console.error('snice: async iterable template value failed:', error);\n return;\n }\n void (async () => {\n try {\n while (this._asyncIterator) {\n const result = await this._asyncIterator.next();\n if (result.done || version !== this._asyncVersion)\n break;\n this._commitAsyncValue(result.value);\n }\n }\n catch (error) {\n if (version === this._asyncVersion)\n console.error('snice: async iterable template value failed:', error);\n }\n finally {\n if (version === this._asyncVersion) {\n this._asyncIterator = null;\n this._asyncRunning = false;\n this._asyncCompleted = true;\n }\n }\n })();\n return;\n }\n Promise.resolve(source).then(value => {\n if (version !== this._asyncVersion)\n return;\n this._asyncRunning = false;\n this._asyncCompleted = true;\n try {\n this._commitAsyncValue(value);\n }\n catch (error) {\n console.error('snice: promise template value failed:', error);\n }\n }, error => {\n if (version !== this._asyncVersion)\n return;\n this._asyncRunning = false;\n this._asyncCompleted = true;\n console.error('snice: promise template value failed:', error);\n });\n }\n _commitAsyncValue(value) {\n this._committingAsyncValue = true;\n try {\n this.commit(value);\n }\n finally {\n this._committingAsyncValue = false;\n }\n }\n _cancelAsync(clearSource) {\n this._asyncVersion++;\n const iterator = this._asyncIterator;\n this._asyncIterator = null;\n this._asyncRunning = false;\n if (clearSource) {\n this._asyncSource = null;\n this._asyncStarted = false;\n this._asyncCompleted = false;\n this._asyncPaused = false;\n }\n if (iterator?.return) {\n try {\n void Promise.resolve(iterator.return()).catch(() => { });\n }\n catch {\n // Cancellation is best-effort; internal state is already detached.\n }\n }\n }\n _insertBefore(node) {\n this.endNode.parentNode?.insertBefore(node, this.endNode);\n }\n _clear() {\n const parent = this.startNode.parentNode;\n const committed = this._committedValue;\n let cleanupError;\n try {\n this._disposeCommitted(committed);\n }\n catch (error) {\n cleanupError = error;\n }\n if (!parent) {\n this._committedValue = nothing;\n return cleanupError;\n }\n let node = this.startNode.nextSibling;\n while (node && node !== this.endNode) {\n const next = node.nextSibling;\n parent.removeChild(node);\n node = next;\n }\n this._committedValue = nothing;\n return cleanupError;\n }\n _disposeCommitted(committed) {\n let lifecycleError;\n if (committed instanceof TemplateInstance) {\n try {\n committed.clear();\n }\n catch (error) {\n lifecycleError = error;\n }\n }\n else if (Array.isArray(committed)) {\n for (const item of committed) {\n if (!(item instanceof NodePart))\n continue;\n try {\n item.destroy();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n clear() {\n this._cancelAsync(true);\n const cleanupError = this._clear();\n if (cleanupError)\n throw cleanupError;\n }\n get isConnected() {\n return this.startNode.isConnected;\n }\n disconnected(preserveEventListeners = false) {\n let lifecycleError;\n if (this._committedValue instanceof TemplateInstance) {\n try {\n this._committedValue.disconnected(preserveEventListeners);\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n else if (Array.isArray(this._committedValue)) {\n for (const part of this._committedValue) {\n if (!(part instanceof NodePart))\n continue;\n try {\n part.disconnected(preserveEventListeners);\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n }\n if (this._asyncSource && this._asyncRunning) {\n this._cancelAsync(false);\n this._asyncPaused = true;\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n reconnected() {\n let lifecycleError;\n if (this._committedValue instanceof TemplateInstance) {\n try {\n this._committedValue.reconnected();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n else if (Array.isArray(this._committedValue)) {\n for (const part of this._committedValue) {\n if (!(part instanceof NodePart))\n continue;\n try {\n part.reconnected();\n }\n catch (error) {\n lifecycleError ??= error;\n }\n }\n }\n if (this._asyncSource && (!this._asyncStarted || this._asyncPaused)) {\n this._startAsyncSource(true);\n }\n if (lifecycleError)\n throw lifecycleError;\n }\n}\n/**\n * AttributePart handles regular attribute updates\n *\n * Supports multiple interpolations: class=\"a ${b} c ${d} e\"\n * Lit-HTML style: tracks each value separately for dirty checking\n */\nclass AttributePart extends Part {\n constructor(element, name, strings) {\n super();\n this.type = 'attribute';\n this._committedValue = NOT_COMMITTED;\n this.lastValues = null;\n this.lastValueIndex = 0;\n this.element = element;\n this.name = name;\n // Determine if this is interpolation or single-value binding\n if (strings && (strings.length > 2 || strings[0] !== '' || strings[1] !== '')) {\n // Interpolation case: class=\"foo ${x} bar ${y}\"\n // strings = [\"foo \", \" bar \", \"\"]\n this._committedValue = new Array(strings.length - 1).fill(NOT_COMMITTED);\n this.strings = strings;\n }\n else {\n // Single-value case: class=\"${x}\"\n this._committedValue = NOT_COMMITTED;\n }\n }\n /**\n * Commit value(s) to the attribute\n *\n * For single-value binding: commit(value)\n * For interpolation: commit(values, startIndex) where values is full template values array\n */\n commit(value, valueIndex = 0) {\n let change = false;\n let finalValue;\n // === SINGLE-VALUE BINDING ===\n if (this.strings === undefined) {\n if (value === noChange)\n return;\n change = !isPrimitive(value) ||\n (value !== this._committedValue && value !== noChange);\n if (change) {\n this._committedValue = value;\n finalValue = value;\n }\n else {\n return; // No change, skip DOM update\n }\n }\n // === INTERPOLATION BINDING ===\n else {\n const values = value;\n this.lastValues = [...values];\n this.lastValueIndex = valueIndex;\n const committedValues = this._committedValue;\n finalValue = this.strings[0];\n for (let i = 0; i < this.strings.length - 1; i++) {\n let v = values[valueIndex + i];\n // Handle noChange sentinel\n if (v === noChange) {\n v = committedValues[i];\n // First-ever commit: there is no previous value to keep — resolve\n // to empty. Without this, the NOT_COMMITTED symbol would be\n // string-concatenated below and throw.\n if (v === NOT_COMMITTED)\n v = '';\n }\n // Track if any value changed\n change = change || !isPrimitive(v) || v !== committedValues[i];\n // Handle nothing sentinel - removes entire attribute\n if (v === nothing) {\n finalValue = nothing;\n }\n else if (finalValue !== nothing) {\n finalValue = finalValue + (v ?? '') + this.strings[i + 1];\n }\n // Always record each value for future comparison\n committedValues[i] = v;\n }\n if (!change) {\n return; // No change, skip DOM update\n }\n }\n // Commit to DOM\n this._commitValue(finalValue);\n }\n _commitValue(value) {\n // Only the `nothing` sentinel removes the attribute. null/undefined\n // commit an empty attribute value, consistent with the interpolated\n // path above (which renders them as '').\n if (value === nothing) {\n this.element.removeAttribute(this.name);\n }\n else {\n this.element.setAttribute(this.name, String(value ?? ''));\n }\n }\n clear() {\n this.element.removeAttribute(this.name);\n }\n}\n/**\n * CommentPart renders binding values into an authored HTML comment's text\n * (<!-- debug: ${x} -->). Its real job is index alignment: each binding in a\n * comment consumes one value slot, so bindings after the comment stay bound\n * to their own values.\n */\nclass CommentPart extends Part {\n constructor(node, strings) {\n super();\n this.type = 'node';\n this.lastValues = null;\n this.lastValueIndex = 0;\n this.node = node;\n this.strings = strings;\n this._committedValues = new Array(strings.length - 1).fill(NOT_COMMITTED);\n }\n /**\n * Commit values into the comment text.\n * commit(values, startIndex) — like interpolated AttributePart, this part\n * consumes (strings.length - 1) values from the template values array.\n */\n commit(values, startIndex = 0) {\n const vals = values;\n this.lastValues = [...vals];\n this.lastValueIndex = startIndex;\n let change = false;\n let text = this.strings[0];\n for (let i = 0; i < this.strings.length - 1; i++) {\n let v = vals[startIndex + i];\n if (v === noChange) {\n v = this._committedValues[i];\n if (v === NOT_COMMITTED)\n v = '';\n }\n change = change || !isPrimitive(v) || v !== this._committedValues[i];\n this._committedValues[i] = v;\n text += String(v === nothing ? '' : (v ?? '')) + this.strings[i + 1];\n }\n if (change) {\n if (text.includes('--') || text.endsWith('-')) {\n throw new Error('snice: comment expressions cannot produce \"--\" or end with \"-\".');\n }\n this.node.data = text;\n }\n }\n clear() { }\n}\n/** Toggle one class without rebuilding the element's full class string. */\nclass ClassPart extends Part {\n constructor(element, name) {\n super();\n this.type = 'class';\n this.committed = NOT_COMMITTED;\n this.element = element;\n this.name = name;\n }\n commit(value) {\n if (value === noChange)\n return;\n const enabled = value !== nothing && Boolean(value);\n if (enabled === this.committed)\n return;\n this.committed = enabled;\n this.element.classList.toggle(this.name, enabled);\n }\n clear() {\n this.element.classList.remove(this.name);\n this.committed = NOT_COMMITTED;\n }\n}\n/** Set one CSS property, including custom properties, declaratively. */\nclass StylePart extends Part {\n constructor(element, name) {\n super();\n this.type = 'style';\n this.committed = NOT_COMMITTED;\n this.element = element;\n this.name = name;\n }\n commit(value) {\n if (value === noChange || Object.is(value, this.committed))\n return;\n this.committed = value;\n const style = this.element.style;\n if (value === nothing || value == null || value === false) {\n style.removeProperty(this.name);\n }\n else {\n style.setProperty(this.name, String(value));\n }\n }\n clear() {\n this.element.style.removeProperty(this.name);\n this.committed = NOT_COMMITTED;\n }\n}\nfunction validateSpreadEvents(next, label) {\n const names = new Set();\n for (const [rawName, value] of Object.entries(next)) {\n const name = rawName.startsWith('@') ? rawName.slice(1) : rawName;\n if (!name)\n throw new TypeError(`snice: ${label} contains an empty event name.`);\n if (names.has(name)) {\n throw new TypeError(`snice: ${label} contains duplicate event name \"${name}\".`);\n }\n names.add(name);\n const listenerObject = !!value && typeof value === 'object' &&\n typeof value.handleEvent === 'function';\n if (value !== nothing && value != null && value !== false &&\n typeof value !== 'function' && !listenerObject) {\n throw new TypeError(`snice: ${label} event \"${name}\" expects a function, EventListenerObject, or null.`);\n }\n }\n}\n/** Named spreads: ...props, ...attrs, and ...events. */\nclass SpreadPart extends Part {\n constructor(element, name) {\n super();\n this.type = 'spread';\n this.committed = {};\n this.listeners = new Map();\n this.consumedOnce = new Map();\n this.element = element;\n this.name = name;\n }\n commit(value) {\n if (value === noChange)\n return;\n if (value === nothing || value == null)\n value = {};\n if (typeof value !== 'object' || Array.isArray(value)) {\n throw new TypeError(`snice: ...${this.name} expects an object.`);\n }\n const next = value;\n if (this.name === 'events')\n this.commitEvents(next);\n else if (this.name === 'props' || this.name === 'properties')\n this.commitProperties(next);\n else\n this.commitAttributes(next);\n this.committed = { ...next };\n }\n commitProperties(next) {\n for (const key of Object.keys(this.committed)) {\n if (!Object.prototype.hasOwnProperty.call(next, key)) {\n markPreUpgradePropertyBinding(this.element, key);\n this.element[key] = undefined;\n }\n }\n for (const [key, value] of Object.entries(next)) {\n if (Object.is(this.committed[key], value))\n continue;\n markPreUpgradePropertyBinding(this.element, key);\n this.element[key] = value === nothing ? undefined : value;\n }\n }\n commitAttributes(next) {\n for (const key of Object.keys(this.committed)) {\n if (!Object.prototype.hasOwnProperty.call(next, key))\n this.element.removeAttribute(key);\n }\n for (const [key, value] of Object.entries(next)) {\n if (Object.is(this.committed[key], value))\n continue;\n if (value === nothing || value == null || value === false)\n this.element.removeAttribute(key);\n else\n this.element.setAttribute(key, value === true ? '' : String(value));\n }\n }\n commitEvents(next) {\n validateSpreadEvents(next, `...${this.name}`);\n for (const [name, value] of this.consumedOnce) {\n const rawName = Object.keys(next).find(key => this.eventName(key) === name);\n if (!rawName || !Object.is(next[rawName], value))\n this.consumedOnce.delete(name);\n }\n for (const [name, entry] of this.listeners) {\n const rawName = Object.keys(next).find(key => this.eventName(key) === name);\n if (rawName && Object.is(next[rawName], entry.value))\n continue;\n this.element.removeEventListener(name, entry.listener, entry.options);\n this.listeners.delete(name);\n }\n for (const [rawName, value] of Object.entries(next)) {\n const name = this.eventName(rawName);\n if (this.listeners.has(name))\n continue;\n const listenerObject = !!value && typeof value === 'object' &&\n typeof value.handleEvent === 'function';\n if (value === nothing || value == null || value === false)\n continue;\n if (this.consumedOnce.has(name) && Object.is(this.consumedOnce.get(name), value))\n continue;\n this.consumedOnce.delete(name);\n const options = listenerObject ? value : undefined;\n const listener = ((event) => {\n if (options?.once)\n this.consumedOnce.set(name, value);\n if (listenerObject)\n value.handleEvent(event);\n else\n value.call(this.resolveHost(), event);\n });\n this.element.addEventListener(name, listener, options);\n this.listeners.set(name, { value, listener, options });\n }\n }\n eventName(name) {\n return name.startsWith('@') ? name.slice(1) : name;\n }\n resolveHost() {\n return findRenderHost(this.element) || this.element;\n }\n clear() {\n if (this.name === 'events') {\n for (const [name, entry] of this.listeners) {\n this.element.removeEventListener(name, entry.listener, entry.options);\n }\n this.listeners.clear();\n this.consumedOnce.clear();\n }\n else if (this.name !== 'props' && this.name !== 'properties') {\n for (const key of Object.keys(this.committed))\n this.element.removeAttribute(key);\n }\n // A property spread is being destroyed with the element that owns it.\n // Resetting native/custom properties here is unnecessary and can throw for\n // setters that reject undefined (textarea.value is a common example).\n // Stale keys are still removed during an ordinary live spread update.\n this.committed = {};\n }\n disconnected(preserveEventListeners = false) {\n if (this.name === 'events' && !preserveEventListeners)\n this.detachListeners();\n }\n reconnected() {\n if (this.name === 'events' && this.listeners.size === 0)\n this.commitEvents(this.committed);\n }\n detachListeners() {\n for (const [name, entry] of this.listeners) {\n this.element.removeEventListener(name, entry.listener, entry.options);\n }\n this.listeners.clear();\n }\n}\n/**\n * PropertyPart handles property bindings (.property=${value})\n */\nclass PropertyPart extends Part {\n constructor(element, name) {\n super();\n this.type = 'property';\n this._committedValue = NOT_COMMITTED;\n this.element = element;\n this.name = name;\n }\n commit(value) {\n if (value === noChange)\n return;\n // live(): compare against the element's actual DOM property, so state\n // the user changed (typed text, toggled checkbox) is reset even when the\n // bound value itself is unchanged.\n if (isLive(value)) {\n value = value.value;\n if (value === noChange)\n return;\n const domValue = this.element[this.name];\n if (value === domValue) {\n this._committedValue = value;\n return;\n }\n }\n else {\n // Dirty check - skip if same value\n if (value === this._committedValue)\n return;\n }\n this._committedValue = value;\n markPreUpgradePropertyBinding(this.element, this.name);\n this.element[this.name] = value === nothing ? undefined : value;\n }\n clear() {\n // This part is being destroyed with its owning template. The element is\n // about to leave the tree, so writing `undefined` is both unnecessary and\n // unsafe for native setters such as HTMLTextAreaElement.value.\n this._committedValue = NOT_COMMITTED;\n }\n}\n/**\n * ControllerPart handles bare controller=${...} bindings.\n *\n * Accepts a controller class decorated with @controller (attached directly,\n * no registry lookup) or a registry name string (delegated to the attribute\n * channel with the exact semantics of a static controller=\"name\"). While a\n * class is bound it owns the element: the attribute/MutationObserver channel\n * is inert until the class is unbound.\n *\n * Renders commit while the tree is detached and connect afterwards, so\n * attachment happens on reconnected()/connected commits; every hook is\n * idempotent because the update loop reconciles connection state on each pass.\n */\nclass ControllerPart extends Part {\n constructor(element) {\n super();\n this.type = 'controller';\n this._committedValue = NOT_COMMITTED;\n this.element = element;\n }\n commit(value) {\n if (value === noChange)\n return;\n // Normalize every \"no controller\" shape to null\n const next = (value == null || value === false || value === '' || value === nothing)\n ? null\n : value;\n const first = this._committedValue === NOT_COMMITTED;\n const previous = first ? null : this._committedValue;\n if (!first && next === previous)\n return;\n this._committedValue = next;\n const el = this.element;\n // Leaving a class binding: release the element back to the attribute channel.\n if (typeof previous === 'function' && typeof next !== 'function') {\n if (el[PENDING_CONTROLLER_BINDING] !== undefined) {\n delete el[PENDING_CONTROLLER_BINDING];\n }\n else if (el[IS_ELEMENT_CLASS]) {\n el.controller = null;\n }\n else {\n this._detach();\n }\n }\n if (typeof next === 'function') {\n // Class binding takes over — drop any attribute so the string channel\n // cannot fight it.\n if (this.element.hasAttribute('controller'))\n this.element.removeAttribute('controller');\n if (this.isConnected) {\n this._apply(next);\n }\n else if (this.element.localName.includes('-') && !el[IS_ELEMENT_CLASS]) {\n // Park on not-yet-upgraded custom elements even while detached — the\n // element picks the class up in connectedCallback on upgrade.\n el[PENDING_CONTROLLER_BINDING] = next;\n }\n // Detached native/upgraded elements attach in reconnected().\n }\n else if (typeof next === 'string') {\n this.element.setAttribute('controller', next);\n }\n else if (typeof previous === 'string') {\n this.element.removeAttribute('controller');\n }\n }\n /** Drive the element toward the committed class. Idempotent. */\n _apply(controllerClass) {\n const el = this.element;\n if (el[IS_ELEMENT_CLASS]) {\n if (el.controller !== controllerClass) {\n // Setter handles detach of the old controller and attach of the new.\n el.controller = controllerClass;\n }\n else {\n // Same value: the setter would no-op, but the element may have\n // self-detached on disconnect. attachController dedupes when the\n // controller is still attached.\n this._attach(controllerClass);\n }\n return;\n }\n if (this.element.localName.includes('-')) {\n // Custom element that hasn't upgraded yet (defined later, or cloned\n // into a detached fragment). Park the class — connectedCallback picks\n // it up on upgrade. Assigning the property now would shadow the future\n // prototype accessor with an own expando property.\n el[PENDING_CONTROLLER_BINDING] = controllerClass;\n return;\n }\n // Native element — attach directly. Mirror the observer path's ready shim.\n if (!el.ready)\n el.ready = Promise.resolve();\n this._attach(controllerClass);\n }\n _attach(controllerClass) {\n attachController(this.element, controllerClass).catch((error) => {\n if (error?.name === 'ControllerAttachAborted')\n return;\n console.error(`Failed to attach controller \"${controllerClass?.name || controllerClass}\":`, error);\n });\n }\n _detach() {\n detachController(this.element).catch((error) => {\n console.error('Failed to detach controller:', error);\n });\n }\n disconnected(_preserveEventListeners = false) {\n const committed = this._committedValue;\n if (typeof committed !== 'function')\n return;\n const el = this.element;\n if (el[PENDING_CONTROLLER_BINDING] !== undefined)\n return; // never attached\n if (el[IS_ELEMENT_CLASS])\n return; // snice elements detach themselves on disconnect\n this._detach();\n }\n reconnected() {\n const committed = this._committedValue;\n if (typeof committed !== 'function')\n return;\n this._apply(committed);\n }\n clear() {\n const el = this.element;\n if (el[PENDING_CONTROLLER_BINDING] !== undefined)\n delete el[PENDING_CONTROLLER_BINDING];\n const committed = this._committedValue;\n this._committedValue = NOT_COMMITTED;\n if (typeof committed !== 'function')\n return;\n if (el[IS_ELEMENT_CLASS])\n return; // the element's own teardown detaches\n this._detach();\n }\n}\n/**\n * BooleanAttributePart handles boolean attributes (?attribute=${value})\n */\nclass BooleanAttributePart extends Part {\n constructor(element, name) {\n super();\n this.type = 'boolean-attribute';\n this._committedValue = NOT_COMMITTED;\n this.element = element;\n this.name = name;\n }\n commit(value) {\n if (value === noChange)\n return;\n // Coerce to boolean\n const boolValue = !!value && value !== nothing;\n // Dirty check - skip if same boolean value\n if (boolValue === this._committedValue)\n return;\n this._committedValue = boolValue;\n if (boolValue) {\n this.element.setAttribute(this.name, '');\n }\n else {\n this.element.removeAttribute(this.name);\n }\n }\n clear() {\n this.element.removeAttribute(this.name);\n this._committedValue = NOT_COMMITTED;\n }\n}\n/**\n * EventPart handles event listener bindings with keyboard shortcut support\n */\nclass EventPart extends Part {\n constructor(element, eventName) {\n super();\n this.type = 'event';\n this.listener = null;\n this.listenerOptions = undefined;\n this.value = undefined;\n this.keyFilter = null;\n this.host = null; // Cache host element\n this.modifiers = new Set();\n this.once = false;\n this.onceConsumed = false;\n this.element = element;\n const [eventSpec, ...modifierSpecs] = eventName.split('|');\n const aliases = {\n preventdefault: 'prevent',\n stoppropagation: 'stop',\n stopimmediatepropagation: 'immediate'\n };\n const allowed = new Set(['prevent', 'stop', 'immediate', 'once', 'capture', 'passive', 'self']);\n for (const raw of modifierSpecs) {\n const normalized = aliases[raw.toLowerCase()] || raw.toLowerCase();\n if (!allowed.has(normalized)) {\n throw new Error(`snice: unknown event modifier \"${raw}\" in @${eventName}. ` +\n 'Supported modifiers: prevent, stop, immediate, once, capture, passive, self.');\n }\n this.modifiers.add(normalized);\n }\n if (this.modifiers.has('passive') && this.modifiers.has('prevent')) {\n throw new Error(`snice: @${eventName} cannot combine passive and prevent.`);\n }\n // Parse keyboard shortcuts:\n // Supports both dot notation (@keydown.enter) and colon notation (@keydown:Enter) to match @on decorator\n // Only parse colons for keyboard events, not custom events\n const isKeyboardEvent = ['keydown', 'keyup', 'keypress'].includes(eventSpec.split('.')[0].split(':')[0]);\n // Only keyboard events split on `.`/`:` into a key filter — a custom event\n // name may legitimately contain a dot (e.g. `app.ready`) and must be kept whole.\n const dotIndex = isKeyboardEvent ? eventSpec.indexOf('.') : -1;\n const colonIndex = isKeyboardEvent ? eventSpec.indexOf(':') : -1;\n // Use whichever delimiter comes first (dot or colon)\n const delimiterIndex = dotIndex > 0 && colonIndex > 0\n ? Math.min(dotIndex, colonIndex)\n : Math.max(dotIndex, colonIndex);\n if (delimiterIndex > 0) {\n const baseEvent = eventSpec.substring(0, delimiterIndex);\n const keySpec = eventSpec.substring(delimiterIndex + 1);\n this.eventName = baseEvent;\n this.keyFilter = parseKeyboardFilter(keySpec);\n }\n else {\n this.eventName = eventSpec;\n warnIfModifierMisuse(eventSpec);\n }\n }\n commit(value) {\n // Handle noChange sentinel\n if (value === noChange)\n return;\n // Handle nothing sentinel - remove listener\n if (value === nothing) {\n value = null;\n }\n const isListenerObject = !!value &&\n typeof value === 'object' &&\n typeof value.handleEvent === 'function';\n if (value !== null && value !== undefined && value !== false &&\n typeof value !== 'function' && !isListenerObject) {\n throw new TypeError(`snice: @${this.eventName} expects a function, EventListenerObject, or null.`);\n }\n if (isListenerObject && this.modifiers.has('prevent') && !!value.passive) {\n throw new Error(`snice: @${this.eventName} cannot combine a passive listener object with prevent.`);\n }\n // Skip if same value (but null/undefined always triggers update for cleanup)\n if (value === this.value && value !== null && value !== undefined)\n return;\n // Remove old listener (with the same capture option it was added with)\n if (this.listener) {\n this.element.removeEventListener(this.eventName, this.listener, this.listenerOptions);\n this.listener = null;\n this.listenerOptions = undefined;\n }\n // Add new listener\n if (value === null || value === undefined || value === false) {\n this.value = value;\n this.onceConsumed = false;\n return;\n }\n this.onceConsumed = false;\n try {\n this.attachListener(value, isListenerObject);\n this.value = value;\n }\n catch (error) {\n this.value = undefined;\n throw error;\n }\n }\n attachListener(value, isListenerObject) {\n // Accept plain functions AND EventListenerObject ({ handleEvent }). For\n // listener objects, the object itself doubles as the options bag.\n const keyFilter = this.keyFilter;\n const listener = ((event) => {\n if (this.modifiers.has('self') && event.target !== this.element)\n return;\n if (keyFilter && !matchesKeyboardFilter(event, keyFilter))\n return;\n if (this.once) {\n this.onceConsumed = true;\n this.element.removeEventListener(this.eventName, listener, listenerOptions);\n this.listener = null;\n this.listenerOptions = undefined;\n }\n if (this.modifiers.has('prevent'))\n event.preventDefault();\n if (this.modifiers.has('immediate'))\n event.stopImmediatePropagation();\n else if (this.modifiers.has('stop'))\n event.stopPropagation();\n if (isListenerObject) {\n // DOM spec: `this` inside handleEvent is the listener object itself\n value.handleEvent(event);\n return;\n }\n // Resolve the host (the custom element owning the shadow root) at dispatch\n // time, not bind time: a binding inside an initially-hidden <if>/<case>\n // branch commits while off-DOM, where getRootNode() has no host — caching\n // that null permanently would call the handler with `this = null` once the\n // branch is shown. By the time an event fires, the element is in the DOM.\n if (!this.host) {\n this.host = findRenderHost(this.element);\n }\n value.call(this.host || this.element, event);\n });\n const valueOptions = isListenerObject ? value : {};\n this.once = this.modifiers.has('once') || !!valueOptions.once;\n const listenerOptions = {\n capture: this.modifiers.has('capture') || valueOptions.capture,\n passive: this.modifiers.has('passive') || valueOptions.passive,\n signal: valueOptions.signal\n };\n this.element.addEventListener(this.eventName, listener, listenerOptions);\n this.listener = listener;\n this.listenerOptions = listenerOptions;\n }\n clear() {\n this.detachListener();\n this.value = undefined;\n this.host = null;\n this.onceConsumed = false;\n }\n detachListener() {\n if (this.listener) {\n this.element.removeEventListener(this.eventName, this.listener, this.listenerOptions);\n this.listener = null;\n this.listenerOptions = undefined;\n }\n }\n disconnected(preserveEventListeners = false) {\n if (!preserveEventListeners)\n this.detachListener();\n this.host = null;\n }\n reconnected() {\n if (!this.listener && !this.onceConsumed && this.value != null && this.value !== false) {\n const isListenerObject = typeof this.value === 'object';\n this.attachListener(this.value, isListenerObject);\n }\n }\n}\n/**\n * Parse keyboard shortcut specification\n * Examples:\n * \"enter\" -> { key: \"Enter\" }\n * \"ctrl+s\" -> { key: \"s\", ctrl: true }\n * \"ctrl+shift+s\" -> { key: \"s\", ctrl: true, shift: true }\n * \"~enter\" -> { key: \"Enter\", anyModifiers: true }\n */\n// once/preventDefault/stopPropagation/capture/passive are @on() OPTIONS, not\n// template modifiers. A dotted non-keyboard event whose suffix is one of these\n// is almost certainly a mistake (e.g. `@click.once`) — it binds a listener for\n// an event type the DOM never dispatches. Warn instead of failing silently. A\n// legitimate custom event name like `app.ready` won't match and stays quiet.\nconst MODIFIER_WORDS = new Set([\n 'once', 'prevent', 'preventdefault', 'stop', 'stoppropagation', 'capture', 'passive',\n]);\nfunction warnIfModifierMisuse(eventName) {\n const dot = eventName.lastIndexOf('.');\n if (dot < 0)\n return;\n const suffix = eventName.slice(dot + 1).toLowerCase();\n if (!MODIFIER_WORDS.has(suffix))\n return;\n console.warn(`snice: \"@${eventName}\" is not a valid modifier — once/preventDefault/` +\n `stopPropagation/capture are @on() options, not template modifiers. ` +\n `This registers a listener for event \"${eventName}\", which never fires.`);\n}\nfunction parseKeyboardFilter(spec) {\n // Handle ~ prefix for matching regardless of modifiers\n const anyModifiers = spec.startsWith('~');\n if (anyModifiers) {\n spec = spec.substring(1);\n }\n const parts = spec.split('+');\n const filter = {\n key: '',\n anyModifiers\n };\n for (const part of parts) {\n const lower = part.toLowerCase();\n if (lower === 'ctrl' || lower === 'control') {\n filter.ctrl = true;\n }\n else if (lower === 'alt') {\n filter.alt = true;\n }\n else if (lower === 'shift') {\n filter.shift = true;\n }\n else if (lower === 'meta' || lower === 'cmd' || lower === 'command') {\n filter.meta = true;\n }\n else {\n // This is the key itself - normalize common keys\n filter.key = normalizeKey(part);\n }\n }\n return filter;\n}\n/**\n * Normalize key names to match KeyboardEvent.key\n */\nfunction normalizeKey(key) {\n const keyMap = {\n 'esc': 'Escape',\n 'escape': 'Escape',\n 'enter': 'Enter',\n 'return': 'Enter',\n 'space': ' ',\n 'spacebar': ' ',\n 'up': 'ArrowUp',\n 'down': 'ArrowDown',\n 'left': 'ArrowLeft',\n 'right': 'ArrowRight',\n 'arrowup': 'ArrowUp',\n 'arrowdown': 'ArrowDown',\n 'arrowleft': 'ArrowLeft',\n 'arrowright': 'ArrowRight',\n 'delete': 'Delete',\n 'del': 'Delete',\n 'backspace': 'Backspace',\n 'tab': 'Tab',\n 'home': 'Home',\n 'end': 'End',\n 'pageup': 'PageUp',\n 'pagedown': 'PageDown'\n };\n const lower = key.toLowerCase();\n return keyMap[lower] || key;\n}\n/**\n * Check if keyboard event matches the filter\n */\nfunction matchesKeyboardFilter(event, filter) {\n // Check key match\n if (event.key !== filter.key) {\n return false;\n }\n // If anyModifiers is true, we don't care about modifiers\n if (filter.anyModifiers) {\n return true;\n }\n // Check modifiers - by default, exact match\n // If filter specifies ctrl: true, event must have ctrlKey\n // If filter doesn't specify ctrl, event must NOT have ctrlKey\n const ctrlMatch = filter.ctrl ? event.ctrlKey : !event.ctrlKey;\n const altMatch = filter.alt ? event.altKey : !event.altKey;\n const shiftMatch = filter.shift ? event.shiftKey : !event.shiftKey;\n const metaMatch = filter.meta ? event.metaKey : !event.metaKey;\n return ctrlMatch && altMatch && shiftMatch && metaMatch;\n}\n/**\n * ConditionalIfPart handles <if> conditional rendering\n * Removes/inserts DOM nodes based on condition\n */\n// Sentinel value to distinguish \"not yet set\" from undefined\nconst NOT_SET = Symbol('not-set');\nclass ConditionalIfPart extends Part {\n constructor(ifElement) {\n super();\n this.type = 'node';\n this.conditions = [NOT_SET];\n this.branches = [];\n this.defaultBranch = -1;\n this.currentBranch = -1;\n const parent = ifElement.parentNode;\n // Create comment boundary markers\n this.startNode = document.createComment('if');\n this.endNode = document.createComment('/if');\n // Insert markers where <if> is\n parent.insertBefore(this.startNode, ifElement);\n parent.insertBefore(this.endNode, ifElement.nextSibling);\n const primary = document.createDocumentFragment();\n this.branches.push(primary);\n let sawAlternative = false;\n let lastBranch = primary;\n for (const child of Array.from(ifElement.childNodes)) {\n const tag = child.nodeType === Node.ELEMENT_NODE\n ? child.tagName.toLowerCase()\n : '';\n if (tag === 'else-if' || tag === 'else') {\n sawAlternative = true;\n const wrapper = child;\n const fragment = document.createDocumentFragment();\n while (wrapper.firstChild)\n fragment.appendChild(wrapper.firstChild);\n const index = this.branches.push(fragment) - 1;\n lastBranch = fragment;\n if (tag === 'else-if') {\n if (this.defaultBranch !== -1) {\n throw new Error('snice: <else> must be the final branch inside <if>.');\n }\n this.conditions[index] = NOT_SET;\n conditionalElseIfOwners.set(wrapper, { coordinator: this, index });\n }\n else {\n if (this.defaultBranch !== -1) {\n throw new Error('snice: <if> may contain only one <else> branch.');\n }\n this.defaultBranch = index;\n }\n wrapper.remove();\n continue;\n }\n if (!sawAlternative) {\n primary.appendChild(child);\n }\n else if (child.nodeType === Node.TEXT_NODE && !child.textContent?.trim()) {\n child.remove();\n }\n else {\n lastBranch.appendChild(child);\n }\n }\n parent.removeChild(ifElement);\n }\n commit(value) {\n if (value !== noChange)\n this.conditions[0] = value;\n }\n setAlternative(index, value) {\n if (value !== noChange)\n this.conditions[index] = value;\n }\n flush() {\n let next = -1;\n for (let i = 0; i < this.conditions.length; i++) {\n if (this.conditions[i] !== NOT_SET &&\n this.conditions[i] !== nothing &&\n Boolean(this.conditions[i])) {\n next = i;\n break;\n }\n }\n if (next === -1)\n next = this.defaultBranch;\n if (next === this.currentBranch)\n return;\n this.collectCurrent();\n this.currentBranch = next;\n if (next !== -1 && this.branches[next].hasChildNodes()) {\n this.startNode.parentNode?.insertBefore(this.branches[next], this.endNode);\n }\n }\n collectCurrent() {\n if (this.currentBranch === -1)\n return;\n const fragment = this.branches[this.currentBranch];\n let node = this.startNode.nextSibling;\n while (node && node !== this.endNode) {\n const next = node.nextSibling;\n fragment.appendChild(node);\n node = next;\n }\n }\n clear() {\n this.collectCurrent();\n this.currentBranch = -1;\n }\n get isConnected() {\n return this.startNode.isConnected;\n }\n}\nconst conditionalElseIfOwners = new WeakMap();\nclass ConditionalElseIfPart extends Part {\n constructor(element) {\n super();\n this.type = 'node';\n const owner = conditionalElseIfOwners.get(element);\n if (!owner)\n throw new Error('snice: <else-if> must be a direct child of <if>.');\n this.coordinator = owner.coordinator;\n this.index = owner.index;\n }\n commit(value) {\n this.coordinator.setAlternative(this.index, value);\n }\n clear() { }\n get isConnected() {\n return this.coordinator.isConnected;\n }\n}\n/**\n * ConditionalCasePart handles <case>/<when>/<default> conditional rendering\n * Removes/inserts matching branch based on value\n */\nclass ConditionalCasePart extends Part {\n constructor(caseElement, dynamicWhenElements) {\n super();\n this.type = 'node';\n this.value = NOT_SET;\n this.branches = [];\n this.defaultBranch = -1;\n this.currentBranch = -1;\n const parent = caseElement.parentNode;\n // Create comment boundary markers\n this.startNode = document.createComment('case');\n this.endNode = document.createComment('/case');\n // Insert markers where <case> is\n parent.insertBefore(this.startNode, caseElement);\n parent.insertBefore(this.endNode, caseElement.nextSibling);\n // Extract branches from <when> and <default> children\n for (const child of Array.from(caseElement.children)) {\n const childTag = child.tagName.toLowerCase();\n if (childTag === 'when') {\n const fragment = document.createDocumentFragment();\n while (child.firstChild) {\n fragment.appendChild(child.firstChild);\n }\n const dynamic = dynamicWhenElements.has(child);\n const index = this.branches.push({\n fragment,\n dynamic,\n expected: dynamic ? NOT_SET : (child.getAttribute('value') ?? '')\n }) - 1;\n if (dynamic)\n conditionalWhenOwners.set(child, { coordinator: this, index });\n }\n else if (childTag === 'default') {\n if (this.defaultBranch !== -1) {\n throw new Error('snice: <case> may contain only one <default> branch.');\n }\n const fragment = document.createDocumentFragment();\n while (child.firstChild) {\n fragment.appendChild(child.firstChild);\n }\n this.defaultBranch = this.branches.push({\n fragment,\n dynamic: false,\n expected: NOT_SET\n }) - 1;\n }\n }\n // Remove the <case> element from DOM\n parent.removeChild(caseElement);\n }\n commit(value) {\n if (value !== noChange)\n this.value = value;\n }\n setExpected(index, value) {\n if (value !== noChange)\n this.branches[index].expected = value;\n }\n flush() {\n let next = this.branches.findIndex((branch, index) => {\n if (index === this.defaultBranch)\n return false;\n return branch.dynamic\n ? Object.is(this.value, branch.expected)\n : String(this.value) === branch.expected;\n });\n if (next === -1)\n next = this.defaultBranch;\n if (next === this.currentBranch)\n return;\n this.collectCurrent();\n this.currentBranch = next;\n if (next !== -1 && this.branches[next].fragment.hasChildNodes()) {\n this.startNode.parentNode?.insertBefore(this.branches[next].fragment, this.endNode);\n }\n }\n collectCurrent() {\n if (this.currentBranch === -1)\n return;\n const fragment = this.branches[this.currentBranch].fragment;\n let node = this.startNode.nextSibling;\n while (node && node !== this.endNode) {\n const next = node.nextSibling;\n fragment.appendChild(node);\n node = next;\n }\n }\n clear() {\n this.collectCurrent();\n this.currentBranch = -1;\n }\n get isConnected() {\n return this.startNode.isConnected;\n }\n}\nconst conditionalWhenOwners = new WeakMap();\nclass ConditionalWhenPart extends Part {\n constructor(element) {\n super();\n this.type = 'node';\n const owner = conditionalWhenOwners.get(element);\n if (!owner)\n throw new Error('snice: dynamic <when> must be a direct child of <case>.');\n this.coordinator = owner.coordinator;\n this.index = owner.index;\n }\n commit(value) {\n this.coordinator.setExpected(this.index, value);\n }\n clear() { }\n get isConnected() {\n return this.coordinator.isConnected;\n }\n}\n\n/**\n * @on decorator for listening to events\n * Use in elements or controllers to listen to DOM events or custom events\n */\nconst ON_HANDLERS = getSymbol('on-handlers');\n/**\n * @on decorator for listening to events\n *\n * Works in both elements and controllers with full event delegation support.\n *\n * @param eventName - Event name(s) to listen for\n * @param selector - Optional CSS selector for event delegation\n * @param options - Event listener options including debounce/throttle\n *\n * @example\n * ```typescript\n * // In elements\n * @element('my-button')\n * class MyButton extends HTMLElement {\n * @on('click', 'button')\n * handleClick(e: MouseEvent) {\n * console.log('Button clicked!', e);\n * }\n *\n * @on('input', 'input', { debounce: 300 })\n * handleInput(e: Event) {\n * console.log('Input changed:', (e.target as HTMLInputElement).value);\n * }\n * }\n *\n * // In controllers\n * @controller('my-controller')\n * class MyController {\n * element!: HTMLElement;\n *\n * @on('count-changed')\n * handleCountChanged(e: CustomEvent) {\n * console.log('Count changed to:', e.detail.count);\n * }\n *\n * @on('click', '.item', { throttle: 100 })\n * handleItemClick(e: MouseEvent) {\n * console.log('Item clicked');\n * }\n * }\n * ```\n */\nfunction on(eventName, selectorOrOptions, options) {\n // Parse arguments to support multiple call signatures\n let selector = null;\n let opts = {};\n if (typeof selectorOrOptions === 'string') {\n selector = selectorOrOptions;\n opts = options || {};\n }\n else if (selectorOrOptions && typeof selectorOrOptions === 'object') {\n opts = selectorOrOptions;\n }\n else if (selectorOrOptions === null && options) {\n opts = options;\n }\n return function (originalMethod, context) {\n const methodName = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // Dedup by registration identity (method + events + selector), NOT by\n // method reference alone — stacked @on decorators share one method and\n // must each register. Use hasOwnProperty so subclasses get their OWN\n // Set instead of inheriting — otherwise parent and child share state\n // and child registrations pollute parent (and vice versa) via the\n // prototype chain.\n const eventNames = Array.isArray(eventName) ? eventName : [eventName];\n const registrationKey = `${methodName}::${eventNames.join(',')}::${selector ?? ''}`;\n if (!Object.prototype.hasOwnProperty.call(constructor, ON_METHODS)) {\n constructor[ON_METHODS] = new Set();\n }\n if (constructor[ON_METHODS].has(registrationKey))\n return;\n constructor[ON_METHODS].add(registrationKey);\n if (!Object.prototype.hasOwnProperty.call(constructor, ON_HANDLERS)) {\n // Seed with parent's handlers (if any) so inherited @on still fires.\n const inherited = constructor[ON_HANDLERS];\n constructor[ON_HANDLERS] = inherited ? [...inherited] : [];\n }\n for (const event of eventNames) {\n constructor[ON_HANDLERS].push({\n eventName: event,\n selector,\n methodName,\n method: originalMethod,\n options: opts\n });\n }\n });\n return originalMethod;\n };\n}\n// Note: on.ts uses leading-edge-only throttle (no trailing call).\n// createThrottled from utils has leading+trailing, so we keep a local leading-only variant.\nfunction throttle$1(fn, delay) {\n let lastCall = 0;\n return function (...args) {\n const now = Date.now();\n if (now - lastCall >= delay) {\n lastCall = now;\n fn.apply(this, args);\n }\n };\n}\n/**\n * Events that don't bubble - these require capture phase for delegation\n */\nconst NON_BUBBLING_EVENTS = new Set([\n 'scroll',\n 'focus',\n 'blur',\n 'load',\n 'unload',\n 'error',\n 'resize',\n 'abort',\n 'mouseenter',\n 'mouseleave',\n 'pointerenter',\n 'pointerleave',\n]);\n/**\n * Setup event listeners for an element or controller instance\n * Called automatically during element connection or controller attachment\n */\nfunction setupEventHandlers(instance, targetElement) {\n const handlers = instance.constructor[ON_HANDLERS];\n if (!handlers || !Array.isArray(handlers) || handlers.length === 0) {\n return;\n }\n // Initialize cleanup object if needed\n if (!instance[CLEANUP]) {\n instance[CLEANUP] = { events: [], channels: [], observers: [] };\n }\n else if (!instance[CLEANUP].events) {\n instance[CLEANUP].events = [];\n }\n else if (instance[CLEANUP].events.length > 0) {\n // Events already set up - clean them up first to avoid duplicates\n cleanupEventHandlers(instance);\n }\n for (const handler of handlers) {\n // Get current method from instance (preserves decorator stacking)\n const currentMethod = instance[handler.methodName];\n let boundMethod = currentMethod ? currentMethod.bind(instance) : handler.method.bind(instance);\n const handlerOptions = handler.options || {};\n // Parse event name for key modifiers\n // Supports both dot notation (@keydown.enter) and colon notation (@keydown:Enter)\n // Only parse colons for keyboard events, not custom events\n const isKeyboardEvent = ['keydown', 'keyup', 'keypress'].includes(handler.eventName.split('.')[0].split(':')[0]);\n // Only keyboard events split on `.`/`:` into a key filter — a custom event\n // name may legitimately contain a dot (e.g. `app.ready`) and must be kept whole.\n const dotIndex = isKeyboardEvent ? handler.eventName.indexOf('.') : -1;\n const colonIndex = isKeyboardEvent ? handler.eventName.indexOf(':') : -1;\n const delimiterIndex = dotIndex > 0 && colonIndex > 0\n ? Math.min(dotIndex, colonIndex)\n : Math.max(dotIndex, colonIndex);\n const baseEventName = delimiterIndex > 0\n ? handler.eventName.substring(0, delimiterIndex)\n : handler.eventName;\n const keyModifier = delimiterIndex > 0\n ? handler.eventName.substring(delimiterIndex + 1)\n : null;\n if (delimiterIndex <= 0)\n warnIfModifierMisuse(handler.eventName);\n // Apply debounce (takes precedence over throttle)\n if (handlerOptions.debounce && handlerOptions.debounce > 0) {\n boundMethod = createDebounced(boundMethod, handlerOptions.debounce);\n }\n else if (handlerOptions.throttle && handlerOptions.throttle > 0) {\n boundMethod = throttle$1(boundMethod, handlerOptions.throttle);\n }\n // Create event handler with key modifier support\n // Uses shared keyboard filter implementation from parts.ts\n let keyFilter = null;\n if (keyModifier && ['keydown', 'keyup', 'keypress'].includes(baseEventName)) {\n keyFilter = parseKeyboardFilter(keyModifier);\n }\n const createKeyModifierHandler = (method) => {\n if (!keyFilter) {\n return method;\n }\n return (event) => {\n const keyEvent = event;\n if (matchesKeyboardFilter(keyEvent, keyFilter)) {\n method(event);\n }\n };\n };\n // Apply key modifier wrapper\n const keyModifierMethod = createKeyModifierHandler(boundMethod);\n // Resolve scope: explicit `scope` option redirects the listener target\n // to document / ancestor / arbitrary EventTarget. Default = host element.\n const hasExplicitScope = handlerOptions.scope !== undefined;\n let scopedTarget = null;\n if (hasExplicitScope) {\n scopedTarget = resolveScope(targetElement, handlerOptions.scope);\n if (!scopedTarget) {\n // Dev warning — listener silently dropped when scope cannot resolve.\n // Skip attachment so we don't bind to the wrong target.\n console.warn(`[snice/@on] scope did not resolve for \"${handler.eventName}\" on ${handler.methodName} — listener skipped.`);\n continue;\n }\n }\n // Main event handler with error handling and event delegation\n if (handler.selector) {\n // Delegated event handling.\n // - Default eventRoot: shadow root if present, else host element.\n // - With explicit scope: attach to the scoped target instead.\n const eventRoot = hasExplicitScope\n ? scopedTarget\n : (targetElement.shadowRoot || targetElement);\n const delegatedHandler = (event) => {\n const target = event.target;\n const matchingElement = (target.matches && target.matches(handler.selector) && target) ||\n (target.closest && target.closest(handler.selector)) ||\n null;\n if (!matchingElement)\n return;\n if (handlerOptions.preventDefault)\n event.preventDefault();\n if (handlerOptions.stopPropagation) {\n event.stopPropagation();\n event.stopImmediatePropagation();\n }\n try {\n keyModifierMethod(event);\n }\n catch (error) {\n console.error(`Error in event handler ${handler.methodName}:`, error);\n }\n };\n // Auto-enable capture for non-bubbling events when using delegation\n const needsCapture = NON_BUBBLING_EVENTS.has(baseEventName);\n const useCapture = handlerOptions.capture !== undefined\n ? handlerOptions.capture\n : needsCapture;\n const listenerOptions = {\n capture: useCapture,\n once: handlerOptions.once || false,\n passive: handlerOptions.passive || false,\n };\n eventRoot.addEventListener(baseEventName, delegatedHandler, listenerOptions);\n instance[CLEANUP].events.push({\n target: eventRoot,\n eventName: baseEventName,\n handler: delegatedHandler,\n options: listenerOptions,\n });\n }\n else {\n // Direct event handling.\n // - Default: shadow root + host element (so events inside shadow and on\n // the host itself both fire). A per-handler Symbol dedupes.\n // - With explicit scope: attach to the scoped target ONLY (no duplication).\n const shadowRoot = hasExplicitScope ? null : targetElement.shadowRoot;\n // Per-handler private Symbol so dedup is scoped to THIS handler's two\n // listeners (shadowRoot + host). Using Symbol.for() with the method name\n // would collide across components that share a method name (e.g. a parent\n // and nested child both defining `handleClick`), causing the parent's\n // handler to be silently swallowed when events bubble up through a\n // shadow boundary.\n const handledSymbol = Symbol();\n const wrappedMethod = (event) => {\n if (event[handledSymbol])\n return;\n event[handledSymbol] = true;\n if (handlerOptions.preventDefault)\n event.preventDefault();\n if (handlerOptions.stopPropagation)\n event.stopPropagation();\n try {\n keyModifierMethod(event);\n }\n catch (error) {\n console.error(`Error in event handler ${handler.methodName}:`, error);\n }\n };\n const listenerOptions = {\n capture: handlerOptions.capture || false,\n once: handlerOptions.once || false,\n passive: handlerOptions.passive || false,\n };\n if (hasExplicitScope) {\n scopedTarget.addEventListener(baseEventName, wrappedMethod, listenerOptions);\n instance[CLEANUP].events.push({\n target: scopedTarget,\n eventName: baseEventName,\n handler: wrappedMethod,\n options: listenerOptions,\n });\n continue;\n }\n if (shadowRoot) {\n // Listen on shadow root for events inside shadow DOM\n shadowRoot.addEventListener(baseEventName, wrappedMethod, listenerOptions);\n instance[CLEANUP].events.push({\n target: shadowRoot,\n eventName: baseEventName,\n handler: wrappedMethod,\n options: listenerOptions,\n });\n }\n // Also listen on host element (for clicks on host itself or when no shadow root)\n targetElement.addEventListener(baseEventName, wrappedMethod, listenerOptions);\n instance[CLEANUP].events.push({\n target: targetElement,\n eventName: baseEventName,\n handler: wrappedMethod,\n options: listenerOptions,\n });\n }\n }\n}\n/**\n * Cleanup event listeners for a controller instance\n * Called automatically by the controller system during detach\n */\nfunction cleanupEventHandlers(instance) {\n if (!instance[CLEANUP]?.events)\n return;\n for (const { target, eventName, handler, options } of instance[CLEANUP].events) {\n target.removeEventListener(eventName, handler, options);\n }\n instance[CLEANUP].events = [];\n}\n\n// Controller-scoped cleanup registry\nclass ControllerScope {\n constructor() {\n this.cleanupFns = new Map();\n this.pendingOperations = new Set();\n }\n register(key, cleanup) {\n this.cleanupFns.set(key, cleanup);\n }\n unregister(key) {\n this.cleanupFns.delete(key);\n }\n async cleanup() {\n // Wait for all pending operations\n await Promise.all(this.pendingOperations);\n // Run all cleanup functions\n for (const cleanup of this.cleanupFns.values()) {\n try {\n await cleanup();\n }\n catch (error) {\n console.error('Error during cleanup:', error);\n }\n }\n this.cleanupFns.clear();\n }\n async runOperation(operation) {\n const promise = operation();\n const voidPromise = promise.then(() => { }, () => { });\n this.pendingOperations.add(voidPromise);\n try {\n const result = await promise;\n this.pendingOperations.delete(voidPromise);\n return result;\n }\n catch (error) {\n this.pendingOperations.delete(voidPromise);\n throw error;\n }\n }\n}\n/**\n * Decorator to register a controller class with a name\n * @param name The name to register the controller under\n */\nfunction controller(name) {\n return function (constructor, _context) {\n // Access globalThis.snice directly to ensure consistency\n const registry = globalThis.snice?.controllerRegistry;\n if (!registry) {\n throw new Error('Snice global registry not initialized');\n }\n registry.set(name, constructor);\n // Mark as controller class for channel decorator detection\n constructor.prototype[IS_CONTROLLER_CLASS] = true;\n const pending = snice.pendingControllerAttachments.get(name);\n if (pending) {\n snice.pendingControllerAttachments.delete(name);\n queueMicrotask(() => {\n for (const element of pending) {\n const nativeName = element[NATIVE_CONTROLLER];\n const desiredName = nativeName === undefined\n ? element[CONTROLLER]\n : nativeName;\n if (desiredName !== name)\n continue;\n attachController(element, name).catch(error => {\n if (error?.name !== 'ControllerAttachAborted') {\n console.error(`Failed to attach controller \"${name}\":`, error);\n }\n });\n }\n });\n }\n return constructor;\n };\n}\n/** Queue an element until its controller module finishes registering. */\nfunction deferControllerAttachment(element, controllerName) {\n // Registration can win the microtask race between attachController's\n // rejected promise and this recovery path. Retry immediately in that case.\n if (snice.controllerRegistry.has(controllerName)) {\n queueMicrotask(() => {\n const nativeName = element[NATIVE_CONTROLLER];\n const desiredName = nativeName === undefined\n ? element[CONTROLLER]\n : nativeName;\n if (desiredName !== controllerName)\n return;\n attachController(element, controllerName).catch(error => {\n if (error?.name !== 'ControllerAttachAborted') {\n console.error(`Failed to attach controller \"${controllerName}\":`, error);\n }\n });\n });\n return;\n }\n let pending = snice.pendingControllerAttachments.get(controllerName);\n if (!pending) {\n pending = new Set();\n snice.pendingControllerAttachments.set(controllerName, pending);\n }\n pending.add(element);\n // Give synchronously evaluated and microtask-delayed controller modules a\n // chance to register, while keeping genuinely missing controllers loud.\n queueMicrotask(() => {\n if (snice.pendingControllerAttachments.get(controllerName)?.has(element)) {\n console.error(`Failed to attach controller \"${controllerName}\":`, new Error(`Controller \"${controllerName}\" not found in registry`));\n }\n });\n}\n/**\n * True when the value is a controller class that went through @controller().\n * The decorator is required — it registers the class, marks it, and flushes\n * pending attachments. Direct class binding only changes the attach side.\n */\nfunction isControllerClass(value) {\n return typeof value === 'function'\n && value.prototype?.[IS_CONTROLLER_CLASS] === true;\n}\n/** Human-readable label for a controller reference (registry name or class). */\nfunction controllerLabel(controller) {\n return typeof controller === 'string'\n ? controller\n : (controller?.name || '(anonymous controller class)');\n}\n/**\n * Attaches a controller to an element\n * @param element The element to attach the controller to\n * @param controller The registry name of the controller, or the decorated\n * controller class itself (classes skip the registry)\n */\nasync function attachController(element, controller) {\n if (typeof controller !== 'string') {\n if (typeof controller !== 'function') {\n throw new Error('attachController: expected a controller name or a controller class, ' +\n `got ${typeof controller}. Controller instances are not supported — pass the class itself.`);\n }\n if (!isControllerClass(controller)) {\n throw new Error(`Controller class \"${controllerLabel(controller)}\" must be decorated with ` +\n `@controller('name') before it can be attached.`);\n }\n }\n const controllerName = controllerLabel(controller);\n const existingController = element[CONTROLLER_KEY];\n const existingSource = element[CONTROLLER_NAME_KEY];\n // For attribute-managed native elements, check if this is actually the\n // desired controller. Class attachments take the element over instead.\n const nativeController = element[NATIVE_CONTROLLER];\n if (typeof controller === 'string' && nativeController !== undefined && nativeController !== controller) {\n // This attachment is outdated, skip it\n return;\n }\n if (existingSource === controller && existingController) {\n // Already attached and controller exists (name or class reference match)\n return;\n }\n // If there's an existing controller, detach it first\n if (existingController) {\n await detachController(element);\n }\n let ControllerClass;\n if (typeof controller === 'string') {\n // Access globalThis.snice directly to ensure consistency\n const registry = globalThis.snice?.controllerRegistry;\n if (!registry) {\n throw new Error('Snice global registry not initialized');\n }\n ControllerClass = registry.get(controller);\n if (!ControllerClass) {\n throw new Error(`Controller \"${controller}\" not found in registry`);\n }\n }\n else {\n ControllerClass = controller;\n // The class channel owns the element from here on: the attribute /\n // MutationObserver channel goes inert and its bookkeeping is dropped.\n element[DIRECT_CONTROLLER] = true;\n delete element[NATIVE_CONTROLLER];\n }\n // Create controller instance with unique ID and scope\n const controllerInstance = new ControllerClass();\n snice.controllerIdCounter += 1;\n const controllerId = snice.controllerIdCounter;\n const scope = new ControllerScope();\n // Mark this as a controller instance\n controllerInstance[IS_CONTROLLER_INSTANCE] = true;\n controllerInstance[CONTROLLER_ID] = controllerId;\n controllerInstance.element = element;\n // Pass router context from element to controller if it exists\n const routerContext = element[ROUTER_CONTEXT];\n if (routerContext !== undefined) {\n controllerInstance[ROUTER_CONTEXT] = routerContext;\n }\n // Store references. CONTROLLER_NAME_KEY holds the attach source — the\n // registry name string, or the class reference itself for class attaches\n // (reference equality is the dedupe key for classes).\n element[CONTROLLER_KEY] = controllerInstance;\n element[CONTROLLER_NAME_KEY] = controller;\n element[CONTROLLER_OPERATIONS] = scope;\n // Wait for element to be ready. Race against abort (detachController) and\n // a 30s deadline so a caller that forgets to append the element gets a\n // clear error instead of an unresolvable promise.\n const abort = new AbortController();\n element[CONTROLLER_ABORT] = abort;\n const ATTACH_DEADLINE_MS = 30_000;\n try {\n await Promise.race([\n element.ready,\n new Promise((_, reject) => {\n const onAbort = () => {\n // Tagged so fire-and-forget call sites can tell this designed\n // teardown path apart from real attach failures and stay quiet.\n const error = new Error(`attachController(\"${controllerName}\"): aborted before element was ready (likely detached or never connected)`);\n error.name = 'ControllerAttachAborted';\n reject(error);\n };\n if (abort.signal.aborted)\n return onAbort();\n abort.signal.addEventListener('abort', onAbort, { once: true });\n const timerId = setTimeout(() => reject(new Error(`attachController(\"${controllerName}\"): element did not become ready within ${ATTACH_DEADLINE_MS}ms (did you forget to appendChild it?)`)), ATTACH_DEADLINE_MS);\n abort.signal.addEventListener('abort', () => clearTimeout(timerId), { once: true });\n }),\n ]);\n }\n catch (error) {\n // Attach never got past `ready` (aborted or deadline). Roll back the stored\n // references so nothing is left pointing at a controller that never\n // attached — otherwise a later attach short-circuits as \"already attached\"\n // and a detach would run detach() on it.\n if (element[CONTROLLER_KEY] === controllerInstance) {\n delete element[CONTROLLER_KEY];\n delete element[CONTROLLER_NAME_KEY];\n delete element[CONTROLLER_OPERATIONS];\n if (typeof controller !== 'string') {\n delete element[DIRECT_CONTROLLER];\n }\n }\n throw error;\n }\n finally {\n if (element[CONTROLLER_ABORT] === abort) {\n delete element[CONTROLLER_ABORT];\n }\n }\n // Past `ready` — mark the controller so detach knows attach was actually run.\n controllerInstance[CONTROLLER_ATTACHED] = true;\n // Run attach in the controller's scope\n await scope.runOperation(async () => {\n await controllerInstance.attach(element);\n });\n // Setup @observe observers for controller\n setupObservers(controllerInstance, element);\n // Setup @channel handlers for controller\n setupResponseHandlers(controllerInstance, element);\n // Setup @on event handlers for controller\n setupEventHandlers(controllerInstance, element);\n element.dispatchEvent(new CustomEvent('controller-attached', {\n detail: { name: controllerName, controller: controllerInstance }\n }));\n}\n/**\n * Detaches a controller from an element\n * @param element The element to detach the controller from\n */\nasync function detachController(element) {\n // If attachController is currently awaiting `.ready`, short-circuit that\n // wait so the pending attach rejects immediately instead of hanging.\n const pendingAbort = element[CONTROLLER_ABORT];\n if (pendingAbort)\n pendingAbort.abort();\n const controllerInstance = element[CONTROLLER_KEY];\n const controllerSource = element[CONTROLLER_NAME_KEY];\n const scope = element[CONTROLLER_OPERATIONS];\n if (!controllerInstance) {\n return;\n }\n // Claim the controller immediately — before any await — so a second detach\n // that overlaps this one (e.g. disconnect's fire-and-forget detach racing a\n // controller reassignment) finds no instance and returns, instead of running\n // detach() a second time on the same controller. The rest of this function\n // works off the locals captured above.\n delete element[CONTROLLER_KEY];\n delete element[CONTROLLER_NAME_KEY];\n delete element[CONTROLLER_OPERATIONS];\n if (typeof controllerSource === 'function') {\n // Class attach owned the element — release it back to the attribute channel.\n delete element[DIRECT_CONTROLLER];\n }\n // A controller whose attach() was aborted before it ever ran must not have\n // detach() (or the teardown/event) run on it.\n if (!controllerInstance[CONTROLLER_ATTACHED]) {\n return;\n }\n // Run detach in the controller's scope\n if (scope) {\n await scope.runOperation(async () => {\n await controllerInstance.detach(element);\n });\n }\n else {\n await controllerInstance.detach(element);\n }\n controllerInstance.element = null;\n // Cleanup @observe observers for controller\n cleanupObservers(controllerInstance);\n // Cleanup @channel handlers for controller\n cleanupResponseHandlers(controllerInstance);\n // Cleanup @on event handlers for controller\n cleanupEventHandlers(controllerInstance);\n // Cleanup the controller scope\n if (scope) {\n await scope.cleanup();\n }\n // Clean up router context reference\n delete controllerInstance[ROUTER_CONTEXT];\n element.dispatchEvent(new CustomEvent('controller-detached', {\n detail: {\n name: controllerSource === undefined ? undefined : controllerLabel(controllerSource),\n controller: controllerInstance\n }\n }));\n}\n/**\n * Gets the controller instance attached to an element\n * @param element The element to get the controller from\n * @returns The controller instance or undefined\n */\nfunction getController(element) {\n return element[CONTROLLER_KEY];\n}\n/**\n * Enable controller support for native HTML elements\n * This sets up a MutationObserver to watch for controller attributes\n * on non-custom elements (elements without hyphens in their tag names)\n */\nfunction useNativeElementControllers() {\n // Return if already initialized\n if (globalThis.sniceNativeControllersInitialized) {\n return;\n }\n globalThis.sniceNativeControllersInitialized = true;\n // Process elements that already have controller attribute\n function processElement(element) {\n if (!(element instanceof HTMLElement))\n return;\n // `tagName` can briefly be null when happy-dom/native mutation observers\n // fire on a node that's been detached mid-callback. Skip cleanly.\n if (!element.tagName || element.tagName.includes('-'))\n return;\n if (element[IS_ELEMENT_CLASS])\n return;\n // A controller CLASS is attached (template binding or direct\n // attachController(el, Class)). The class channel owns the element:\n // attribute writes must not attach over it, and insertion sweeps must\n // not detach it.\n if (element[DIRECT_CONTROLLER])\n return;\n const controllerName = element.getAttribute('controller');\n const currentControllerName = element[NATIVE_CONTROLLER];\n // No change\n if (controllerName === currentControllerName)\n return;\n // No attribute and never attribute-managed — nothing for this channel to\n // do. Without this guard, every added native element (including ones a\n // class controller was imperatively attached to before insertion) would\n // fall into the removal branch and get spuriously detached.\n if (!controllerName && currentControllerName === undefined)\n return;\n // Controller removed\n if (!controllerName) {\n delete element[NATIVE_CONTROLLER];\n delete element[CONTROLLER_NAME_KEY];\n detachController(element).catch(error => {\n console.error(`Failed to detach controller from native element:`, error);\n });\n return;\n }\n // Controller added or changed\n element[NATIVE_CONTROLLER] = controllerName;\n if (!element.ready) {\n element.ready = Promise.resolve();\n }\n if (currentControllerName) {\n detachController(element).catch(error => {\n console.error(`Failed to detach old controller from native element:`, error);\n });\n }\n attachController(element, controllerName).catch(error => {\n // Detached before ready — designed teardown, not a failure\n if (error?.name === 'ControllerAttachAborted') {\n console.debug(`Controller \"${controllerName}\" attach aborted (element detached before ready)`);\n return;\n }\n if (error?.message === `Controller \"${controllerName}\" not found in registry`) {\n deferControllerAttachment(element, controllerName);\n return;\n }\n console.error(`Failed to attach controller \"${controllerName}\" to native element:`, error);\n });\n }\n // Set up MutationObserver to watch for controller attributes\n const observer = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type === 'attributes' && mutation.attributeName === 'controller') {\n processElement(mutation.target);\n }\n else if (mutation.type === 'childList') {\n // Process added nodes\n mutation.addedNodes.forEach(node => {\n if (node instanceof HTMLElement) {\n // Process the node itself\n processElement(node);\n // Process all descendants with controller attribute\n node.querySelectorAll('[controller]').forEach(processElement);\n }\n });\n }\n }\n });\n function startObserving() {\n document.querySelectorAll('[controller]').forEach(processElement);\n observer.observe(document.body, {\n attributes: true,\n attributeFilter: ['controller'],\n childList: true,\n subtree: true\n });\n }\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', startObserving);\n }\n else {\n startObserving();\n }\n // Store observer reference for cleanup if needed\n globalThis.sniceNativeControllerObserver = observer;\n}\n\n/**\n * @context decorator for receiving router context updates\n */\nconst CONTEXT_HANDLERS = getSymbol('context-handlers');\n/**\n * @context decorator for receiving router context updates\n *\n * @example\n * ```typescript\n * @element('my-layout')\n * class MyLayout extends HTMLElement {\n * @context\n * handleContext(ctx: Context) {\n * this.renderNav(ctx.placards, ctx.currentRoute);\n * }\n *\n * @context({ debounce: 300 })\n * handleContextDebounced(ctx: Context) {\n * // Called after 300ms of no updates\n * }\n * }\n * ```\n */\nfunction context$1(options = {}) {\n return function (originalMethod, context) {\n const methodName = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // hasOwnProperty guards so subclasses don't mutate parent state via\n // the prototype chain.\n if (!Object.prototype.hasOwnProperty.call(constructor, CONTEXT_METHODS)) {\n constructor[CONTEXT_METHODS] = new Set();\n }\n if (constructor[CONTEXT_METHODS].has(originalMethod))\n return;\n constructor[CONTEXT_METHODS].add(originalMethod);\n if (!Object.prototype.hasOwnProperty.call(constructor, CONTEXT_HANDLERS)) {\n const inherited = constructor[CONTEXT_HANDLERS];\n constructor[CONTEXT_HANDLERS] = inherited ? [...inherited] : [];\n }\n constructor[CONTEXT_HANDLERS].push({\n methodName,\n method: originalMethod,\n options,\n });\n });\n return originalMethod;\n };\n}\n/**\n * Setup context handler for an element instance\n * Called automatically during element connection\n */\nfunction setupContextHandler(element) {\n const handlers = element.constructor[CONTEXT_HANDLERS];\n if (!handlers || !Array.isArray(handlers) || handlers.length === 0) {\n return;\n }\n // Get the Context instance from the router\n const ctx = element[CONTEXT_HANDLER];\n if (!ctx) {\n return;\n }\n // Store the Context instance for cleanup\n element[NAVIGATION_CONTEXT_INSTANCE] = ctx;\n // Register each handler with the Context\n for (const handler of handlers) {\n const { methodName, method, options } = handler;\n const wrappedMethodName = `__wrapped_${methodName}`;\n // Create wrapped method with timing controls\n element[wrappedMethodName] = function (context) {\n // `once` is tracked PER method (not a single element-level flag) so\n // multiple once handlers on the same element each fire.\n const called = element[CONTEXT_CALLED] ||\n (element[CONTEXT_CALLED] = new Set());\n if (options.once && called.has(methodName)) {\n return;\n }\n const callMethod = () => {\n method.call(element, context);\n // Handle once option\n if (options.once) {\n called.add(methodName);\n // Unregister ONLY this handler, not the whole element — otherwise the\n // element's other @context handlers would stop receiving updates.\n const ctx = element[NAVIGATION_CONTEXT_INSTANCE];\n if (ctx && typeof ctx[CONTEXT_UNREGISTER] === 'function') {\n ctx[CONTEXT_UNREGISTER](element, wrappedMethodName);\n }\n }\n };\n // Per-handler timer slot to avoid debounce/throttle handlers on the same\n // element overwriting each other's state.\n const timerSlot = element[CONTEXT_TIMER] ||\n (element[CONTEXT_TIMER] = {});\n const timerKey = methodName;\n if (options.debounce) {\n clearTimeout(timerSlot[timerKey]?.timeout);\n timerSlot[timerKey] = {\n timeout: setTimeout(callMethod, options.debounce),\n };\n return;\n }\n if (options.throttle) {\n const now = Date.now();\n const lastCall = timerSlot[timerKey]?.lastCall || 0;\n if (now - lastCall >= options.throttle) {\n timerSlot[timerKey] = { lastCall: now };\n callMethod();\n }\n return;\n }\n callMethod();\n };\n // Register with the Context using the wrapped method name\n if (typeof ctx[CONTEXT_REGISTER] === 'function') {\n ctx[CONTEXT_REGISTER](element, wrappedMethodName);\n }\n }\n}\n/**\n * Cleanup context handler for an element instance\n * Called automatically during element disconnection\n */\nfunction cleanupContextHandler(element) {\n const handlers = element.constructor[CONTEXT_HANDLERS];\n if (!handlers || !Array.isArray(handlers) || handlers.length === 0) {\n return;\n }\n // Clear any pending debounce timers (per-handler slots)\n const timerSlot = element[CONTEXT_TIMER];\n if (timerSlot && typeof timerSlot === 'object') {\n for (const key of Object.keys(timerSlot)) {\n if (timerSlot[key]?.timeout)\n clearTimeout(timerSlot[key].timeout);\n }\n delete element[CONTEXT_TIMER];\n }\n for (const handler of handlers) {\n // Clean up wrapped method\n const wrappedMethodName = `__wrapped_${handler.methodName}`;\n delete element[wrappedMethodName];\n }\n // Unregister from Context if available\n const ctx = element[NAVIGATION_CONTEXT_INSTANCE];\n if (ctx && typeof ctx[CONTEXT_UNREGISTER] === 'function') {\n ctx[CONTEXT_UNREGISTER](element);\n }\n delete element[NAVIGATION_CONTEXT_INSTANCE];\n delete element[CONTEXT_CALLED];\n}\n\n/**\n * @render and @styles decorators for Snice v3.0.0\n * Provides automatic differential rendering on property changes\n */\n/**\n * When true, render errors are rethrown instead of logged, so tests and dev\n * environments fail loudly rather than leaving the element silently stale.\n * Production default is false (log and keep the previous DOM).\n */\nlet strictRenderErrors = false;\nfunction setStrictRenderErrors(value) {\n strictRenderErrors = value;\n}\n/**\n * Ensure the element has a pending `rendered` promise. Called whenever a\n * render is requested; resolved by performRender once the render commits.\n */\nfunction ensureRenderedPromise(element) {\n if (!element[RENDERED_RESOLVE]) {\n element[RENDERED_PROMISE] = new Promise((resolve) => {\n element[RENDERED_RESOLVE] = resolve;\n });\n }\n}\n/** Resolve the element's pending `rendered` promise, if any. */\nfunction resolveRendered(element) {\n const resolve = element[RENDERED_RESOLVE];\n if (resolve) {\n element[RENDERED_RESOLVE] = null;\n resolve();\n }\n}\n/**\n * Global render scheduler for microtask batching\n * Batches multiple property changes into a single render\n */\nclass RenderScheduler {\n constructor() {\n this.pending = new Set();\n this.scheduled = false;\n }\n /**\n * Schedule an element for rendering\n * Batches renders in a microtask unless sync option is enabled\n */\n schedule(element, options) {\n // Sync rendering - execute immediately\n if (options.sync) {\n performRender(element, options);\n return;\n }\n // Async rendering - batch in microtask\n this.pending.add(element);\n if (!this.scheduled) {\n this.scheduled = true;\n queueMicrotask(() => this.flush());\n }\n }\n /**\n * Flush all pending renders\n */\n flush() {\n const elements = Array.from(this.pending);\n this.pending.clear();\n this.scheduled = false;\n for (const element of elements) {\n // Skip elements that were disconnected between scheduling and flush, but\n // remember the dropped render so reconnect can replay it — otherwise the\n // shadow DOM stays stale for a property changed while detached. The flag\n // lives on the element, so it's GC'd with it (no leak if never reattached).\n if (!element.isConnected) {\n element[PENDING_RECONNECT_RENDER] = true;\n continue;\n }\n const options = element[RENDER_OPTIONS] || {};\n performRender(element, options);\n }\n }\n /** Remove a disconnected element from the queue */\n remove(element) {\n this.pending.delete(element);\n }\n}\nconst renderScheduler = new RenderScheduler();\nfunction hasRendered(element) {\n return Object.prototype.hasOwnProperty.call(element, RENDER_INSTANCE);\n}\nfunction flushRenderCallbacks(element) {\n const callbacks = element[RENDER_CALLBACKS];\n if (!callbacks || callbacks.length === 0)\n return;\n const cbs = [...callbacks];\n element[RENDER_CALLBACKS] = [];\n cbs.forEach(cb => cb());\n}\n/**\n * Backstop against a render() that mutates an observed property, which makes\n * the property setter request another render from inside the current one. In\n * `sync` mode that re-enters performRender synchronously and, unchecked,\n * recurses to a stack overflow. The counter caps synchronous nesting and turns\n * a silent crash into an actionable error. Normal renders never nest (child\n * renders defer to a microtask), so this stays at depth 1 in the common case.\n *\n * The depth is tracked PER ELEMENT (on RENDER_DEPTH), not globally: a runaway\n * component must not consume a shared budget and reject an unrelated component\n * that happens to render inside its call stack.\n */\nconst MAX_RENDER_DEPTH = 50;\n/**\n * Perform the actual render of an element\n */\nfunction performRender(element, options, precomputedResult) {\n const hasPrecomputedResult = arguments.length >= 3;\n const renderMethod = element[RENDER_METHOD];\n if (!renderMethod) {\n resolveRendered(element);\n return;\n }\n // If once is true and we've already rendered, skip\n if (options.once && hasRendered(element)) {\n resolveRendered(element);\n return;\n }\n const depth = (element[RENDER_DEPTH] ?? 0);\n if (depth >= MAX_RENDER_DEPTH) {\n const tag = element.tagName ? element.tagName.toLowerCase() : 'element';\n console.error(`snice: maximum render depth (${MAX_RENDER_DEPTH}) exceeded for <${tag}>. ` +\n `render() is mutating an observed property, causing an infinite render loop.`);\n resolveRendered(element);\n return;\n }\n element[RENDER_DEPTH] = depth + 1;\n try {\n const result = hasPrecomputedResult\n ? precomputedResult\n : renderMethod.call(element);\n const renderRoot = ensureRenderRoot(element);\n // Non-differential rendering (string)\n if (options.differential === false) {\n if (typeof result !== 'string') {\n console.warn('Render method with differential: false must return a string');\n return;\n }\n const template = document.createElement('template');\n template.innerHTML = result;\n const instance = element[RENDER_INSTANCE];\n instance?.clear();\n const removable = Array.from(renderRoot.childNodes).filter(node => !(node.nodeType === Node.ELEMENT_NODE &&\n node.tagName === 'STYLE' &&\n node.hasAttribute('data-snice-style')));\n for (const node of removable)\n node.remove();\n renderRoot.appendChild(template.content);\n // A present, null render instance records a successful string render so\n // `once` works without pretending the string tree is a TemplateInstance.\n element[RENDER_INSTANCE] = null;\n flushRenderCallbacks(element);\n return;\n }\n // Differential rendering (template)\n if (!isTemplateResult(result)) {\n console.warn('Render method must return html`` template result');\n return;\n }\n let instance = element[RENDER_INSTANCE];\n if (instance && instance.isSameTemplate(result.strings)) {\n instance.update(result.values);\n flushRenderCallbacks(element);\n return;\n }\n const nextInstance = new TemplateInstance(result);\n const nextFragment = nextInstance.renderFragment();\n // Commit while detached first. A malformed binding can then fail without\n // exposing a half-updated tree. Connection-aware parts are paired with\n // reconnected() immediately after the successful mount.\n try {\n nextInstance.update(result.values);\n }\n catch (error) {\n nextInstance.clear();\n throw error;\n }\n // Park the previous tree without disposing it, mount the prepared tree,\n // then run connection hooks. If reconnecting a listener or async part\n // fails, restore the still-live previous tree instead of leaving a\n // partially mounted replacement behind.\n const previousFragment = document.createDocumentFragment();\n for (const child of Array.from(renderRoot.childNodes)) {\n if (child.nodeType === Node.ELEMENT_NODE &&\n child.tagName === 'STYLE' &&\n child.hasAttribute('data-snice-style'))\n continue;\n previousFragment.appendChild(child);\n }\n renderRoot.appendChild(nextFragment);\n try {\n if (element.isConnected)\n nextInstance.reconnected();\n }\n catch (error) {\n try {\n nextInstance.clear();\n }\n catch (cleanupError) {\n console.error('snice: failed to clean up a rejected render tree:', cleanupError);\n }\n for (const child of Array.from(renderRoot.childNodes)) {\n if (child.nodeType === Node.ELEMENT_NODE &&\n child.tagName === 'STYLE' &&\n child.hasAttribute('data-snice-style'))\n continue;\n child.remove();\n }\n renderRoot.appendChild(previousFragment);\n throw error;\n }\n element[RENDER_INSTANCE] = nextInstance;\n let cleanupError;\n try {\n instance?.clear();\n }\n catch (error) {\n cleanupError = error;\n }\n flushRenderCallbacks(element);\n if (cleanupError)\n throw cleanupError;\n }\n catch (error) {\n if (strictRenderErrors)\n throw error;\n console.error('Error rendering element:', error);\n }\n finally {\n element[RENDER_DEPTH] = depth;\n resolveRendered(element);\n }\n}\n/** Commit immediately using the element's configured render options. */\nfunction renderElementNow(element) {\n ensureRenderedPromise(element);\n const options = element[RENDER_OPTIONS] || {};\n performRender(element, { ...options, once: false });\n}\n/**\n * Request a render for an element\n * Respects debounce/throttle/once/sync options\n * @param immediate - Force immediate render (used for initial render)\n */\nfunction requestRender(element, immediate = false) {\n const options = element[RENDER_OPTIONS] || {};\n // Handle once option\n if (options.once && hasRendered(element)) {\n if (element.isConnected)\n reconnectRenderTree(element);\n return;\n }\n // Arm the `rendered` promise: it resolves when this request's render\n // commits (immediately below for sync/immediate, later for batched/\n // debounced/throttled renders).\n ensureRenderedPromise(element);\n // Force immediate render (for initial render)\n if (immediate) {\n performRender(element, options);\n return;\n }\n // Handle debounce\n if (options.debounce !== undefined && options.debounce > 0) {\n if (!element[RENDER_TIMERS]) {\n element[RENDER_TIMERS] = {};\n }\n clearTimeout(element[RENDER_TIMERS].debounce);\n element[RENDER_TIMERS].debounce = setTimeout(() => {\n element[RENDER_TIMERS].debounce = null;\n renderScheduler.schedule(element, options);\n }, options.debounce);\n return;\n }\n // Handle throttle\n if (options.throttle !== undefined && options.throttle > 0) {\n if (!element[RENDER_TIMERS]) {\n element[RENDER_TIMERS] = { lastThrottle: 0 };\n }\n const timers = element[RENDER_TIMERS];\n const now = Date.now();\n if (timers.lastThrottle === 0 || now - timers.lastThrottle >= options.throttle) {\n timers.lastThrottle = now;\n renderScheduler.schedule(element, options);\n return;\n }\n if (!timers.throttleTimer) {\n const remaining = options.throttle - (now - timers.lastThrottle);\n timers.throttleTimer = setTimeout(() => {\n timers.throttleTimer = null;\n timers.lastThrottle = Date.now();\n renderScheduler.schedule(element, options);\n }, remaining);\n }\n return;\n }\n // Normal rendering (with microtask batching unless sync)\n renderScheduler.schedule(element, options);\n}\n/**\n * Clear any pending debounce/throttle render timers on an element (e.g. on\n * disconnect, so they don't fire on a dead element and retain it until they\n * expire). Returns true if a render was actually pending, so the caller can\n * arrange a replay on reconnect via PENDING_RECONNECT_RENDER.\n */\nfunction clearRenderTimers(element) {\n const timers = element[RENDER_TIMERS];\n if (!timers)\n return false;\n let hadPending = false;\n if (timers.debounce) {\n clearTimeout(timers.debounce);\n timers.debounce = null;\n hadPending = true;\n }\n if (timers.throttleTimer) {\n clearTimeout(timers.throttleTimer);\n timers.throttleTimer = null;\n hadPending = true;\n }\n // Deliberately do NOT reset timers.lastThrottle: a plain DOM move is a\n // disconnect+reconnect, and zeroing the cooldown would let the next render\n // fire inside the throttle window. Preserving it keeps throttle honest\n // across moves; on a true disconnect the element is discarded anyway.\n return hadPending;\n}\n/** Pause connection-aware render parts while an element is detached. */\nfunction disconnectRenderTree(element) {\n const instance = element[RENDER_INSTANCE];\n // A host disconnection is not the same thing as parking a conditional\n // branch. The shadow/light render tree still belongs to the host, so native\n // event listeners remain usable on retained node references. Async iteration\n // is paused, and parked branches continue to detach their listeners through\n // the ordinary Part lifecycle.\n instance?.disconnected(true);\n}\n/** Resume connection-aware render parts when an existing tree reconnects. */\nfunction reconnectRenderTree(element) {\n const instance = element[RENDER_INSTANCE];\n instance?.reconnected();\n}\n/**\n * @render decorator for component rendering\n *\n * Marks a method as the render method for the component.\n * The method should return html`...` template.\n * Automatically re-renders when properties change (unless once: true).\n *\n * @example\n * ```typescript\n * @render()\n * renderContent() {\n * return html`<div>${this.count}</div>`;\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Debounced rendering\n * @render({ debounce: 100 })\n * renderContent() {\n * return html`<div>${this.searchTerm}</div>`;\n * }\n * ```\n *\n * @example\n * ```typescript\n * // Render only once (manual re-renders only)\n * @render({ once: true })\n * renderContent() {\n * return html`<div>Static content</div>`;\n * }\n * ```\n */\nfunction render(options = {}) {\n return function (originalMethod, context) {\n context.name;\n context.addInitializer(function () {\n // Store the render method and options\n this[RENDER_METHOD] = originalMethod;\n this[RENDER_OPTIONS] = options;\n });\n // Return wrapped method that triggers re-render when called manually\n return function (...args) {\n // Call original method to get the template\n const result = originalMethod.apply(this, args);\n // Always render when method is called manually (even if once: true)\n // Force immediate render to bypass all options, pass precomputed result to avoid calling method twice\n const configured = this[RENDER_OPTIONS] || options;\n performRender(this, { ...configured, once: false }, result);\n return result;\n };\n };\n}\n/**\n * @styles decorator for component styles\n *\n * Marks a method as the styles method for the component.\n * The method should return css`...` template.\n * Styles are applied once when the component is connected.\n *\n * @example\n * ```typescript\n * @styles()\n * styles() {\n * return css`:host { display: block; }`;\n * }\n * ```\n */\nfunction styles() {\n return function (originalMethod, context) {\n context.addInitializer(function () {\n // Collect parent styles methods before overwriting with child's\n if (this[STYLES_METHOD] && !this[PARENT_STYLES_METHODS]) {\n this[PARENT_STYLES_METHODS] = [this[STYLES_METHOD]];\n }\n else if (this[STYLES_METHOD] && this[PARENT_STYLES_METHODS]) {\n this[PARENT_STYLES_METHODS].push(this[STYLES_METHOD]);\n }\n this[STYLES_METHOD] = originalMethod;\n });\n return originalMethod;\n };\n}\n/**\n * Apply styles to an element\n * Called during element initialization\n */\nfunction applyStyles(element) {\n const stylesMethod = element[STYLES_METHOD];\n const staticResults = [];\n const constructors = [];\n let constructor = element.constructor;\n while (constructor && constructor !== HTMLElement && constructor !== Function.prototype) {\n constructors.unshift(constructor);\n constructor = Object.getPrototypeOf(constructor);\n }\n for (const current of constructors) {\n if (!Object.prototype.hasOwnProperty.call(current, 'styles'))\n continue;\n const value = current.styles;\n const values = Array.isArray(value) ? value : [value];\n for (const result of values) {\n if (isCSSResult(result))\n staticResults.push(result);\n else\n console.warn('Static styles must be a css`` result or an array of css`` results');\n }\n }\n if (!stylesMethod && staticResults.length === 0)\n return;\n // Only apply once\n if (element[STYLES_APPLIED])\n return;\n element[STYLES_APPLIED] = true;\n try {\n // Collect all CSS results: parent styles first, then child styles\n const allResults = [...staticResults];\n const parentMethods = element[PARENT_STYLES_METHODS];\n if (parentMethods) {\n for (const method of parentMethods) {\n const r = method.call(element);\n if (isCSSResult(r))\n allResults.push(r);\n }\n }\n if (stylesMethod) {\n const result = stylesMethod.call(element);\n if (!isCSSResult(result)) {\n console.warn('Styles method must return css`` template result');\n return;\n }\n allResults.push(result);\n }\n const renderRoot = ensureRenderRoot(element);\n // Retain matching framework-owned style elements instead of adding a\n // duplicate stylesheet during a repeated setup pass.\n const existingStyles = Array.from(renderRoot.childNodes).filter(node => node.nodeType === Node.ELEMENT_NODE &&\n node.tagName === 'STYLE' &&\n node.hasAttribute('data-snice-style'));\n if (existingStyles.length === allResults.length &&\n existingStyles.every((style, index) => style.textContent === allResults[index].cssText)) {\n return;\n }\n for (const style of existingStyles)\n style.remove();\n // Prefer constructable stylesheets\n if (renderRoot instanceof ShadowRoot && allResults.every(r => !!r.styleSheet) && 'adoptedStyleSheets' in renderRoot) {\n try {\n renderRoot.adoptedStyleSheets = allResults.map(r => r.styleSheet);\n return;\n }\n catch {\n // A stylesheet constructed in another Window/Document realm cannot be\n // adopted here. Fall through to equivalent <style> elements.\n }\n }\n // Fallback — one <style> tag per stylesheet, preserving cascade order.\n // Marked so the template-switch cleanup keeps these (framework styles) but\n // still removes template-emitted <style> tags (which would otherwise pile up).\n for (const r of allResults) {\n const style = document.createElement('style');\n style.setAttribute('data-snice-style', '');\n style.textContent = r.cssText;\n renderRoot.appendChild(style);\n }\n }\n catch (error) {\n console.error('Error applying styles:', error);\n }\n}\n\n// @dispatch decorator - auto-dispatches custom events from method return values\n/**\n * Decorator that automatically dispatches a custom event after a method is called.\n * The return value of the method becomes the event detail.\n *\n * @param eventName The name of the event to dispatch\n * @param options Optional configuration extending EventInit\n */\nfunction dispatch(eventName, options) {\n return function (originalMethod, _context) {\n return function (...args) {\n // Create timing wrappers for dispatch (per-instance)\n if (!this[DISPATCH_TIMERS]) {\n this[DISPATCH_TIMERS] = new Map();\n }\n const timerKey = `${eventName}_${_context.name}`;\n if (!this[DISPATCH_TIMERS].has(timerKey)) {\n this[DISPATCH_TIMERS].set(timerKey, {\n debounceTimeout: null,\n throttleLastCall: 0,\n throttleTimeout: null\n });\n }\n const timers = this[DISPATCH_TIMERS].get(timerKey);\n // Call the original method with preserved this context\n const result = originalMethod.apply(this, args);\n // Helper to dispatch the event\n const doDispatch = (detail) => {\n // Skip dispatch if result is undefined and dispatchOnUndefined is false\n if (detail === undefined && options?.dispatchOnUndefined === false) {\n return;\n }\n // Create event with spread operator for options\n const event = new CustomEvent(eventName, {\n bubbles: true, // Default to true for component events\n composed: true, // Allow crossing shadow DOM boundaries\n ...options, // Spread all EventInit options\n detail\n });\n // Resolve scope target. Default is `this` (host element).\n // Explicit scope dispatches the event on another target — useful for\n // 'global' bus events on document, or routing through an ancestor.\n if (options?.scope !== undefined) {\n const target = resolveScope(this, options.scope);\n if (!target) {\n console.warn(`[snice/@dispatch] scope did not resolve for \"${eventName}\" — event not dispatched.`);\n return;\n }\n target.dispatchEvent(event);\n return;\n }\n this.dispatchEvent(event);\n };\n // Helper to handle timed dispatch\n const timedDispatch = (detail) => {\n if (options?.debounce) {\n clearTimeout(timers.debounceTimeout);\n timers.debounceTimeout = setTimeout(() => doDispatch(detail), options.debounce);\n return;\n }\n if (!options?.throttle) {\n doDispatch(detail);\n return;\n }\n const now = Date.now();\n const remaining = options.throttle - (now - timers.throttleLastCall);\n if (remaining <= 0) {\n clearTimeout(timers.throttleTimeout);\n timers.throttleLastCall = now;\n doDispatch(detail);\n return;\n }\n // Record the LATEST detail so the trailing dispatch carries fresh\n // data, not the first-suppressed-call detail captured by closure.\n timers.latestDetail = detail;\n if (!timers.throttleTimeout) {\n timers.throttleTimeout = setTimeout(() => {\n timers.throttleLastCall = Date.now();\n timers.throttleTimeout = null;\n const d = timers.latestDetail;\n timers.latestDetail = undefined;\n doDispatch(d);\n }, remaining);\n }\n };\n // Handle async methods\n if (result instanceof Promise) {\n return result.then((resolvedResult) => {\n timedDispatch(resolvedResult);\n return resolvedResult;\n });\n }\n // Sync method\n timedDispatch(result);\n return result;\n };\n };\n}\n/**\n * Clear any pending debounce/throttle dispatch timers on an instance (e.g. on\n * disconnect, so a queued event doesn't fire into a detached node). A dispatch\n * is a one-shot signal, so pending ones are dropped, not replayed.\n */\nfunction clearDispatchTimers(instance) {\n const timers = instance[DISPATCH_TIMERS];\n if (!timers)\n return;\n for (const t of timers.values()) {\n if (t.debounceTimeout)\n clearTimeout(t.debounceTimeout);\n if (t.throttleTimeout)\n clearTimeout(t.throttleTimeout);\n t.debounceTimeout = null;\n t.throttleTimeout = null;\n t.throttleLastCall = 0;\n t.latestDetail = undefined;\n }\n}\n\n/**\n * Method decorators for common patterns\n * @debounce, @throttle, @once, @memoize\n */\nconst DEBOUNCE_TIMERS = getSymbol('debounce-timers');\nconst THROTTLE_TIMERS = getSymbol('throttle-timers');\nconst ONCE_CALLED = getSymbol('once-called');\nconst MEMOIZE_CACHE = getSymbol('memoize-cache');\n/**\n * @debounce decorator - delays function execution until after wait time has elapsed\n * since the last invocation\n *\n * @param wait - Time to wait in milliseconds (default: 300)\n * @param options - Debounce options\n * @param options.leading - Invoke on the leading edge (default: false)\n * @param options.trailing - Invoke on the trailing edge (default: true)\n * @param options.maxWait - Maximum time to wait before invoking (default: undefined)\n *\n * @example\n * ```typescript\n * @element('search-input')\n * class SearchInput extends HTMLElement {\n * @debounce(500)\n * handleSearch(query: string) {\n * // Only called 500ms after last keystroke\n * fetch(`/api/search?q=${query}`);\n * }\n * }\n * ```\n */\nfunction debounce(wait = 300, options = {}) {\n const { leading = false, trailing = true, maxWait } = options;\n return function (originalMethod, context) {\n const methodName = context.name;\n return function (...args) {\n if (!this[DEBOUNCE_TIMERS]) {\n this[DEBOUNCE_TIMERS] = {};\n }\n const timers = this[DEBOUNCE_TIMERS];\n const timerKey = methodName;\n // Clear existing timer\n if (timers[timerKey]) {\n clearTimeout(timers[timerKey].timeout);\n }\n // Track when debounce started for maxWait\n const now = Date.now();\n const isFirstCall = !timers[timerKey];\n const startTime = isFirstCall ? now : timers[timerKey].startTime;\n // Check if maxWait exceeded\n const shouldInvokeFromMaxWait = maxWait !== undefined && now - startTime >= maxWait;\n // Leading edge invocation\n if (leading && isFirstCall) {\n const result = originalMethod.apply(this, args);\n timers[timerKey] = {\n timeout: null,\n startTime,\n lastArgs: args,\n };\n return result;\n }\n // Set new timer for trailing edge\n const timeout = setTimeout(() => {\n if (trailing || shouldInvokeFromMaxWait) {\n originalMethod.apply(this, timers[timerKey].lastArgs);\n }\n delete timers[timerKey];\n }, shouldInvokeFromMaxWait ? 0 : wait);\n timers[timerKey] = {\n timeout,\n startTime,\n lastArgs: args,\n };\n };\n };\n}\n/**\n * @throttle decorator - ensures function is called at most once per specified time period\n *\n * @param wait - Time to wait in milliseconds (default: 300)\n * @param options - Throttle options\n * @param options.leading - Invoke on the leading edge (default: true)\n * @param options.trailing - Invoke on the trailing edge (default: true)\n *\n * @example\n * ```typescript\n * @element('scroll-tracker')\n * class ScrollTracker extends HTMLElement {\n * @throttle(100)\n * handleScroll(e: Event) {\n * // Called at most once every 100ms\n * this.updateScrollPosition();\n * }\n * }\n * ```\n */\nfunction throttle(wait = 300, options = {}) {\n const { leading = true, trailing = true } = options;\n return function (originalMethod, context) {\n const methodName = context.name;\n return function (...args) {\n if (!this[THROTTLE_TIMERS]) {\n this[THROTTLE_TIMERS] = {};\n }\n const timers = this[THROTTLE_TIMERS];\n const timerKey = methodName;\n const now = Date.now();\n // First call\n if (!timers[timerKey]) {\n if (leading)\n originalMethod.apply(this, args);\n timers[timerKey] = { lastInvoke: now, timeout: null, lastArgs: args };\n if (trailing && !leading) {\n timers[timerKey].timeout = setTimeout(() => {\n originalMethod.apply(this, timers[timerKey].lastArgs);\n delete timers[timerKey];\n }, wait);\n }\n return;\n }\n // Subsequent calls\n const timeSinceLastInvoke = now - timers[timerKey].lastInvoke;\n timers[timerKey].lastArgs = args;\n if (timers[timerKey].timeout) {\n clearTimeout(timers[timerKey].timeout);\n }\n // Enough time passed — invoke immediately\n if (timeSinceLastInvoke >= wait) {\n originalMethod.apply(this, args);\n timers[timerKey].lastInvoke = now;\n return;\n }\n // Set up trailing call\n if (trailing) {\n const remaining = wait - timeSinceLastInvoke;\n timers[timerKey].timeout = setTimeout(() => {\n originalMethod.apply(this, timers[timerKey].lastArgs);\n timers[timerKey].lastInvoke = Date.now();\n timers[timerKey].timeout = null;\n }, remaining);\n }\n };\n };\n}\n/**\n * @once decorator - ensures function is only called once\n * Subsequent calls return the result of the first call\n *\n * @param perInstance - If true, function can be called once per instance (default: true)\n * If false, function can only be called once globally across all instances\n *\n * @example\n * ```typescript\n * @element('data-loader')\n * class DataLoader extends HTMLElement {\n * @once()\n * async loadData() {\n * // Only loads data once, even if called multiple times\n * const data = await fetch('/api/data');\n * return data.json();\n * }\n * }\n * ```\n */\nfunction once(perInstance = true) {\n let globalCalled = false;\n let globalResult;\n return function (originalMethod, context) {\n const methodName = context.name;\n return function (...args) {\n // Per-instance tracking\n if (perInstance) {\n if (!this[ONCE_CALLED])\n this[ONCE_CALLED] = {};\n if (!this[ONCE_CALLED][methodName]) {\n this[ONCE_CALLED][methodName] = {\n called: true,\n result: originalMethod.apply(this, args),\n };\n }\n return this[ONCE_CALLED][methodName].result;\n }\n // Global tracking\n if (!globalCalled) {\n globalCalled = true;\n globalResult = originalMethod.apply(this, args);\n }\n return globalResult;\n };\n };\n}\n/**\n * @memoize decorator - caches function results based on arguments\n * Uses JSON.stringify for argument comparison by default\n *\n * @param options - Memoization options\n * @param options.keyGenerator - Custom function to generate cache key from arguments\n * @param options.maxSize - Maximum cache size (default: 100)\n * @param options.ttl - Time to live in milliseconds (default: undefined - no expiration)\n *\n * @example\n * ```typescript\n * @element('calculator')\n * class Calculator extends HTMLElement {\n * @memoize({ maxSize: 50 })\n * fibonacci(n: number): number {\n * // Results are cached, subsequent calls with same n are instant\n * if (n <= 1) return n;\n * return this.fibonacci(n - 1) + this.fibonacci(n - 2);\n * }\n * }\n * ```\n */\nfunction memoize(options = {}) {\n const { keyGenerator = (...args) => JSON.stringify(args), maxSize = 100, ttl } = options;\n return function (originalMethod, context) {\n const methodName = context.name;\n return function (...args) {\n if (!this[MEMOIZE_CACHE]) {\n this[MEMOIZE_CACHE] = {};\n }\n if (!this[MEMOIZE_CACHE][methodName]) {\n this[MEMOIZE_CACHE][methodName] = new Map();\n }\n const cache = this[MEMOIZE_CACHE][methodName];\n const key = keyGenerator(...args);\n // Check if cached\n if (cache.has(key)) {\n const cached = cache.get(key);\n const expired = ttl !== undefined && (Date.now() - cached.timestamp) > ttl;\n if (expired) {\n cache.delete(key);\n }\n else {\n return cached.value;\n }\n }\n // Compute result\n const result = originalMethod.apply(this, args);\n // Store in cache\n cache.set(key, {\n value: result,\n timestamp: Date.now(),\n });\n // Enforce max size (LRU - delete oldest)\n if (cache.size > maxSize) {\n const firstKey = cache.keys().next().value;\n cache.delete(firstKey);\n }\n return result;\n };\n };\n}\n/**\n * Clear all debounce timers for an instance\n * Useful in cleanup/disconnectedCallback\n */\nfunction clearDebounceTimers(instance) {\n if (instance[DEBOUNCE_TIMERS]) {\n for (const timerKey in instance[DEBOUNCE_TIMERS]) {\n if (instance[DEBOUNCE_TIMERS][timerKey]?.timeout) {\n clearTimeout(instance[DEBOUNCE_TIMERS][timerKey].timeout);\n }\n }\n instance[DEBOUNCE_TIMERS] = {};\n }\n}\n/**\n * Clear all throttle timers for an instance\n * Useful in cleanup/disconnectedCallback\n */\nfunction clearThrottleTimers(instance) {\n if (instance[THROTTLE_TIMERS]) {\n for (const timerKey in instance[THROTTLE_TIMERS]) {\n if (instance[THROTTLE_TIMERS][timerKey]?.timeout) {\n clearTimeout(instance[THROTTLE_TIMERS][timerKey].timeout);\n }\n }\n instance[THROTTLE_TIMERS] = {};\n }\n}\n/**\n * Clear memoize cache for an instance\n */\nfunction clearMemoizeCache(instance, methodName) {\n if (instance[MEMOIZE_CACHE]) {\n if (methodName) {\n delete instance[MEMOIZE_CACHE][methodName];\n }\n else {\n instance[MEMOIZE_CACHE] = {};\n }\n }\n}\n/**\n * Reset once-called state for an instance\n */\nfunction resetOnce(instance, methodName) {\n if (instance[ONCE_CALLED]) {\n if (methodName) {\n delete instance[ONCE_CALLED][methodName];\n }\n else {\n instance[ONCE_CALLED] = {};\n }\n }\n}\n\nfunction isPlainObject(value) {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\nfunction descriptorsEqual(first, second) {\n if (!first || !second)\n return first === second;\n const firstIsData = 'value' in first || 'writable' in first;\n const secondIsData = 'value' in second || 'writable' in second;\n return firstIsData === secondIsData &&\n first.configurable === second.configurable &&\n first.enumerable === second.enumerable &&\n (!firstIsData || (first.writable === second.writable &&\n Object.is(first.value, second.value))) &&\n (firstIsData || (first.get === second.get &&\n first.set === second.set));\n}\nfunction invariantValue(target, property) {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, property);\n if (!descriptor || descriptor.configurable)\n return { locked: false, value: undefined };\n if ('value' in descriptor && descriptor.writable === false) {\n return { locked: true, value: descriptor.value };\n }\n if (!('value' in descriptor) && descriptor.get === undefined) {\n return { locked: true, value: undefined };\n }\n return { locked: false, value: undefined };\n}\n/**\n * Wrap mutable collection/object state so nested writes can invalidate a\n * component without requiring a replacement assignment.\n */\nfunction createDeepReactive(value, changed) {\n if (!value || typeof value !== 'object')\n return value;\n const cache = new WeakMap();\n const rawByProxy = new WeakMap();\n const unwrap = (input) => input && typeof input === 'object'\n ? rawByProxy.get(input) || input\n : input;\n const wrap = (input) => {\n if (!input || typeof input !== 'object')\n return input;\n if (cache.has(input))\n return cache.get(input);\n if (input instanceof Map) {\n let proxy;\n const methods = new Map();\n proxy = new Proxy(input, {\n get(target, property) {\n const invariant = invariantValue(target, property);\n if (invariant.locked)\n return invariant.value;\n if (methods.has(property))\n return methods.get(property);\n let method;\n if (property === 'set')\n method = (key, next) => {\n key = unwrap(key);\n next = unwrap(next);\n const existed = target.has(key);\n const previous = target.get(key);\n target.set(key, next);\n if (!existed || !Object.is(previous, next))\n changed();\n return proxy;\n };\n else if (property === 'delete')\n method = (key) => {\n key = unwrap(key);\n const deleted = target.delete(key);\n if (deleted)\n changed();\n return deleted;\n };\n else if (property === 'clear')\n method = () => {\n if (target.size === 0)\n return;\n target.clear();\n changed();\n };\n else if (property === 'get')\n method = (key) => wrap(target.get(unwrap(key)));\n else if (property === 'has')\n method = (key) => target.has(unwrap(key));\n else if (property === 'forEach')\n method = (callback, thisArg) => target.forEach((entryValue, key) => callback.call(thisArg, wrap(entryValue), wrap(key), proxy));\n else if (property === 'values')\n method = function* () {\n for (const entryValue of target.values())\n yield wrap(entryValue);\n };\n else if (property === 'keys')\n method = function* () {\n for (const key of target.keys())\n yield wrap(key);\n };\n else if (property === 'entries' || property === Symbol.iterator)\n method = function* () {\n for (const [key, entryValue] of target.entries())\n yield [wrap(key), wrap(entryValue)];\n };\n else {\n const value = Reflect.get(target, property, target);\n if (typeof value !== 'function')\n return value;\n if (property === 'constructor')\n return value;\n method = value.bind(target);\n }\n methods.set(property, method);\n return method;\n }\n });\n cache.set(input, proxy);\n rawByProxy.set(proxy, input);\n return proxy;\n }\n if (input instanceof Set) {\n let proxy;\n const methods = new Map();\n proxy = new Proxy(input, {\n get(target, property) {\n const invariant = invariantValue(target, property);\n if (invariant.locked)\n return invariant.value;\n if (methods.has(property))\n return methods.get(property);\n let method;\n if (property === 'add')\n method = (entryValue) => {\n entryValue = unwrap(entryValue);\n const existed = target.has(entryValue);\n target.add(entryValue);\n if (!existed)\n changed();\n return proxy;\n };\n else if (property === 'delete')\n method = (entryValue) => {\n entryValue = unwrap(entryValue);\n const deleted = target.delete(entryValue);\n if (deleted)\n changed();\n return deleted;\n };\n else if (property === 'clear')\n method = () => {\n if (target.size === 0)\n return;\n target.clear();\n changed();\n };\n else if (property === 'has')\n method = (entryValue) => target.has(unwrap(entryValue));\n else if (property === 'forEach')\n method = (callback, thisArg) => target.forEach(entryValue => {\n const wrapped = wrap(entryValue);\n callback.call(thisArg, wrapped, wrapped, proxy);\n });\n else if (property === 'values' || property === 'keys' || property === Symbol.iterator)\n method = function* () {\n for (const entryValue of target.values())\n yield wrap(entryValue);\n };\n else if (property === 'entries')\n method = function* () {\n for (const entryValue of target.values()) {\n const wrapped = wrap(entryValue);\n yield [wrapped, wrapped];\n }\n };\n else {\n const value = Reflect.get(target, property, target);\n if (typeof value !== 'function')\n return value;\n if (property === 'constructor')\n return value;\n method = value.bind(target);\n }\n methods.set(property, method);\n return method;\n }\n });\n cache.set(input, proxy);\n rawByProxy.set(proxy, input);\n return proxy;\n }\n if (!Array.isArray(input) && !isPlainObject(input))\n return input;\n const proxy = new Proxy(input, {\n get(target, property, receiver) {\n const invariant = invariantValue(target, property);\n return invariant.locked\n ? invariant.value\n : wrap(Reflect.get(target, property, receiver));\n },\n set(target, property, next, receiver) {\n const previous = Reflect.get(target, property, receiver);\n next = unwrap(next);\n // Write directly to the wrapped target. Passing the proxy as the\n // receiver re-enters defineProperty for an ordinary assignment and\n // would report the same mutation twice.\n const result = Reflect.set(target, property, next);\n if (result && !Object.is(previous, next))\n changed();\n return result;\n },\n deleteProperty(target, property) {\n const existed = Object.prototype.hasOwnProperty.call(target, property);\n const result = Reflect.deleteProperty(target, property);\n if (result && existed)\n changed();\n return result;\n },\n defineProperty(target, property, descriptor) {\n const previous = Reflect.getOwnPropertyDescriptor(target, property);\n const nextDescriptor = 'value' in descriptor\n ? { ...descriptor, value: unwrap(descriptor.value) }\n : descriptor;\n const result = Reflect.defineProperty(target, property, nextDescriptor);\n const current = result ? Reflect.getOwnPropertyDescriptor(target, property) : previous;\n if (result && !descriptorsEqual(previous, current))\n changed();\n return result;\n }\n });\n cache.set(input, proxy);\n rawByProxy.set(proxy, input);\n return proxy;\n };\n return wrap(value);\n}\n\n/**\n * Applies core element functionality to a constructor\n * This is shared between @element and @page decorators\n */\nfunction applyElementFunctionality(constructor) {\n // Mark as element class for channel decorator detection\n constructor.prototype[IS_ELEMENT_CLASS] = true;\n // Add controller property to all elements\n const originalConnectedCallback = constructor.prototype.connectedCallback;\n const originalDisconnectedCallback = constructor.prototype.disconnectedCallback;\n const originalAttributeChangedCallback = constructor.prototype.attributeChangedCallback;\n // Add 'controller' and all reflected properties to observed attributes\n const observedAttributes = constructor.observedAttributes || [];\n if (!observedAttributes.includes('controller')) {\n observedAttributes.push('controller');\n }\n // Add all properties to observed attributes (skip attribute: false)\n const properties = constructor[PROPERTIES];\n if (properties) {\n for (const [propName, propOptions] of properties) {\n if (propOptions.attribute === false)\n continue;\n const attributeName = getAttrName(propOptions, propName);\n if (!observedAttributes.includes(attributeName)) {\n observedAttributes.push(attributeName);\n }\n }\n }\n Object.defineProperty(constructor, 'observedAttributes', {\n get() { return observedAttributes; },\n configurable: true\n });\n // Add ready property - always returns a promise\n Object.defineProperty(constructor.prototype, 'ready', {\n get() {\n if (!this[READY_PROMISE]) {\n // Create a pending promise if not yet initialized\n this[READY_PROMISE] = new Promise((resolve) => {\n this[READY_RESOLVE] = resolve;\n });\n }\n return this[READY_PROMISE];\n },\n enumerable: true,\n configurable: true\n });\n // Add rendered property - resolves when the pending render (batched,\n // debounced, or throttled) has committed to the DOM; resolves\n // immediately when no render is pending.\n Object.defineProperty(constructor.prototype, 'rendered', {\n get() {\n return this[RENDERED_RESOLVE] ? this[RENDERED_PROMISE] : Promise.resolve();\n },\n enumerable: true,\n configurable: true\n });\n // Add controller property\n Object.defineProperty(constructor.prototype, 'controller', {\n get() {\n return this[CONTROLLER];\n },\n set(value) {\n const oldValue = this[CONTROLLER];\n this[CONTROLLER] = value;\n if (value === oldValue)\n return;\n if (value) {\n const label = typeof value === 'string' ? value : (value.name || '(anonymous controller class)');\n attachController(this, value).catch(error => {\n // Detached before ready — designed teardown, not a failure\n if (error?.name === 'ControllerAttachAborted') {\n console.debug(`Controller \"${label}\" attach aborted (element detached before ready)`);\n return;\n }\n // Registry misses only apply to string names — class references\n // never go through the registry.\n if (typeof value === 'string' && error?.message === `Controller \"${value}\" not found in registry`) {\n deferControllerAttachment(this, value);\n return;\n }\n console.error(`Failed to attach controller \"${label}\":`, error);\n });\n return;\n }\n if (oldValue) {\n detachController(this).catch(error => {\n console.error(`Failed to detach controller:`, error);\n });\n }\n },\n enumerable: true,\n configurable: true\n });\n constructor.prototype.connectedCallback = async function () {\n // If ready promise was already created (controller attached before connected), use existing resolve\n // Otherwise create the ready promise now\n if (!this[READY_PROMISE]) {\n this[READY_PROMISE] = new Promise((resolve) => {\n this[READY_RESOLVE] = resolve;\n });\n }\n // Only run initialization logic once, but re-establish handlers on reconnection\n if (this[INITIALIZED]) {\n try {\n reconnectRenderTree(this);\n }\n catch (error) {\n console.error(`Error reconnecting the render tree for ${this.tagName}:`, error);\n }\n // Re-establish handlers that get cleaned up on disconnect\n setupEventHandlers(this, this);\n setupResponseHandlers(this, this);\n setupContextHandler(this);\n // Re-establish observers that get cleaned up on disconnect\n try {\n setupObservers(this, this);\n }\n catch (error) {\n console.error(`Error setting up observers for ${this.tagName} on reconnection:`, error);\n }\n // Call user's connectedCallback\n if (originalConnectedCallback) {\n originalConnectedCallback.call(this);\n }\n // Fire @reconnect handlers — for components that wire long-lived\n // global listeners or subscriptions in @ready and need to re-establish\n // them on re-connection. @ready does NOT re-fire (deliberately, to\n // preserve once-only initialization semantics).\n const reconnectHandlers = constructor[RECONNECT_HANDLERS];\n if (reconnectHandlers) {\n for (const handler of reconnectHandlers) {\n try {\n const result = handler.method.call(this);\n if (result && typeof result.then === 'function') {\n result.catch(error => {\n console.error(`Error in @reconnect handler ${handler.methodName}:`, error);\n });\n }\n }\n catch (error) {\n console.error(`Error in @reconnect handler ${handler.methodName}:`, error);\n }\n }\n }\n // Replay a render that was dropped while disconnected. The scheduler\n // sets this flag when it skips a detached element, so a property changed\n // while detached still reaches the DOM on reattach. A plain move (no\n // pending render) leaves the flag unset, so we don't re-render needlessly.\n if (this[RENDER_METHOD] && this[PENDING_RECONNECT_RENDER]) {\n this[PENDING_RECONNECT_RENDER] = false;\n requestRender(this);\n }\n return;\n }\n // Mark that properties are being initialized from attributes\n // This allows property setters to work during initialization\n this[PROPERTIES_INITIALIZED] = true;\n // Initialize properties from attributes before rendering\n const properties = constructor[PROPERTIES];\n if (properties) {\n for (const [propName, propOptions] of properties) {\n if (propOptions.attribute === false)\n continue;\n const attributeName = getAttrName(propOptions, propName);\n if (!this.hasAttribute(attributeName))\n continue;\n const attrValue = this.getAttribute(attributeName);\n ensureSet(this, EXPLICITLY_SET_PROPERTIES).add(propName);\n if (propOptions.type === Boolean && attrValue === '') {\n this.setAttribute(attributeName, 'true');\n }\n this[propName] = parseAttributeValue(attrValue, propOptions);\n }\n }\n // Clear pre-init values for properties that have HTML attributes\n if (this[PRE_INIT_PROPERTY_VALUES]) {\n for (const [propName, propValue] of Array.from(this[PRE_INIT_PROPERTY_VALUES].entries())) {\n const propOptions = properties?.get(propName);\n const attributeName = getAttrName(propOptions || {}, propName);\n this[PRE_INIT_PROPERTY_VALUES].delete(propName);\n if (!this.hasAttribute(attributeName)) {\n this[propName] = propValue;\n }\n }\n delete this[PRE_INIT_PROPERTY_VALUES];\n }\n // Pick up a controller CLASS a template bound before this element was\n // defined. The binding parks the class instead of assigning the\n // property — a pre-upgrade assignment would have shadowed this accessor\n // with an own expando property. Attach directly rather than through the\n // `controller` accessor: some DOM implementations (happy-dom) invoke\n // connectedCallback on define without swapping the prototype, so the\n // accessor may not exist on this instance yet.\n if (this[PENDING_CONTROLLER_BINDING] !== undefined) {\n const pendingControllerClass = this[PENDING_CONTROLLER_BINDING];\n delete this[PENDING_CONTROLLER_BINDING];\n if (!this[CONTROLLER]) {\n this[CONTROLLER] = pendingControllerClass;\n const pendingLabel = pendingControllerClass?.name || '(anonymous controller class)';\n attachController(this, pendingControllerClass).catch((error) => {\n if (error?.name === 'ControllerAttachAborted') {\n console.debug(`Controller \"${pendingLabel}\" attach aborted (element detached before ready)`);\n return;\n }\n console.error(`Failed to attach controller \"${pendingLabel}\":`, error);\n });\n }\n }\n // Pick up a `controller` attribute set before connection. Real browsers\n // fire attributeChangedCallback on connect for all observed attrs that\n // already existed; happy-dom doesn't always, so we read it proactively.\n if (this.hasAttribute('controller') && !this[CONTROLLER]) {\n const controllerName = this.getAttribute('controller');\n if (controllerName)\n this.controller = controllerName;\n }\n applyStyles(this);\n setupEventHandlers(this, this);\n setupResponseHandlers(this, this);\n setupContextHandler(this);\n this[INITIALIZED] = true;\n // One-time (per class) sanity check: a @watch name with no matching\n // @property never fires — surface the typo instead of staying silent.\n validateWatchedProperties(this, constructor);\n // Now that the initial value is settled, give @watch immediate handlers\n // their one init call (before the first render, so derived state is ready).\n invokeImmediateWatchers(this, constructor);\n if (originalConnectedCallback) {\n originalConnectedCallback.call(this);\n }\n // v4.16.1: Render, run @ready handlers, THEN resolve .ready promise\n // This ensures `await el.ready` waits for both initial render AND all async @ready() methods\n //\n // We await a microtask boundary (to defer render for parent property bindings),\n // then run render + @ready handlers sequentially, then resolve .ready.\n const readyHandlers = constructor[READY_HANDLERS];\n // Await one microtask to defer initial render (allows parent property bindings)\n await new Promise(r => queueMicrotask(r));\n // If the element was removed during the microtask gap, don't render,\n // don't run @ready on an orphan. Resolve ready so any awaiters don't\n // hang — the element exists, it just isn't in the DOM.\n if (!this.isConnected) {\n if (this[READY_RESOLVE]) {\n this[READY_RESOLVE]();\n this[READY_RESOLVE] = null;\n }\n return;\n }\n if (this[RENDER_METHOD]) {\n requestRender(this, true);\n }\n // Setup observers after render so shadow DOM content exists\n try {\n setupObservers(this, this);\n }\n catch (error) {\n console.error(`Error setting up observers for ${this.tagName}:`, error);\n }\n // Yield a microtask so child elements' microtask-deferred renders\n // complete before @ready handlers run. Children queued their render\n // microtask when they connected (earlier in the queue), so they\n // drain before this one.\n await new Promise(r => queueMicrotask(r));\n // Element may have been removed during the second microtask gap.\n if (!this.isConnected) {\n if (this[READY_RESOLVE]) {\n this[READY_RESOLVE]();\n this[READY_RESOLVE] = null;\n }\n return;\n }\n // Run @ready handlers serially, awaiting each\n if (readyHandlers) {\n for (const handler of readyHandlers) {\n try {\n await handler.method.call(this);\n }\n catch (error) {\n console.error(`Error in @ready handler ${handler.methodName}:`, error);\n }\n }\n }\n // NOW resolve — render done AND all @ready handlers complete\n if (this[READY_RESOLVE]) {\n this[READY_RESOLVE]();\n this[READY_RESOLVE] = null;\n }\n };\n constructor.prototype.disconnectedCallback = async function () {\n try {\n disconnectRenderTree(this);\n }\n catch (error) {\n console.error(`Error disconnecting the render tree for ${this.tagName}:`, error);\n }\n // Call @dispose handlers\n const disposeHandlers = constructor[DISPOSE_HANDLERS];\n if (disposeHandlers) {\n for (const handler of disposeHandlers) {\n try {\n await handler.method.call(this);\n }\n catch (error) {\n console.error(`Error in @dispose handler ${handler.methodName}:`, error);\n }\n }\n }\n // Call original user-defined disconnectedCallback\n if (originalDisconnectedCallback) {\n originalDisconnectedCallback.call(this);\n }\n if (this[CONTROLLER]) {\n detachController(this).catch(error => {\n console.error(`Failed to detach controller:`, error);\n });\n }\n // Cleanup @on event handlers (v2.5.4 compatibility restored!)\n cleanupEventHandlers(this);\n // Cleanup @respond handlers\n cleanupResponseHandlers(this);\n // Cleanup @context handler\n cleanupContextHandler(this);\n // Cleanup @observe observers\n cleanupObservers(this);\n // Cleanup pending @debounce / @throttle timers so they don't fire on a dead element\n clearDebounceTimers(this);\n clearThrottleTimers(this);\n // The render/dispatch debounce-throttle timers live in separate stores.\n // A pending render is replayed on reconnect (same flag the scheduler\n // uses); a pending dispatch is a one-shot signal, so it's dropped.\n if (clearRenderTimers(this)) {\n this[PENDING_RECONNECT_RENDER] = true;\n }\n clearDispatchTimers(this);\n // @moved / @adopted debounce-throttle timers, likewise dropped so they\n // don't fire on a dead element.\n clearLifecycleTimers(this, MOVED_TIMERS);\n clearLifecycleTimers(this, ADOPTED_TIMERS);\n };\n constructor.prototype.attributeChangedCallback = function (name, oldValue, newValue) {\n originalAttributeChangedCallback?.call(this, name, oldValue, newValue);\n if (name === 'controller') {\n this.controller = newValue;\n return;\n }\n const properties = constructor[PROPERTIES];\n if (!properties)\n return;\n for (const [propName, propOptions] of properties) {\n const attributeName = getAttrName(propOptions, propName);\n if (attributeName.toLowerCase() !== name.toLowerCase())\n continue;\n // A property-originated reflection already stored the authoritative\n // JS value. Do not parse the serialized attribute back into a clone.\n if (this[SETTING_FROM_PROPERTY]?.has(name.toLowerCase()))\n break;\n const currentValue = this[PROPERTY_VALUES]?.[propName];\n // A removed attribute reverts the property to its field default. Read it\n // back through the getter (attribute is already gone at this point) so the\n // watcher's newValue and PROPERTY_VALUES match what this[propName] now\n // returns — parseAttributeValue(null) would diverge to null for String/Number.\n const defaultValue = this[PROPERTY_DEFAULTS]?.[propName];\n let parsedValue = newValue === null\n ? (propOptions.type === Boolean ? false : defaultValue)\n : parseAttributeValue(newValue, propOptions, currentValue, defaultValue);\n const wrap = this[PROPERTY_WRAPPERS]?.[propName];\n if (wrap)\n parsedValue = wrap(parsedValue);\n const changed = propOptions?.hasChanged\n ? propOptions.hasChanged(parsedValue, currentValue)\n : notEqual(parsedValue, currentValue);\n if (!changed)\n break;\n ensureSet(this, EXPLICITLY_SET_PROPERTIES).add(propName);\n ensureObj(this, PROPERTY_VALUES)[propName] = parsedValue;\n // Watchers react to changes only. During upgrade the initial value\n // is not a change, so suppress until INITIALIZED; @watch immediate\n // handlers get their one init call from invokeImmediateWatchers.\n if (this[INITIALIZED]) {\n invokeWatchers(this, constructor, propName, currentValue, parsedValue);\n }\n if (this[RENDER_METHOD] && this[INITIALIZED]) {\n requestRender(this);\n }\n break;\n }\n };\n // Add connectedMoveCallback for handling DOM moves\n constructor.prototype.connectedMoveCallback = async function () {\n // Call @moved handlers via the prototype method (the debounce/throttle\n // wrapper), not the raw handler — otherwise @moved({debounce}) options\n // are ignored for real moves and only work when called directly.\n const movedHandlers = constructor[MOVED_HANDLERS];\n if (movedHandlers) {\n for (const handler of movedHandlers) {\n try {\n await this[handler.methodName]();\n }\n catch (error) {\n console.error(`Error in @moved handler ${handler.methodName}:`, error);\n }\n }\n }\n };\n // Add adoptedCallback for handling document adoption\n constructor.prototype.adoptedCallback = async function () {\n // Call @adopted handlers via the prototype method (the debounce/throttle\n // wrapper), not the raw handler — same reason as connectedMoveCallback.\n const adoptedHandlers = constructor[ADOPTED_HANDLERS];\n if (adoptedHandlers) {\n for (const handler of adoptedHandlers) {\n try {\n await this[handler.methodName]();\n }\n catch (error) {\n console.error(`Error in @adopted handler ${handler.methodName}:`, error);\n }\n }\n }\n };\n}\n/**\n * Walk the prototype chain and merge parent element metadata into the child.\n * Called once at class definition time — zero per-instance cost.\n * Skips plain HTMLElement (no metadata to merge).\n *\n * Only merges PROPERTIES (stored via context.metadata at decoration time)\n * and formAssociated. Other handler registrations (@watch, @on, @ready, etc.)\n * inherit automatically via TC39 addInitializer — parent initializers run\n * during child instance construction.\n */\nfunction mergeParentMetadata(constructor) {\n let parent = Object.getPrototypeOf(constructor);\n // Collect ancestors bottom-up, then merge top-down so the deepest parent goes first\n const ancestors = [];\n while (parent && parent !== HTMLElement && parent !== Function.prototype) {\n ancestors.push(parent);\n parent = Object.getPrototypeOf(parent);\n }\n ancestors.reverse();\n for (const ancestor of ancestors) {\n // Properties (Map) — parent first, child overrides\n if (ancestor[PROPERTIES]) {\n if (!constructor[PROPERTIES])\n constructor[PROPERTIES] = new Map();\n for (const [key, value] of ancestor[PROPERTIES]) {\n if (!constructor[PROPERTIES].has(key)) {\n constructor[PROPERTIES].set(key, value);\n }\n }\n }\n // formAssociated — inherit if parent is form-associated\n if (ancestor.formAssociated && !constructor.formAssociated) {\n constructor.formAssociated = true;\n }\n }\n}\nfunction defineElement(tagName, constructor, context, options) {\n // Merge metadata from parent @element classes (inheritance support)\n mergeParentMetadata(constructor);\n if (context.metadata && context.metadata[PROPERTIES]) {\n if (!constructor[PROPERTIES])\n constructor[PROPERTIES] = new Map();\n for (const [key, value] of context.metadata[PROPERTIES]) {\n constructor[PROPERTIES].set(key, value);\n }\n }\n else if (_pendingProperties.length > 0) {\n // Symbol.metadata unavailable — drain the pending stack\n if (!constructor[PROPERTIES])\n constructor[PROPERTIES] = new Map();\n const pending = _pendingProperties.pop();\n for (const [key, value] of pending) {\n constructor[PROPERTIES].set(key, value);\n }\n }\n if (options?.formAssociated)\n constructor.formAssociated = true;\n const inheritedOptions = {\n ...(Object.getPrototypeOf(constructor)?.[ELEMENT_OPTIONS] || {})\n };\n const ownOptions = options || {};\n if (ownOptions.renderRoot === 'light' && typeof ownOptions.shadow === 'string' ||\n ownOptions.renderRoot === 'shadow' && ownOptions.shadow === false) {\n throw new TypeError('snice: @element renderRoot and shadow options select conflicting render roots.');\n }\n const mergedOptions = { ...inheritedOptions, ...ownOptions };\n if (Object.prototype.hasOwnProperty.call(ownOptions, 'shadow')) {\n mergedOptions.renderRoot = ownOptions.shadow === false ? 'light' : 'shadow';\n }\n else if (Object.prototype.hasOwnProperty.call(ownOptions, 'renderRoot')) {\n if (ownOptions.renderRoot === 'light')\n mergedOptions.shadow = false;\n else if (mergedOptions.shadow === false)\n mergedOptions.shadow = 'open';\n }\n constructor[ELEMENT_OPTIONS] = mergedOptions;\n if (constructor.prototype[SNICE_ELEMENT_BASE] === true &&\n Object.prototype.hasOwnProperty.call(constructor.prototype, 'render') &&\n !Object.prototype.hasOwnProperty.call(constructor.prototype, RENDER_METHOD) &&\n typeof constructor.prototype.render === 'function') {\n constructor.prototype[RENDER_METHOD] = constructor.prototype.render;\n constructor.prototype[RENDER_OPTIONS] = constructor.renderOptions || {};\n }\n applyElementFunctionality(constructor);\n if (customElements.get(tagName)) {\n if (globalThis.SNICE_DEBUG)\n console.warn(`[snice] \"${tagName}\" is already registered. Skipping.`);\n return constructor;\n }\n customElements.define(tagName, constructor);\n return constructor;\n}\nfunction element(tagName, options) {\n if (options?.renderRoot !== undefined && options.renderRoot !== 'shadow' && options.renderRoot !== 'light') {\n throw new TypeError('snice: @element renderRoot must be \"shadow\" or \"light\".');\n }\n if (options?.shadow !== undefined && options.shadow !== false &&\n options.shadow !== 'open' && options.shadow !== 'closed') {\n throw new TypeError('snice: @element shadow must be \"open\", \"closed\", or false.');\n }\n return function (constructor, context) {\n return defineElement(tagName, constructor, context, options);\n };\n}\nfunction layout(tagName) {\n return function (constructor, context) {\n return defineElement(tagName, constructor, context);\n };\n}\n// Fallback stack for environments where Symbol.metadata is unavailable.\n// @property pushes entries; @element pops them. Works because field decorators\n// run synchronously before the class decorator in the same static block.\nconst _pendingProperties = [];\nconst nativeOwnPropertyDefaults = new WeakMap();\nfunction isNativeOwnPropertyDefault(instance, propertyKey, value) {\n const ownerDocument = instance?.ownerDocument;\n if (!ownerDocument?.createElement)\n return false;\n let defaults = nativeOwnPropertyDefaults.get(ownerDocument);\n if (!defaults) {\n const nativeElement = ownerDocument.createElement('div');\n defaults = new Map();\n for (const key of Reflect.ownKeys(nativeElement))\n defaults.set(key, nativeElement[key]);\n nativeOwnPropertyDefaults.set(ownerDocument, defaults);\n }\n return defaults.has(propertyKey) && Object.is(defaults.get(propertyKey), value);\n}\nfunction property(options) {\n return function (_value, context) {\n const propertyKey = context.name;\n // Use metadata to store property information at decoration time\n if (context.metadata) {\n if (!context.metadata[PROPERTIES]) {\n context.metadata[PROPERTIES] = new Map();\n }\n context.metadata[PROPERTIES].set(propertyKey, options || {});\n }\n else {\n // Symbol.metadata unavailable — use the pending stack instead\n if (_pendingProperties.length === 0)\n _pendingProperties.push(new Map());\n _pendingProperties[_pendingProperties.length - 1].set(propertyKey, options || {});\n }\n return function (initialValue) {\n // A property binding can run while this is still an unupgraded custom\n // element, creating an own data property. Preserve that value across the\n // upgrade, but remove the expando before the decorated field initializer\n // is assigned so the assignment replays through the reactive accessor.\n const markedBindings = this[PRE_UPGRADE_PROPERTY_BINDINGS];\n const wasTemplateBoundBeforeUpgrade = markedBindings?.delete(propertyKey) === true;\n if (markedBindings?.size === 0)\n delete this[PRE_UPGRADE_PROPERTY_BINDINGS];\n const hasOwnValue = Object.prototype.hasOwnProperty.call(this, propertyKey);\n const hadPreUpgradeValue = hasOwnValue && (wasTemplateBoundBeforeUpgrade || !isNativeOwnPropertyDefault(this, propertyKey, this[propertyKey]));\n const preUpgradeValue = hadPreUpgradeValue ? this[propertyKey] : initialValue;\n if (hasOwnValue)\n delete this[propertyKey];\n const constructor = this.constructor;\n if (!constructor[PROPERTIES])\n constructor[PROPERTIES] = new Map();\n const finalOptions = { ...options };\n if (!finalOptions.type && initialValue !== undefined)\n finalOptions.type = detectType(initialValue);\n if (!finalOptions.attributeNaming && constructor.propertyAttributeNaming === 'kebab') {\n finalOptions.attributeNaming = 'kebab';\n }\n constructor[PROPERTIES].set(propertyKey, finalOptions);\n ensureObj(this, PROPERTY_DEFAULTS)[propertyKey] = initialValue;\n const notifyDeepMutation = () => {\n if (!this[PROPERTIES_INITIALIZED])\n return;\n const current = this[PROPERTY_VALUES]?.[propertyKey];\n if (finalOptions.attribute !== false && finalOptions.reflect !== false) {\n const attributeName = getAttrName(finalOptions, propertyKey);\n const attributeValue = valueToAttribute(current, finalOptions, initialValue);\n const attrKey = attributeName.toLowerCase();\n ensureSet(this, SETTING_FROM_PROPERTY).add(attrKey);\n try {\n if (attributeValue === null)\n this.removeAttribute?.(attributeName);\n else\n this.setAttribute?.(attributeName, attributeValue);\n }\n finally {\n this[SETTING_FROM_PROPERTY].delete(attrKey);\n }\n }\n if (this[INITIALIZED]) {\n invokeWatchers(this, this.constructor, propertyKey, current, current);\n if (this[RENDER_METHOD])\n requestRender(this);\n }\n };\n const wrap = (value) => {\n if (!finalOptions.deep)\n return value;\n let wrapped;\n wrapped = createDeepReactive(value, () => {\n // A caller may retain an old proxied object after replacing the\n // property. Mutating that detached graph must not invalidate the\n // component or notify watchers for the current value.\n if (this[PROPERTY_VALUES]?.[propertyKey] !== wrapped)\n return;\n notifyDeepMutation();\n });\n return wrapped;\n };\n ensureObj(this, PROPERTY_WRAPPERS)[propertyKey] = wrap;\n const proto = this.constructor.prototype;\n let definers = proto[PROPERTY_DEFINERS];\n if (!definers || !Object.prototype.hasOwnProperty.call(proto, PROPERTY_DEFINERS)) {\n definers = new Map(definers);\n proto[PROPERTY_DEFINERS] = definers;\n }\n const existingDefiner = definers.get(propertyKey);\n if (!existingDefiner || existingDefiner !== options) {\n definers.set(propertyKey, options);\n Object.defineProperty(this.constructor.prototype, propertyKey, {\n get() {\n if (this[PRE_INIT_PROPERTY_VALUES]?.has(propertyKey)) {\n return this[PRE_INIT_PROPERTY_VALUES].get(propertyKey);\n }\n if (this[PROPERTY_VALUES] && propertyKey in this[PROPERTY_VALUES]) {\n return this[PROPERTY_VALUES][propertyKey];\n }\n return initialValue;\n },\n set(incomingValue) {\n const oldValue = this[propertyKey];\n const changed = finalOptions.hasChanged\n ? finalOptions.hasChanged(incomingValue, oldValue)\n : notEqual(incomingValue, oldValue);\n if (!changed)\n return;\n const instanceWrap = this[PROPERTY_WRAPPERS]?.[propertyKey] || ((value) => value);\n // Property assignments are already typed JavaScript values and\n // remain the source of truth. `type` and `converter.fromAttribute`\n // apply only at the string attribute boundary; coercing here would\n // destroy object identity and turn valid union values (for example\n // `Date | ''` or `string | string[]`) into the wrong type.\n const newValue = instanceWrap(incomingValue);\n if (!this[PROPERTIES_INITIALIZED]) {\n if (!this[PRE_INIT_PROPERTY_VALUES])\n this[PRE_INIT_PROPERTY_VALUES] = new Map();\n this[PRE_INIT_PROPERTY_VALUES].set(propertyKey, newValue);\n return;\n }\n ensureObj(this, PROPERTY_VALUES)[propertyKey] = newValue;\n if (finalOptions.attribute !== false && finalOptions.reflect !== false) {\n const attributeName = getAttrName(finalOptions, propertyKey);\n const attributeValue = valueToAttribute(newValue, finalOptions, this[PROPERTY_DEFAULTS]?.[propertyKey]);\n ensureSet(this, EXPLICITLY_SET_PROPERTIES).add(propertyKey);\n const attrKey = attributeName.toLowerCase();\n ensureSet(this, SETTING_FROM_PROPERTY).add(attrKey);\n try {\n if (attributeValue === null)\n this.removeAttribute?.(attributeName);\n else\n this.setAttribute?.(attributeName, attributeValue);\n }\n finally {\n this[SETTING_FROM_PROPERTY].delete(attrKey);\n }\n }\n if (this[INITIALIZED]) {\n invokeWatchers(this, this.constructor, propertyKey, oldValue, newValue);\n if (this[RENDER_METHOD])\n requestRender(this);\n }\n },\n configurable: true,\n enumerable: true\n });\n }\n const wrappedInitialValue = wrap(initialValue);\n ensureObj(this, PROPERTY_VALUES)[propertyKey] = wrappedInitialValue;\n ensureObj(this, PROPERTY_DEFAULTS)[propertyKey] = wrappedInitialValue;\n return hadPreUpgradeValue ? preUpgradeValue : wrappedInitialValue;\n };\n };\n}\n/** Internal reactive state: never reads from or reflects to an attribute. */\nfunction state(options = {}) {\n return property({ ...options, attribute: false, reflect: false });\n}\nfunction getQueryRoot(instance) {\n const isController = instance[IS_CONTROLLER_INSTANCE] === true;\n return isController && instance.element ? instance.element : instance;\n}\nfunction query(selector, options = {}) {\n return function (_value, context) {\n const { light = false, shadow = true } = options;\n const propertyKey = context.name;\n return function (initialValue) {\n if (!Object.hasOwn(this.constructor.prototype, propertyKey)) {\n Object.defineProperty(this.constructor.prototype, propertyKey, {\n get() {\n const root = getQueryRoot(this);\n let result = null;\n const managedRoot = root instanceof HTMLElement ? getRenderRoot(root) : null;\n if (shadow && managedRoot)\n result = managedRoot.querySelector(selector);\n else if (shadow && root.shadowRoot)\n result = root.shadowRoot.querySelector(selector);\n if (!result && light)\n result = root.querySelector(selector);\n return result || null;\n },\n set() { },\n configurable: true,\n enumerable: true\n });\n }\n return initialValue;\n };\n };\n}\nfunction queryAll(selector, options = {}) {\n return function (_value, context) {\n const { light = false, shadow = true } = options;\n const propertyKey = context.name;\n return function (initialValue) {\n if (!Object.hasOwn(this.constructor.prototype, propertyKey)) {\n Object.defineProperty(this.constructor.prototype, propertyKey, {\n get() {\n const root = getQueryRoot(this);\n const results = new Set();\n const managedRoot = root instanceof HTMLElement ? getRenderRoot(root) : null;\n if (shadow && managedRoot) {\n for (const match of managedRoot.querySelectorAll(selector))\n results.add(match);\n }\n else if (shadow && root.shadowRoot) {\n for (const match of root.shadowRoot.querySelectorAll(selector))\n results.add(match);\n }\n if (light) {\n for (const match of root.querySelectorAll(selector))\n results.add(match);\n }\n return [...results];\n },\n set() { },\n configurable: true,\n enumerable: true\n });\n }\n return initialValue;\n };\n };\n}\nfunction watch(...args) {\n // A trailing options object is separated from the watched property names.\n const propertyNames = args.filter((a) => typeof a === 'string');\n const options = args.find((a) => typeof a === 'object' && a !== null);\n // Fire on init by default; opt out of the init call with { immediate: false }.\n const immediate = options?.immediate !== false;\n return function (target, context) {\n const methodName = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // Dedup by (method reference, propertyName) so that multiple @watch\n // decorators on the same method register for each key independently,\n // while still preventing duplicate registration when child classes\n // inherit/override a method with the same name. Use hasOwnProperty so\n // subclasses get their OWN Map — otherwise child pushes into the\n // parent's PROPERTY_WATCHERS via the prototype chain.\n if (!Object.prototype.hasOwnProperty.call(constructor, WATCH_METHODS)) {\n constructor[WATCH_METHODS] = new Map();\n }\n let registered = constructor[WATCH_METHODS].get(target);\n if (!registered) {\n registered = new Set();\n constructor[WATCH_METHODS].set(target, registered);\n }\n if (!Object.prototype.hasOwnProperty.call(constructor, PROPERTY_WATCHERS)) {\n // Deep-copy the inherited Map so the child starts with the parent's\n // watchers but pushing to a propertyName's array on the child doesn't\n // mutate the parent's array.\n const inherited = constructor[PROPERTY_WATCHERS];\n const copy = new Map();\n if (inherited) {\n for (const [key, arr] of inherited)\n copy.set(key, [...arr]);\n }\n constructor[PROPERTY_WATCHERS] = copy;\n }\n for (const propertyName of propertyNames) {\n if (registered.has(propertyName))\n continue;\n registered.add(propertyName);\n if (!constructor[PROPERTY_WATCHERS].has(propertyName)) {\n constructor[PROPERTY_WATCHERS].set(propertyName, []);\n }\n constructor[PROPERTY_WATCHERS].get(propertyName).push({\n methodName,\n method: target,\n immediate\n });\n }\n });\n };\n}\n/**\n * Decorator that injects router context into a property\n * The context is automatically provided to page components by the router\n */\nfunction context() {\n return function (_value, context) {\n const propertyKey = context.name;\n // Return a field initializer function for new decorators\n return function (initialValue) {\n // Set up the property descriptor on first access\n if (!Object.hasOwn(this.constructor.prototype, propertyKey)) {\n const descriptor = {\n get() {\n // Cached context\n if (this[ROUTER_CONTEXT] !== undefined) {\n return this[ROUTER_CONTEXT];\n }\n // Resolve dispatch target\n const isController = this[IS_CONTROLLER_INSTANCE] === true;\n let targetElement = isController && this.element ? this.element : this;\n // Controller was detached\n if (!targetElement || !targetElement.dispatchEvent)\n return undefined;\n // Shadow DOM: dispatch on host for proper bubbling\n if (targetElement.getRootNode && targetElement.getRootNode() instanceof ShadowRoot) {\n targetElement = targetElement.getRootNode().host;\n }\n // Request context from parent page\n const detail = { target: this };\n targetElement.dispatchEvent(new CustomEvent('@context/request', {\n bubbles: true,\n cancelable: true,\n detail\n }));\n // No context provided\n if (detail.context === undefined)\n return undefined;\n // Cache and return\n this[ROUTER_CONTEXT] = detail.context;\n return detail.context;\n },\n set() {\n // Context is read-only\n },\n configurable: true,\n enumerable: true\n };\n Object.defineProperty(this.constructor.prototype, propertyKey, descriptor);\n }\n return initialValue;\n };\n };\n}\nfunction registerHandler(handlersSymbol, methodsSymbol, target, context, extra) {\n const methodName = context.name;\n context.addInitializer(function () {\n const constructor = this.constructor;\n // hasOwnProperty guards so subclasses get their OWN Set/array instead of\n // mutating the parent's via the prototype chain.\n if (!Object.prototype.hasOwnProperty.call(constructor, methodsSymbol)) {\n constructor[methodsSymbol] = new Set();\n }\n if (constructor[methodsSymbol].has(target))\n return;\n constructor[methodsSymbol].add(target);\n if (!Object.prototype.hasOwnProperty.call(constructor, handlersSymbol)) {\n const inherited = constructor[handlersSymbol];\n constructor[handlersSymbol] = inherited ? [...inherited] : [];\n }\n constructor[handlersSymbol].push({ methodName, method: target, ...extra });\n });\n}\nfunction ready() {\n return function (target, context) {\n registerHandler(READY_HANDLERS, READY_METHODS, target, context);\n };\n}\nfunction dispose() {\n return function (target, context) {\n registerHandler(DISPOSE_HANDLERS, DISPOSE_METHODS, target, context);\n };\n}\n/**\n * Fires every time the element is connected AFTER the first connect.\n *\n * `@ready` only fires once (after the initial render). `@dispose` fires on\n * every disconnect. The gap between them is \"what should run on a\n * reconnect?\" For most components, framework-managed pieces (`@on`,\n * `@observe`, `@respond`, `@context`) are re-established automatically\n * and nothing else is needed.\n *\n * Use `@reconnect` only when the component wires its OWN long-lived global\n * subscription in `@ready` (e.g. a `document.addEventListener` for\n * outside-click detection) and tears it down in `@dispose`. The framework\n * doesn't track those, so they need a hook to re-attach on reconnect.\n *\n * Counterpart to `@dispose`. Symmetric.\n */\nfunction reconnect() {\n return function (target, context) {\n registerHandler(RECONNECT_HANDLERS, RECONNECT_METHODS, target, context);\n };\n}\n/**\n * Clear any pending @moved / @adopted debounce/throttle timers on an instance\n * (e.g. on disconnect), so they don't fire on a dead element.\n */\nfunction clearLifecycleTimers(instance, timersSymbol) {\n const map = instance[timersSymbol];\n if (!map)\n return;\n for (const t of map.values()) {\n if (t.debounceTimer)\n clearTimeout(t.debounceTimer);\n if (t.throttleTimer)\n clearTimeout(t.throttleTimer);\n t.debounceTimer = null;\n t.throttleTimer = null;\n t.lastThrottleCall = 0;\n }\n}\nfunction createLifecycleDecorator(handlersSymbol, timersSymbol, methodsSymbol) {\n return function (options = {}) {\n return function (originalMethod, context) {\n registerHandler(handlersSymbol, methodsSymbol, originalMethod, context, { options });\n const methodName = context.name;\n return function (...args) {\n if (!this[timersSymbol])\n this[timersSymbol] = new Map();\n if (!this[timersSymbol].has(methodName)) {\n this[timersSymbol].set(methodName, { throttleTimer: null, debounceTimer: null, lastThrottleCall: 0 });\n }\n const timers = this[timersSymbol].get(methodName);\n const exec = (...a) => originalMethod.apply(this, a);\n // Deferred (debounce/throttle) calls run inside a setTimeout, outside\n // the caller's try/catch — so catch their sync throws and async\n // rejections here and log, rather than surface an uncaught error.\n const execDeferred = (...a) => {\n try {\n const result = originalMethod.apply(this, a);\n if (result && typeof result.then === 'function') {\n result.catch((error) => console.error(`Error in deferred lifecycle handler ${methodName}:`, error));\n }\n }\n catch (error) {\n console.error(`Error in deferred lifecycle handler ${methodName}:`, error);\n }\n };\n if (options.debounce > 0) {\n clearTimeout(timers.debounceTimer);\n timers.debounceTimer = setTimeout(() => execDeferred(...args), options.debounce);\n return undefined;\n }\n if (options.throttle > 0) {\n const now = Date.now();\n if (timers.lastThrottleCall === 0 || now - timers.lastThrottleCall >= options.throttle) {\n timers.lastThrottleCall = now;\n return exec(...args);\n }\n if (!timers.throttleTimer) {\n const remaining = options.throttle - (now - timers.lastThrottleCall);\n timers.throttleTimer = setTimeout(() => {\n timers.throttleTimer = null;\n timers.lastThrottleCall = Date.now();\n execDeferred(...args);\n }, remaining);\n }\n return undefined;\n }\n return exec(...args);\n };\n };\n };\n}\nconst moved = createLifecycleDecorator(MOVED_HANDLERS, MOVED_TIMERS, MOVED_METHODS);\nconst adopted = createLifecycleDecorator(ADOPTED_HANDLERS, ADOPTED_TIMERS, ADOPTED_METHODS);\n\n/**\n * Optional authoring base for convention-driven Snice components.\n *\n * Decorators remain fully supported on plain HTMLElement subclasses. Extending\n * this class adds typed lifecycle promises, imperative invalidation, modern\n * kebab-case implicit attributes, and `render()` / static `styles` conventions.\n */\nclass SniceElement extends HTMLElement {\n static { this.propertyAttributeNaming = 'kebab'; }\n createRenderRoot() {\n const options = this.constructor[ELEMENT_OPTIONS];\n const mode = typeof options?.shadow === 'string' ? options.shadow : 'open';\n return this.attachShadow({ mode, delegatesFocus: options?.delegatesFocus });\n }\n invalidate() {\n requestRender(this);\n return this.rendered;\n }\n renderNow() {\n renderElementNow(this);\n return this.rendered;\n }\n}\n// `@element` uses this inherited marker to enable render() conventions only\n// for the opt-in base class. Plain HTMLElement components may legitimately\n// have imperative helper methods named render().\nObject.defineProperty(SniceElement.prototype, SNICE_ELEMENT_BASE, { value: true });\n\n/*!\n * pica-route v1.1.2\n * A pure URL pattern matching library compatible with route-parser API\n * (c) 2024\n * Released under the MIT License.\n */\nclass Route {\n constructor(pattern) {\n this.parsed = this.parsePattern(pattern);\n }\n get spec() {\n return this.parsed.template;\n }\n parsePattern(pattern) {\n // Handle optional query syntax (?query=:param)\n let pathPattern = pattern;\n let queryPattern = '';\n let queryOptional = false;\n const queryIndex = pattern.indexOf('?');\n if (queryIndex !== -1) {\n pathPattern = pattern.slice(0, queryIndex);\n queryPattern = pattern.slice(queryIndex + 1);\n // Check if query is wrapped in optional syntax (?...)\n if (pathPattern.endsWith('(') && queryPattern.endsWith(')')) {\n queryOptional = true;\n pathPattern = pathPattern.slice(0, -1);\n queryPattern = queryPattern.slice(0, -1);\n }\n }\n return {\n pathSegments: this.parseSegments(pathPattern),\n querySegments: queryPattern ? this.parseQuerySegments(queryPattern) : [],\n queryOptional,\n template: pattern\n };\n }\n parseSegments(pattern) {\n const segments = [];\n let i = 0;\n while (i < pattern.length) {\n const char = pattern[i];\n switch (char) {\n case '(':\n // Parse optional group\n const { segments: optionalSegments, endIndex } = this.parseOptionalGroup(pattern, i);\n segments.push({ type: 'optional', segments: optionalSegments });\n i = endIndex + 1;\n break;\n case ':':\n // Parse parameter\n const { name, endIndex: paramEndIndex } = this.parseIdentifier(pattern, i + 1);\n segments.push({ type: 'param', name });\n i = paramEndIndex;\n break;\n case '*':\n // Parse splat\n const { name: splatName, endIndex: splatEndIndex } = this.parseIdentifier(pattern, i + 1);\n segments.push({ type: 'splat', name: splatName });\n i = splatEndIndex;\n break;\n default:\n // Parse literal text\n const { value, endIndex: literalEndIndex } = this.parseLiteral(pattern, i);\n if (value) {\n segments.push({ type: 'literal', value });\n }\n i = literalEndIndex;\n break;\n }\n }\n return segments;\n }\n parseOptionalGroup(pattern, startIndex) {\n let depth = 1;\n let i = startIndex + 1;\n while (i < pattern.length && depth > 0) {\n if (pattern[i] === '(')\n depth++;\n if (pattern[i] === ')')\n depth--;\n i++;\n }\n const content = pattern.slice(startIndex + 1, i - 1);\n return {\n segments: this.parseSegments(content),\n endIndex: i - 1\n };\n }\n parseIdentifier(pattern, startIndex) {\n let i = startIndex;\n while (i < pattern.length && /[\\w-]/.test(pattern[i])) {\n i++;\n }\n return {\n name: pattern.slice(startIndex, i),\n endIndex: i\n };\n }\n parseLiteral(pattern, startIndex) {\n let i = startIndex;\n while (i < pattern.length && !'(:*('.includes(pattern[i])) {\n i++;\n }\n return {\n value: pattern.slice(startIndex, i),\n endIndex: i\n };\n }\n parseQuerySegments(queryPattern) {\n // Remove optional group syntax wrapping the query\n let cleanPattern = queryPattern;\n if (cleanPattern.startsWith('(') && cleanPattern.endsWith(')')) {\n cleanPattern = cleanPattern.slice(1, -1);\n }\n const segments = [];\n let i = 0;\n while (i < cleanPattern.length) {\n switch (cleanPattern[i]) {\n case ':':\n const { name, endIndex } = this.parseIdentifier(cleanPattern, i + 1);\n segments.push({ type: 'param', name });\n i = endIndex;\n break;\n default:\n const { value, endIndex: literalEndIndex } = this.parseQueryLiteral(cleanPattern, i);\n if (value) {\n segments.push({ type: 'literal', value });\n }\n i = literalEndIndex;\n break;\n }\n }\n return segments;\n }\n parseQueryLiteral(pattern, startIndex) {\n let i = startIndex;\n while (i < pattern.length && pattern[i] !== ':') {\n i++;\n }\n return {\n value: pattern.slice(startIndex, i),\n endIndex: i\n };\n }\n getAllParamNames() {\n const paramNames = new Set();\n const collectParams = (segments) => {\n for (const segment of segments) {\n switch (segment.type) {\n case 'param':\n case 'splat':\n paramNames.add(segment.name);\n break;\n case 'optional':\n collectParams(segment.segments);\n break;\n }\n }\n };\n collectParams(this.parsed.pathSegments);\n collectParams(this.parsed.querySegments);\n return Array.from(paramNames);\n }\n canMatchRemainingSegments(path, startIndex, segments) {\n // Quick check: try to match the remaining segments\n // This is a simplified check - we just look for literal segments that must exist\n let pathIndex = startIndex;\n for (const segment of segments) {\n if (segment.type === 'literal') {\n const literalIndex = path.indexOf(segment.value, pathIndex);\n if (literalIndex === -1) {\n return false; // Required literal not found\n }\n pathIndex = literalIndex + segment.value.length;\n }\n // For optional, param, and splat segments, we're more permissive in this quick check\n }\n return true;\n }\n match(url) {\n const [pathPart, queryPart] = url.split('?');\n const pathParams = this.matchPath(pathPart, this.parsed.pathSegments);\n if (pathParams === false) {\n return false;\n }\n const queryParams = this.matchQuery(queryPart || '', this.parsed.querySegments);\n if (queryParams === false) {\n return false;\n }\n // Initialize result with all optional parameters set to undefined\n const allParams = this.getAllParamNames();\n const result = {};\n // Set all parameters to undefined initially\n for (const paramName of allParams) {\n result[paramName] = undefined;\n }\n // Override with actual matched values\n Object.assign(result, pathParams, queryParams);\n return result;\n }\n matchPath(path, segments) {\n const result = {};\n let pathIndex = 0;\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const remainingSegments = segments.slice(i + 1);\n const matchResult = this.matchSegment(path, pathIndex, segment, remainingSegments);\n if (matchResult === false) {\n return false;\n }\n Object.assign(result, matchResult.params);\n pathIndex = matchResult.nextIndex;\n }\n // Check if we've consumed the entire path\n if (pathIndex < path.length) {\n return false;\n }\n return result;\n }\n matchSegment(path, startIndex, segment, remainingSegments = []) {\n switch (segment.type) {\n case 'literal':\n if (path.slice(startIndex, startIndex + segment.value.length) === segment.value) {\n return { params: {}, nextIndex: startIndex + segment.value.length };\n }\n return false;\n case 'param': {\n let endIndex = startIndex;\n // Check if the next segment is a literal and find where it starts\n const nextSegment = remainingSegments[0];\n let stopChars = ['/', '?'];\n if (nextSegment && nextSegment.type === 'literal') {\n // For parameters followed by literals, we need to find where the literal starts\n const literalValue = nextSegment.value;\n const literalStart = path.indexOf(literalValue, startIndex);\n if (literalStart !== -1) {\n endIndex = literalStart;\n }\n else {\n // Literal not found, this parameter can't match\n return false;\n }\n }\n else {\n // Default behavior - stop at / or ?\n while (endIndex < path.length && !stopChars.includes(path[endIndex])) {\n endIndex++;\n }\n }\n if (endIndex === startIndex)\n return false;\n let value;\n try {\n value = decodeURIComponent(path.slice(startIndex, endIndex));\n }\n catch (e) {\n // If decoding fails, use the original value\n value = path.slice(startIndex, endIndex);\n }\n // If we hit a query string, we should reject this match for path parameters\n if (endIndex < path.length && path[endIndex] === '?' && remainingSegments.length > 0) {\n return false;\n }\n // Keep values as strings to match route-parser behavior\n return {\n params: { [segment.name]: value },\n nextIndex: endIndex\n };\n }\n case 'splat': {\n // For splats, we need to find the optimal stopping point by looking ahead\n let endIndex = path.length;\n const nextSegment = remainingSegments[0];\n if (nextSegment) {\n switch (nextSegment.type) {\n case 'literal':\n // For literal dots after splats, use first occurrence (for file extensions)\n // For other literals, use last occurrence\n if (nextSegment.value === '.') {\n const firstDotIndex = path.indexOf('.', startIndex);\n if (firstDotIndex !== -1) {\n endIndex = firstDotIndex;\n }\n }\n else {\n // Find the last occurrence of the next literal\n const literalIndex = path.lastIndexOf(nextSegment.value);\n if (literalIndex !== -1 && literalIndex >= startIndex) {\n endIndex = literalIndex;\n }\n }\n break;\n case 'param':\n // For parameter after splat, find the last slash\n let lastSlashIndex = -1;\n for (let i = path.length - 1; i >= startIndex; i--) {\n if (path[i] === '/') {\n lastSlashIndex = i;\n break;\n }\n }\n if (lastSlashIndex !== -1) {\n endIndex = lastSlashIndex;\n }\n break;\n case 'splat':\n // For consecutive splats, give this splat everything up to the last slash\n // The next splat gets the last component\n let lastSlash = -1;\n for (let i = path.length - 1; i > startIndex; i--) {\n if (path[i] === '/') {\n lastSlash = i + 1; // Include the slash\n break;\n }\n }\n if (lastSlash !== -1) {\n endIndex = lastSlash;\n }\n else {\n // No slash found, this splat gets everything except the last component\n const pathSegments = path.slice(startIndex).split('/').filter(s => s);\n if (pathSegments.length > 1) {\n endIndex = startIndex + pathSegments.slice(0, -1).join('/').length + 1;\n }\n else {\n endIndex = startIndex; // Give nothing to this splat\n }\n }\n break;\n case 'optional':\n // Look for literals inside optional groups\n const findFirstLiteral = (segs) => {\n for (const seg of segs) {\n if (seg.type === 'literal')\n return seg.value;\n if (seg.type === 'optional') {\n const nested = findFirstLiteral(seg.segments);\n if (nested)\n return nested;\n }\n }\n return null;\n };\n const firstLiteral = findFirstLiteral(nextSegment.segments);\n if (firstLiteral) {\n const literalIndex = path.lastIndexOf(firstLiteral);\n if (literalIndex !== -1 && literalIndex >= startIndex) {\n endIndex = literalIndex;\n }\n }\n break;\n }\n }\n // Don't go past query parameters\n const queryIndex = path.indexOf('?', startIndex);\n if (queryIndex !== -1 && queryIndex < endIndex) {\n endIndex = queryIndex;\n }\n let value;\n try {\n value = decodeURIComponent(path.slice(startIndex, endIndex));\n }\n catch (e) {\n // If decoding fails, use the original value\n value = path.slice(startIndex, endIndex);\n }\n return {\n params: { [segment.name]: value },\n nextIndex: endIndex\n };\n }\n case 'optional': {\n // Try to match the optional segment first, with backtracking if needed\n let tempIndex = startIndex;\n let params = {};\n let allMatched = true;\n for (let i = 0; i < segment.segments.length; i++) {\n const innerSegment = segment.segments[i];\n const remainingInner = segment.segments.slice(i + 1);\n const innerResult = this.matchSegment(path, tempIndex, innerSegment, remainingInner);\n if (innerResult === false) {\n allMatched = false;\n break;\n }\n Object.assign(params, innerResult.params);\n tempIndex = innerResult.nextIndex;\n }\n if (allMatched) {\n // Check if the rest of the segments can still be matched\n const canMatchRemaining = this.canMatchRemainingSegments(path, tempIndex, remainingSegments);\n if (canMatchRemaining) {\n return {\n params,\n nextIndex: tempIndex\n };\n }\n }\n // Optional segment either didn't match or would prevent remaining segments from matching\n // So skip it and return to original position\n return { params: {}, nextIndex: startIndex };\n }\n default:\n return false;\n }\n }\n findNextLiteral(segments) {\n for (const segment of segments) {\n if (segment.type === 'literal') {\n return segment;\n }\n else if (segment.type === 'optional') {\n const nested = this.findNextLiteral(segment.segments);\n if (nested)\n return nested;\n }\n }\n return null;\n }\n matchQuery(query, segments) {\n if (segments.length === 0) {\n return {};\n }\n const result = {};\n let queryIndex = 0;\n for (const segment of segments) {\n switch (segment.type) {\n case 'literal':\n if (query.slice(queryIndex, queryIndex + segment.value.length) === segment.value) {\n queryIndex += segment.value.length;\n }\n else {\n return false;\n }\n break;\n case 'param': {\n let endIndex = queryIndex;\n while (endIndex < query.length && query[endIndex] !== '&') {\n endIndex++;\n }\n if (endIndex === queryIndex)\n return false;\n let value;\n try {\n value = decodeURIComponent(query.slice(queryIndex, endIndex));\n }\n catch (e) {\n // If decoding fails, use the original value\n value = query.slice(queryIndex, endIndex);\n }\n result[segment.name] = value;\n queryIndex = endIndex;\n break;\n }\n }\n }\n return result;\n }\n reverse(params = {}) {\n const pathResult = this.reverseSegments(this.parsed.pathSegments, params);\n if (pathResult === false) {\n return false;\n }\n let result = pathResult;\n if (this.parsed.querySegments.length > 0) {\n const queryResult = this.reverseSegments(this.parsed.querySegments, params);\n if (!this.parsed.queryOptional) {\n // Query is required - if it fails, the whole reverse fails\n if (queryResult === false) {\n return false;\n }\n }\n // Add query string if we have a result\n if (queryResult && queryResult !== '') {\n result += '?' + queryResult;\n }\n }\n return result;\n }\n reverseSegments(segments, params, inActivatedStructure = false) {\n let result = '';\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const remainingSegments = segments.slice(i + 1);\n switch (segment.type) {\n case 'literal':\n result += segment.value;\n break;\n case 'param':\n case 'splat':\n if (segment.name in params) {\n result += String(params[segment.name]);\n }\n else {\n // Missing required parameter - but for query segments, this might be optional\n return false;\n }\n break;\n case 'optional':\n // Check if this optional group should be included\n // considering dependencies from later optional groups\n const shouldInclude = this.hasAllParams(segment.segments, params, inActivatedStructure) ||\n this.hasLaterOptionalGroupNeedingParams(remainingSegments, params, segment.segments);\n if (shouldInclude) {\n const optionalResult = this.reverseSegments(segment.segments, params, true);\n if (optionalResult === false) {\n return false;\n }\n result += optionalResult;\n }\n break;\n }\n }\n return result;\n }\n // Check if any later optional groups need parameters and would require this group to be included\n hasLaterOptionalGroupNeedingParams(laterSegments, params, currentOptionalSegments) {\n // Check if any later optional group has parameters that are provided\n for (const segment of laterSegments) {\n if (segment.type === 'optional') {\n if (this.hasAnyParamInSegments(segment.segments, params)) {\n // Check if the current optional group only has literals/no required params\n // If so, it should be included as a bridge to the later group\n return this.hasOnlyLiteralsAndOptionals(currentOptionalSegments);\n }\n }\n }\n return false;\n }\n hasOnlyLiteralsAndOptionals(segments) {\n for (const segment of segments) {\n if (segment.type === 'param' || segment.type === 'splat') {\n return false;\n }\n }\n return true;\n }\n hasAllParams(segments, params, inActivatedStructure = false) {\n // Check if we can include this optional group\n let hasDirectParams = false;\n let hasNestedParams = false;\n let missingDirectParam = false;\n let hasOnlyLiteralsAndOptionals = true;\n // First pass: check direct params and literals\n for (const segment of segments) {\n switch (segment.type) {\n case 'param':\n case 'splat':\n hasOnlyLiteralsAndOptionals = false;\n if (segment.name in params && params[segment.name] !== undefined) {\n hasDirectParams = true;\n }\n else {\n missingDirectParam = true;\n }\n break;\n }\n }\n // Determine if this level will be activated and propagate to nested\n const willBeActivated = (hasDirectParams && !missingDirectParam);\n const passToNested = inActivatedStructure || willBeActivated;\n // Second pass: check nested optional groups with correct context\n for (const segment of segments) {\n if (segment.type === 'optional') {\n const shouldIncludeNested = this.hasAllParams(segment.segments, params, passToNested);\n if (shouldIncludeNested) {\n hasNestedParams = true;\n }\n }\n }\n // Include this optional group if:\n // 1. We have all direct parameters needed, OR\n // 2. We have nested parameters and no missing direct parameters, OR\n // 3. We have only literals/optionals and parent was activated\n if (hasDirectParams && !missingDirectParam) {\n return true; // We have all required params for this level\n }\n if (hasNestedParams && !missingDirectParam) {\n return true; // We need this group to reach nested parameters\n }\n // Include literal-only groups in nested structures\n if (hasOnlyLiteralsAndOptionals && inActivatedStructure) {\n return true; // Include literal paths in activated structures\n }\n return false;\n }\n hasOnlyOptionalMissingParams(segments, params) {\n // Check if all missing parameters are in nested optional groups\n for (const segment of segments) {\n switch (segment.type) {\n case 'param':\n case 'splat':\n if (!(segment.name in params)) {\n return false; // Has required missing param\n }\n break;\n }\n }\n return true;\n }\n hasAnyParamInSegments(segments, params) {\n for (const segment of segments) {\n switch (segment.type) {\n case 'param':\n case 'splat':\n if (segment.name in params) {\n return true;\n }\n break;\n case 'optional':\n if (this.hasAnyParamInSegments(segment.segments, params)) {\n return true;\n }\n break;\n }\n }\n return false;\n }\n}\n\n/**\n * Score a route pattern by specificity so that more specific routes are tried\n * first. Scoring is per-segment by ROLE, not by string length: a static segment\n * outweighs a dynamic (`:param`) segment, which outweighs a wildcard (`*` /\n * `*name`). So `/post/new` beats `/post/:id`, and a splat always ranks last —\n * regardless of how long the pattern string happens to be. This mirrors the\n * segment-scoring model mainstream routers (React Router, Remix) use.\n *\n * Sort callers descending by this score (highest = most specific = first).\n *\n * NOTE: mirrored in `src/react/route-specificity.ts` for the isolated React\n * bundle — keep the two in sync.\n */\nconst STATIC_SEGMENT = 10;\nconst DYNAMIC_SEGMENT = 3;\nconst WILDCARD_SEGMENT = -2;\nfunction routeSpecificity(spec) {\n const segments = spec.split('/').filter(Boolean);\n // Base on segment count so a deeper path outranks a shallower one on ties.\n let score = segments.length;\n for (const segment of segments) {\n if (segment.startsWith('*')) {\n score += WILDCARD_SEGMENT;\n }\n else if (segment.startsWith(':')) {\n score += DYNAMIC_SEGMENT;\n }\n else {\n score += STATIC_SEGMENT;\n }\n }\n return score;\n}\n\n/**\n * Generic transition system for animating between elements\n */\n/**\n * Parse CSS property string into an object\n */\nfunction parseStyles(styleString) {\n const styles = {};\n styleString.split(';').forEach(rule => {\n const idx = rule.indexOf(':');\n if (idx === -1)\n return;\n const prop = rule.slice(0, idx).trim();\n const value = rule.slice(idx + 1).trim();\n if (prop && value) {\n styles[prop] = value;\n }\n });\n return styles;\n}\n/**\n * Perform a transition between two elements\n */\nfunction applyBaseTransitionStyles(el, isSlotted, duration, prop) {\n el.style.position = 'absolute';\n el.style.width = '100%';\n if (isSlotted) {\n el.style.height = '100%';\n el.style.transition = `opacity ${duration}ms ease-in-out`;\n return;\n }\n el.style.top = '0';\n el.style.left = '0';\n el.style.transition = `${prop} ${duration}ms ease-in-out`;\n}\nfunction resetTransitionStyles(el, isSlotted) {\n el.style.position = '';\n el.style.width = '';\n el.style.transition = '';\n if (isSlotted) {\n el.style.height = '';\n return;\n }\n el.style.top = '';\n el.style.left = '';\n}\nasync function performTransition(container, oldElement, newElement, transition = {}, \n/**\n * Called at each async boundary — if it returns true, this transition has\n * been superseded by a newer navigation. We abort cleanup so we don't tear\n * down elements now owned by the newer transition.\n */\nisStale = () => false) {\n const outDuration = transition.outDuration ?? 300;\n const inDuration = transition.inDuration ?? 300;\n const mode = (transition.mode || 'sequential');\n const outStyles = transition.out ? parseStyles(transition.out) : { opacity: '0' };\n const inStartStyles = { opacity: '0' };\n const inEndStyles = transition.in ? parseStyles(transition.in) : { opacity: '1' };\n const containerStyle = container.style;\n const isLayoutElement = container.tagName.includes('-') && container.shadowRoot;\n // Track the position we were ORIGINALLY given, not what a concurrent\n // transition may have already written. The first transition to touch this\n // container wins; subsequent overlapping transitions reuse the same value\n // and the last one to finish restores it.\n const POS_KEY = Symbol.for('snice:transition-original-position');\n const POS_COUNT = Symbol.for('snice:transition-count');\n const c = container;\n if (!isLayoutElement) {\n if (!(POS_KEY in c)) {\n c[POS_KEY] = containerStyle.position;\n c[POS_COUNT] = 0;\n }\n c[POS_COUNT]++;\n containerStyle.position = 'relative';\n }\n const restorePosition = () => {\n if (isLayoutElement)\n return;\n c[POS_COUNT]--;\n if (c[POS_COUNT] <= 0) {\n containerStyle.position = c[POS_KEY];\n delete c[POS_KEY];\n delete c[POS_COUNT];\n }\n };\n const isSlotted = oldElement.hasAttribute('slot') || newElement.hasAttribute('slot');\n applyBaseTransitionStyles(oldElement, isSlotted, outDuration, 'all');\n applyBaseTransitionStyles(newElement, isSlotted, inDuration, 'all');\n Object.assign(newElement.style, inStartStyles);\n container.appendChild(newElement);\n void newElement.offsetHeight;\n // Animate\n switch (mode) {\n case TransitionMode.SIMULTANEOUS:\n Object.assign(oldElement.style, outStyles);\n Object.assign(newElement.style, inEndStyles);\n await new Promise(resolve => setTimeout(resolve, Math.max(outDuration, inDuration)));\n break;\n case TransitionMode.SEQUENTIAL:\n Object.assign(oldElement.style, outStyles);\n await new Promise(resolve => setTimeout(resolve, outDuration));\n if (isStale()) {\n if (newElement.parentNode === container)\n newElement.remove();\n restorePosition();\n return;\n }\n Object.assign(newElement.style, inEndStyles);\n await new Promise(resolve => setTimeout(resolve, inDuration));\n break;\n }\n if (isStale()) {\n // A newer navigation took over while we were animating. Don't touch\n // oldElement (the newer transition owns it now) and remove OUR newElement\n // since the newer transition appended its own.\n if (newElement.parentNode === container)\n newElement.remove();\n restorePosition();\n return;\n }\n // Cleanup\n oldElement.remove();\n resetTransitionStyles(newElement, isSlotted);\n Object.keys({ ...inStartStyles, ...inEndStyles }).forEach(prop => {\n newElement.style[prop] = '';\n });\n restorePosition();\n}\n\n/**\n * Possible outcomes from route resolution\n */\nvar RouteResult;\n(function (RouteResult) {\n RouteResult[\"SUCCESS\"] = \"success\";\n RouteResult[\"GUARDS_FAILED\"] = \"guards-failed\";\n RouteResult[\"NOT_FOUND\"] = \"not-found\";\n})(RouteResult || (RouteResult = {}));\n/**\n * Creates a new router instance.\n * @param {RouterOptions} options - The router configuration options.\n * @returns An object containing the router's API methods.\n */\nfunction Router(options) {\n const win = options.window ?? window;\n const doc = options.document ?? document;\n const routes = [];\n let is_sorted = false;\n let placards = []; // Store collected placards\n let _404; // the 404 page\n let _403; // the 403 forbidden page\n let home; // the home page\n let currentLayoutName = null; // Track current layout name\n let currentLayoutTimestamp = null; // Track current layout timestamp\n const context = options.context || {}; // Store context for guards\n // Create Context instance for managing router state\n const navigationContext = new Context(context, [], '', {}, options.fetcher);\n function getCurrentLayoutElement(target) {\n const noCurrentLayout = !currentLayoutName || !currentLayoutTimestamp;\n if (noCurrentLayout) {\n return null;\n }\n const layoutElements = target.querySelectorAll(currentLayoutName);\n for (const element of layoutElements) {\n const hasTimestamp = element[CREATED_AT] === currentLayoutTimestamp;\n if (hasTimestamp) {\n return element;\n }\n }\n return null;\n }\n /**\n * Decorator function for defining a page with associated routes.\n * @param {PageOptions} pageOptions - The page configuration options.\n * @returns A decorator function to apply to a custom element class.\n */\n function page(pageOptions) {\n return function (constructor, context) {\n // Transfer metadata from context to constructor (for new decorators)\n if (context?.metadata && context.metadata[PROPERTIES]) {\n if (!constructor[PROPERTIES]) {\n constructor[PROPERTIES] = new Map();\n }\n for (const [key, value] of context.metadata[PROPERTIES]) {\n constructor[PROPERTIES].set(key, value);\n }\n }\n // Apply all element functionality (properties, queries, watchers, controllers, etc.)\n applyElementFunctionality(constructor);\n // Store transition config on constructor for later use\n constructor[PAGE_TRANSITION] = pageOptions.transition;\n // Extend the connectedCallback to add router-specific functionality\n const elementConnectedCallback = constructor.prototype.connectedCallback;\n constructor.prototype.connectedCallback = function () {\n // Store the Context instance for @context decorated methods to access\n this[CONTEXT_HANDLER] = navigationContext;\n // Call the element's connectedCallback first\n elementConnectedCallback?.call(this);\n };\n // Extend the disconnectedCallback to clean up router-specific stuff\n const elementDisconnectedCallback = constructor.prototype.disconnectedCallback;\n constructor.prototype.disconnectedCallback = function () {\n // Call element's disconnectedCallback first\n elementDisconnectedCallback?.call(this);\n // Clean up context references\n delete this[ROUTER_CONTEXT];\n delete this[CONTEXT_HANDLER];\n };\n // Define the custom element (skip if already registered)\n if (!win.customElements.get(pageOptions.tag)) {\n win.customElements.define(pageOptions.tag, constructor);\n }\n // Register the routes with guards, layout, and placard\n pageOptions.routes.forEach(route => register(route, pageOptions.tag, pageOptions.transition, pageOptions.guards, pageOptions.layout, pageOptions.placard));\n return constructor;\n };\n }\n /**\n * Registers a new route with the router.\n * @param {string} route - The route path.\n * @param {string} tag - The custom element tag associated with the route.\n * @example\n * register('/custom-route', 'custom-element');\n */\n function register(route, tag, transition, guards, layout, placard) {\n routes.push({ route: new Route(route), tag, transition, guards, layout, placard });\n is_sorted = false;\n switch (route) {\n case '/404':\n _404 = tag;\n break;\n case '/403':\n _403 = tag;\n break;\n case '/':\n home = tag;\n break;\n }\n }\n function setupEventListeners() {\n const handler = () => {\n if (!doc.querySelector(options.target))\n return;\n navigate(getPath());\n };\n switch (options.type) {\n case 'hash':\n win.addEventListener('hashchange', handler);\n break;\n case 'pushstate':\n win.addEventListener('popstate', handler);\n break;\n }\n }\n /**\n * Initializes the router and sets up navigation event listeners.\n * @example\n * initialize();\n */\n function initialize() {\n const target = doc.querySelector(options.target);\n if (!target) {\n throw new Error(`Target element not found: ${options.target}`);\n }\n const needsSorting = !is_sorted;\n if (needsSorting) {\n routes.sort((a, b) => routeSpecificity(b.route.spec) - routeSpecificity(a.route.spec));\n is_sorted = true;\n }\n // Collect placards from registered routes\n collectPlacards();\n setupEventListeners();\n const path = getPath();\n navigate(path);\n }\n function collectPlacards() {\n const seen = new Set();\n placards = routes\n .filter(route => route.placard)\n .map(route => {\n const placard = route.placard;\n return typeof placard === 'function'\n ? placard(context)\n : placard;\n })\n .filter(p => {\n if (seen.has(p.name))\n return false;\n seen.add(p.name);\n return true;\n });\n }\n function emitContextUpdate(target, currentPath, routeParams) {\n // Update the navigation context and notify all registered elements\n navigationContext[CONTEXT_UPDATE](context, placards, currentPath, routeParams);\n }\n function updateLayout(layoutElement, currentPath, routeParams) {\n // Check if layout implements the update method\n if (typeof layoutElement.update === 'function') {\n layoutElement.update(context, placards, currentPath, routeParams);\n }\n }\n function getPath() {\n switch (options.type) {\n case 'hash':\n return win.location.hash.slice(1);\n case 'pushstate':\n return win.location.pathname;\n }\n }\n function renderForbiddenPage(target) {\n let newPageElement;\n if (_403) {\n newPageElement = doc.createElement(_403);\n newPageElement[ROUTER_CONTEXT] = context;\n }\n else {\n const div = doc.createElement('div');\n div.className = 'default-403';\n div.innerHTML = /*html*/ `<h1>403</h1><p>Unauthorized</p>`;\n newPageElement = div;\n }\n target.innerHTML = '';\n target.appendChild(newPageElement);\n currentLayoutName = null;\n currentLayoutTimestamp = null;\n }\n function createLoadingSpinner() {\n const container = doc.createElement('div');\n container.setAttribute('data-snice-loading', '');\n container.innerHTML = /*html*/ `\n <style>@keyframes snice-spin{to{transform:rotate(360deg)}}</style>\n <div style=\"display:flex;align-items:center;justify-content:center;height:100%;min-height:200px\">\n <div style=\"width:32px;height:32px;border:3px solid rgba(128,128,128,0.3);border-top-color:rgba(128,128,128,0.8);border-radius:50%;animation:snice-spin 0.6s linear infinite\"></div>\n </div>`;\n return container;\n }\n async function checkGuards(guards, params, target, stale) {\n const hasGuards = !!guards;\n if (!hasGuards) {\n return true;\n }\n const guardsArray = Array.isArray(guards) ? guards : [guards];\n let spinner = null;\n let spinnerTimer = null;\n // Show spinner after a short delay (avoids flash for fast sync guards).\n // Skip if a newer navigation has already superseded this one.\n spinnerTimer = setTimeout(() => {\n if (stale && stale())\n return;\n spinner = createLoadingSpinner();\n target.appendChild(spinner);\n }, 50);\n try {\n for (const guard of guardsArray) {\n const allowed = await guard(context, params);\n if (!allowed) {\n // Don't stomp the current page with a 403 if a newer navigation\n // already took over while this guard was resolving.\n if (!stale || !stale()) {\n renderForbiddenPage(target);\n }\n return false;\n }\n }\n return true;\n }\n finally {\n if (spinnerTimer)\n clearTimeout(spinnerTimer);\n // @ts-ignore — TS narrows spinner to never because it can't track setTimeout mutations\n if (spinner)\n spinner.remove();\n }\n }\n function createHomeElement() {\n const newPageElement = doc.createElement(home);\n newPageElement[ROUTER_CONTEXT] = context;\n const constructor = win.customElements.get(home);\n const transition = constructor?.[PAGE_TRANSITION];\n const homeRoute = routes.find(r => r.route.match('/'));\n return { element: newPageElement, transition, layout: homeRoute?.layout };\n }\n function create404Element() {\n const has404Page = !!_404;\n if (has404Page) {\n const newPageElement = doc.createElement(_404);\n newPageElement[ROUTER_CONTEXT] = context;\n const constructor = win.customElements.get(_404);\n const transition = constructor?.[PAGE_TRANSITION];\n return { element: newPageElement, transition, layout: undefined };\n }\n const div = doc.createElement('div');\n div.className = 'default-404';\n div.innerHTML = /*html*/ `<h1>404</h1><p>Page not found</p>`;\n return { element: div, transition: undefined, layout: undefined };\n }\n async function resolveRoute(path, target, stale) {\n for (const route of routes) {\n const params = route.route.match(path);\n const isMatch = params !== false;\n if (!isMatch) {\n continue;\n }\n const guardsAllowed = await checkGuards(route.guards, params, target, stale);\n if (!guardsAllowed) {\n return { result: RouteResult.GUARDS_FAILED };\n }\n const newPageElement = doc.createElement(route.tag);\n newPageElement[ROUTER_CONTEXT] = context;\n newPageElement[CONTEXT_HANDLER] = navigationContext;\n const routeParams = params;\n Object.keys(routeParams).forEach(key => newPageElement.setAttribute(key, routeParams[key]));\n return { result: RouteResult.SUCCESS, element: newPageElement, transition: route.transition, layout: route.layout, routeParams };\n }\n return { result: RouteResult.NOT_FOUND };\n }\n function determineLayout(pageLayout) {\n const isExplicitlyNoLayout = pageLayout === false;\n if (isExplicitlyNoLayout) {\n return null;\n }\n const hasPageLayout = !!pageLayout;\n if (hasPageLayout) {\n return pageLayout;\n }\n const hasRouterLayout = !!options.layout;\n if (hasRouterLayout) {\n return options.layout;\n }\n return null;\n }\n function setupLayout(layoutToUse) {\n const needsNewLayout = layoutToUse !== currentLayoutName;\n if (!needsNewLayout) {\n return { element: null, needsNewLayout: false };\n }\n currentLayoutName = layoutToUse;\n const shouldCreateLayout = !!layoutToUse;\n if (shouldCreateLayout) {\n const timestamp = Date.now();\n currentLayoutTimestamp = timestamp;\n const layoutElement = doc.createElement(layoutToUse);\n layoutElement[ROUTER_CONTEXT] = context;\n layoutElement[CREATED_AT] = timestamp;\n return { element: layoutElement, needsNewLayout: true };\n }\n currentLayoutTimestamp = null;\n return { element: null, needsNewLayout: true };\n }\n async function renderWithLayout(target, pageElement, transition, layoutElement, needsNewLayout, currentPath, routeParams, stale) {\n const currentLayout = layoutElement || getCurrentLayoutElement(target);\n if (!currentLayout) {\n return;\n }\n // Update layout with current context and placards\n updateLayout(currentLayout, currentPath, routeParams);\n const oldPageInLayout = currentLayout.querySelector('[slot=\"page\"]');\n const shouldTransition = !!(transition && oldPageInLayout);\n if (shouldTransition) {\n pageElement.setAttribute('slot', 'page');\n await performTransition$1(currentLayout, oldPageInLayout, pageElement, transition);\n if (stale && stale())\n return;\n if (needsNewLayout) {\n target.innerHTML = '';\n target.appendChild(currentLayout);\n }\n return;\n }\n // Guard before committing DOM changes.\n if (stale && stale())\n return;\n const existingPages = currentLayout.querySelectorAll('[slot=\"page\"]');\n existingPages.forEach(page => page.remove());\n pageElement.setAttribute('slot', 'page');\n currentLayout.appendChild(pageElement);\n if (needsNewLayout) {\n target.innerHTML = '';\n target.appendChild(currentLayout);\n }\n }\n async function renderDirect(target, pageElement, transition, stale) {\n const currentElementInTarget = target.children[0];\n const shouldTransition = !!(transition && currentElementInTarget);\n if (shouldTransition) {\n await performTransition$1(target, currentElementInTarget, pageElement, transition);\n return;\n }\n // Guard against superseded navigation before committing DOM.\n if (stale && stale())\n return;\n target.innerHTML = '';\n target.appendChild(pageElement);\n }\n async function renderPage(target, pageElement, transition, layout, path, routeParams, stale) {\n const layoutToUse = determineLayout(layout);\n const { element: layoutElement, needsNewLayout } = setupLayout(layoutToUse);\n const finalTransition = transition || options.transition;\n const hasLayout = layoutElement !== null || getCurrentLayoutElement(target) !== null;\n if (hasLayout) {\n await renderWithLayout(target, pageElement, finalTransition, layoutElement, needsNewLayout, path, routeParams, stale);\n if (stale && stale())\n return;\n emitContextUpdate(target, path, routeParams);\n return;\n }\n await renderDirect(target, pageElement, finalTransition, stale);\n if (stale && stale())\n return;\n emitContextUpdate(target, path, routeParams);\n }\n /**\n * Navigates to the specified path.\n * @param {string} path - The path to navigate to.\n * @example\n * navigate('/login');\n */\n let navGeneration = 0;\n async function navigate(path) {\n const target = doc.querySelector(options.target);\n if (!target) {\n throw new Error(`Target element not found: ${options.target}`);\n }\n const myGen = ++navGeneration;\n const stale = () => myGen !== navGeneration;\n collectPlacards();\n win.scrollTo(0, 0);\n // Home path\n const isHomePath = (path?.trim() === '' || path === '/') && !!home;\n if (isHomePath) {\n const homeRoute = routes.find(r => r.route.match('/'));\n if (!(await checkGuards(homeRoute?.guards, {}, target, stale)))\n return;\n if (stale())\n return;\n const { element, transition, layout } = createHomeElement();\n await renderPage(target, element, transition, layout, path, {}, stale);\n return;\n }\n // No path\n if (!path)\n return;\n // Resolve route\n const routeResult = await resolveRoute(path, target, stale);\n if (stale())\n return;\n // Guards failed (403 already rendered by checkGuards)\n if (routeResult.result === RouteResult.GUARDS_FAILED)\n return;\n // Route matched\n if (routeResult.result === RouteResult.SUCCESS) {\n const { element, transition, layout, routeParams = {} } = routeResult;\n await renderPage(target, element, transition, layout, path, routeParams, stale);\n return;\n }\n // 404 fallthrough\n const { element, transition, layout } = create404Element();\n await renderPage(target, element, transition, layout, path, {}, stale);\n }\n async function performTransition$1(container, oldElement, newElement, transition, atGen = navGeneration) {\n // `isStale` returns true when a newer navigate() has been kicked off.\n // The transition util checks this at each async boundary and bails so\n // we don't remove an element the newer transition now owns.\n const isStale = () => atGen !== navGeneration;\n return performTransition(container, oldElement, newElement, transition, isStale);\n }\n return {\n page,\n initialize,\n navigate,\n register\n };\n}\n\n/**\n * createRequestHandler — vanilla JS utility for handling @request channels\n * outside of the Snice element/controller decorator system.\n *\n * Listens for @request CustomEvents on a target element (or document),\n * performs the discovery/data handshake, and dispatches to your route map.\n *\n * @example\n * ```js\n * import { createRequestHandler } from 'snice';\n *\n * const cleanup = createRequestHandler(document, {\n * 'fetch-user': async (payload) => {\n * const res = await fetch(`/api/users/${payload.id}`);\n * return res.json();\n * },\n * 'save-settings': async (payload) => {\n * await fetch('/api/settings', { method: 'POST', body: JSON.stringify(payload) });\n * return { ok: true };\n * }\n * });\n *\n * // Later, to remove all listeners:\n * cleanup();\n * ```\n */\n/**\n * Attach request handlers to a DOM target.\n *\n * @param target The element or document to listen on. Events bubble, so an\n * ancestor element catches requests from any descendant.\n * @param routes Map of channel names to handler functions.\n * @param options Optional configuration.\n * @returns A cleanup function that removes all listeners.\n */\nfunction createRequestHandler(target, routes, options) {\n const cleanups = [];\n for (const [channelName, handler] of Object.entries(routes)) {\n const eventName = `@request/${channelName}`;\n const listener = (event) => {\n const ce = event;\n const { discovery, data, payload } = ce.detail;\n if (!options?.passive) {\n ce.preventDefault();\n ce.stopImmediatePropagation();\n ce.stopPropagation();\n }\n // Signal that we found the handler — clears discovery timeout\n discovery.resolve();\n // Execute the handler and wire up the data promise\n Promise.resolve()\n .then(() => handler(payload))\n .then((result) => data.resolve(result))\n .catch((error) => {\n data.reject(error);\n console.error(`createRequestHandler: error in \"${channelName}\" handler:`, error);\n });\n };\n target.addEventListener(eventName, listener);\n cleanups.push(() => target.removeEventListener(eventName, listener));\n }\n return () => {\n for (const fn of cleanups)\n fn();\n cleanups.length = 0;\n };\n}\n\n/**\n * Template binding helpers for class and style attributes.\n *\n * @example\n * ```typescript\n * html`<div class=\"${classMap({ box: true, 'box--active': this.active })}\"></div>`\n * html`<div style=\"${styleMap({ color: this.color, fontWeight: 'bold' })}\"></div>`\n * ```\n */\n/**\n * Build a class string from an object: keys with truthy values are included.\n */\nfunction classMap(classes) {\n let out = '';\n for (const name of Object.keys(classes)) {\n if (classes[name])\n out += (out ? ' ' : '') + name;\n }\n return out;\n}\n/**\n * Build a style string from an object. camelCase keys convert to kebab-case;\n * CSS custom properties (`--token`) pass through unchanged. Entries whose\n * value is null/undefined/false are dropped.\n */\nfunction styleMap(styles) {\n const decls = [];\n for (const key of Object.keys(styles)) {\n const value = styles[key];\n if (value === null || value === undefined || value === false)\n continue;\n const prop = key.startsWith('--')\n ? key\n : key.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());\n decls.push(`${prop}: ${value}`);\n }\n return decls.join('; ');\n}\n\n/**\n * Custom element readiness utilities\n * Handles waiting for custom elements to be defined with timeout warnings\n */\n/**\n * Global flag to disable custom element readiness timeout warnings\n * Set this to true in environments where slow element registration is expected\n */\nlet DISABLE_ELEMENT_READY_WARNINGS = false;\n/**\n * Set whether to disable custom element readiness timeout warnings\n */\nfunction setDisableElementReadyWarnings(value) {\n DISABLE_ELEMENT_READY_WARNINGS = value;\n}\n/**\n * Default timeout for custom element registration warning (500ms)\n */\nconst DEFAULT_WARNING_TIMEOUT = 500;\n/**\n * Wait for a custom element to be defined\n * Logs a warning if it takes longer than the warning timeout\n *\n * @param tagName - The custom element tag name\n * @param warningTimeout - Time in ms before warning (default 500ms)\n * @returns Promise that resolves when element is defined\n */\nasync function waitForElementDefined(tagName, warningTimeout = DEFAULT_WARNING_TIMEOUT) {\n // If already defined, return immediately\n if (customElements.get(tagName)) {\n return;\n }\n // Set up warning timer if not disabled\n let warningTimer = null;\n if (!DISABLE_ELEMENT_READY_WARNINGS) {\n warningTimer = setTimeout(() => {\n console.warn(`Custom element <${tagName}> is taking longer than ${warningTimeout}ms to register. ` +\n `This may indicate a missing import or circular dependency. ` +\n `Set DISABLE_ELEMENT_READY_WARNINGS=true to disable this warning.`);\n }, warningTimeout);\n }\n try {\n // Wait for element to be defined\n await customElements.whenDefined(tagName);\n }\n finally {\n // Clear warning timer\n if (warningTimer) {\n clearTimeout(warningTimer);\n }\n }\n}\n/**\n * Wait for a custom element to be defined and ready\n * First waits for the element to be registered, then waits for its ready promise\n *\n * @param element - The custom element instance\n * @param warningTimeout - Time in ms before warning about registration (default 500ms)\n * @returns Promise that resolves when element is defined and ready\n */\nasync function waitForElementReady(element, warningTimeout = DEFAULT_WARNING_TIMEOUT) {\n const tagName = element.tagName.toLowerCase();\n // Wait for element to be defined\n await waitForElementDefined(tagName, warningTimeout);\n // Wait for element's ready promise if it exists\n if ('ready' in element && typeof element.ready?.then === 'function') {\n await element.ready;\n }\n}\n/**\n * Process all custom elements in a node tree and wait for them to be ready\n * This is useful after inserting a template with custom elements\n *\n * @param node - The root node to scan for custom elements\n * @param warningTimeout - Time in ms before warning about registration (default 500ms)\n * @returns Promise that resolves when all custom elements are ready\n */\nasync function waitForAllCustomElements(node, warningTimeout = DEFAULT_WARNING_TIMEOUT) {\n const customElements = [];\n // Find all custom elements (tag names with hyphens)\n if (node instanceof Element) {\n if (node.tagName.includes('-')) {\n customElements.push(node);\n }\n // Also check in shadow DOM\n if (node.shadowRoot) {\n const shadowCustomElements = node.shadowRoot.querySelectorAll('*');\n shadowCustomElements.forEach(el => {\n if (el.tagName.includes('-')) {\n customElements.push(el);\n }\n });\n }\n }\n // If it's a DocumentFragment, check all children\n if (node instanceof DocumentFragment) {\n const elements = node.querySelectorAll('*');\n elements.forEach(el => {\n if (el.tagName.includes('-')) {\n customElements.push(el);\n }\n });\n }\n // Wait for all custom elements to be ready\n await Promise.all(customElements.map(el => waitForElementReady(el, warningTimeout)));\n}\n\n/**\n * Render debugging utilities for Snice v3.0.0\n * For testing and debugging only - not recommended for production use\n */\n/**\n * Track renders of an element using an async generator\n * Each call to tracker.next() waits for the next render to complete\n *\n * @example\n * ```typescript\n * const tracker = trackRenders(element);\n *\n * element.someProp = 'new value';\n * await tracker.next(); // Waits for render\n * // DOM is now updated\n *\n * element.someProp = 'another value';\n * await tracker.next(); // Waits for next render\n * // DOM is updated again\n * ```\n *\n * WARNING: For testing/debugging only!\n * - Do not use in production code\n * - The generator yields indefinitely - use it only in controlled test environments\n * - Each yield waits for the next render event\n */\nasync function* trackRenders(element) {\n while (true) {\n await new Promise(resolve => {\n if (!element[RENDER_CALLBACKS]) {\n element[RENDER_CALLBACKS] = [];\n }\n element[RENDER_CALLBACKS].push(resolve);\n });\n yield;\n }\n}\n\n/**\n * Shared body scroll-lock with refcounting.\n *\n * Multiple overlay components (drawer, modal, etc.) can each lock body\n * scroll independently. Without coordination, closing one overlay would\n * unlock scroll while another is still open. This utility increments\n * a module-scope counter on lock, decrements on unlock, and only mutates\n * `document.body.style.overflow` on the 0 ↔ 1 transitions. The original\n * overflow value is captured at the first lock and restored at the last\n * unlock — important because some pages set `overflow: scroll` for layout\n * and a naive `= ''` would clobber it.\n */\nlet count = 0;\nlet savedOverflow = null;\n// Test hook — `afterEach` in test suites can call `.clear()` to reset the\n// counter when document.body.innerHTML is wiped. The counter is module-scope,\n// so without this it survives across tests and the second test's first lock\n// would only increment instead of flipping `overflow: hidden`.\nconst TEST_HOOK = Symbol.for('snice:body-scroll-lock');\nglobalThis[TEST_HOOK] = {\n clear() {\n count = 0;\n savedOverflow = null;\n },\n};\nfunction lockBodyScroll() {\n if (count === 0) {\n savedOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n }\n count++;\n}\nfunction unlockBodyScroll() {\n if (count === 0)\n return;\n count--;\n if (count === 0) {\n document.body.style.overflow = savedOverflow ?? '';\n savedOverflow = null;\n }\n}\n/**\n * Test/debug only — peek at the current refcount.\n */\nfunction getBodyScrollLockCount() {\n return count;\n}\n\n/**\n * Context-aware fetch implementation with middleware support\n *\n * @example\n * ```typescript\n * const fetcher = new ContextAwareFetcher();\n *\n * fetcher.use('request', function(request, next) {\n * const token = this.application.user?.token;\n * if (token) {\n * request.headers.set('Authorization', `Bearer ${token}`);\n * }\n * return next();\n * });\n *\n * fetcher.use('response', async function(response, next) {\n * if (!response.ok) {\n * throw new Error(`HTTP ${response.status}`);\n * }\n * return next();\n * });\n *\n * const router = Router({\n * target: '#app',\n * context: { user: null },\n * fetcher\n * });\n * ```\n */\nclass ContextAwareFetcher {\n constructor() {\n this.requestMiddlewares = [];\n this.responseMiddlewares = [];\n }\n use(type, middleware) {\n if (type === 'request') {\n this.requestMiddlewares.push(middleware);\n return;\n }\n this.responseMiddlewares.push(middleware);\n }\n /**\n * Create a fetch function bound to the given Context instance\n * @param ctx - The Context instance to bind to\n * @returns A fetch function with middleware applied\n */\n create(ctx) {\n const requestMiddlewares = this.requestMiddlewares;\n const responseMiddlewares = this.responseMiddlewares;\n const fetchFn = async function (input, init) {\n const request = new Request(input, init);\n // Request middleware chain\n let reqIndex = 0;\n const nextRequest = async () => {\n if (reqIndex < requestMiddlewares.length) {\n const middleware = requestMiddlewares[reqIndex++];\n return middleware.call(this, request, nextRequest);\n }\n // Execute actual fetch\n const response = await fetch(request);\n // Response middleware chain\n let resIndex = 0;\n const nextResponse = async () => {\n if (resIndex < responseMiddlewares.length) {\n const middleware = responseMiddlewares[resIndex++];\n return middleware.call(this, response, nextResponse);\n }\n return response;\n };\n return nextResponse();\n };\n return nextRequest();\n };\n return fetchFn.bind(ctx);\n }\n}\n\n// v3.0.0 exports\n// Auto-enable native element controllers in browser environments\nif (typeof document !== 'undefined') {\n useNativeElementControllers();\n}\n// NOTE: @on decorator works in both elements AND controllers.\n// Supports event delegation, keyboard modifiers, debounce/throttle - see docs/events.md\n// Template event syntax (@click=${handler}) is also available as an alternative.\n\nexport { Context, ContextAwareFetcher, IS_CONTROLLER_INSTANCE, Router, SimpleArray, SniceElement, TransitionMode, adopted, applyElementFunctionality, attachController, classMap, clearDebounceTimers, clearMemoizeCache, clearThrottleTimers, context$1 as context, context as contextProperty, controller, createRequestHandler, css, debounce, detachController, dispatch, dispose, element, escapeAttr, escapeHtml, getBodyScrollLockCount, getController, getSymbol, html, isSafeUrl, layout, live, lockBodyScroll, memoize, moved, noChange, nothing, observe, on, once, parseDuration, property, query, queryAll, ready, reconnect, render, repeat, request, resetOnce, respond, setDisableElementReadyWarnings, setStrictRenderErrors, state, styleMap, styles, svg, throttle, trackRenders, unlockBodyScroll, unsafeHTML, useNativeElementControllers, waitForAllCustomElements, waitForElementDefined, waitForElementReady, watch };\n//# sourceMappingURL=index.esm.js.map\n","/*!\n * snice v7.0.1\n * A decorator-driven web component library with differential rendering, routing, controllers, and 130+ ready-made UI components. Use as much or as little as you want. Zero dependencies, works anywhere.\n * (c) 2024\n * Released under the MIT License.\n *\n * GENERATED FILE — DO NOT EDIT. Source: src/. Rebuild: npm run build:core\n */\n/**\n * Generic transition system for animating between elements\n */\nvar TransitionMode;\n(function (TransitionMode) {\n /** out transition completes before in transition starts */\n TransitionMode[\"SEQUENTIAL\"] = \"sequential\";\n /** both transitions happen at the same time */\n TransitionMode[\"SIMULTANEOUS\"] = \"simultaneous\";\n})(TransitionMode || (TransitionMode = {}));\n\n/**\n * Generic transition system for animating between elements\n */\n/**\n * Parse CSS property string into an object\n */\nfunction parseStyles(styleString) {\n const styles = {};\n styleString.split(';').forEach(rule => {\n const idx = rule.indexOf(':');\n if (idx === -1)\n return;\n const prop = rule.slice(0, idx).trim();\n const value = rule.slice(idx + 1).trim();\n if (prop && value) {\n styles[prop] = value;\n }\n });\n return styles;\n}\n/**\n * Perform a transition between two elements\n */\nfunction applyBaseTransitionStyles(el, isSlotted, duration, prop) {\n el.style.position = 'absolute';\n el.style.width = '100%';\n if (isSlotted) {\n el.style.height = '100%';\n el.style.transition = `opacity ${duration}ms ease-in-out`;\n return;\n }\n el.style.top = '0';\n el.style.left = '0';\n el.style.transition = `${prop} ${duration}ms ease-in-out`;\n}\nfunction resetTransitionStyles(el, isSlotted) {\n el.style.position = '';\n el.style.width = '';\n el.style.transition = '';\n if (isSlotted) {\n el.style.height = '';\n return;\n }\n el.style.top = '';\n el.style.left = '';\n}\nasync function performTransition(container, oldElement, newElement, transition = {}, \n/**\n * Called at each async boundary — if it returns true, this transition has\n * been superseded by a newer navigation. We abort cleanup so we don't tear\n * down elements now owned by the newer transition.\n */\nisStale = () => false) {\n const outDuration = transition.outDuration ?? 300;\n const inDuration = transition.inDuration ?? 300;\n const mode = (transition.mode || 'sequential');\n const outStyles = transition.out ? parseStyles(transition.out) : { opacity: '0' };\n const inStartStyles = { opacity: '0' };\n const inEndStyles = transition.in ? parseStyles(transition.in) : { opacity: '1' };\n const containerStyle = container.style;\n const isLayoutElement = container.tagName.includes('-') && container.shadowRoot;\n // Track the position we were ORIGINALLY given, not what a concurrent\n // transition may have already written. The first transition to touch this\n // container wins; subsequent overlapping transitions reuse the same value\n // and the last one to finish restores it.\n const POS_KEY = Symbol.for('snice:transition-original-position');\n const POS_COUNT = Symbol.for('snice:transition-count');\n const c = container;\n if (!isLayoutElement) {\n if (!(POS_KEY in c)) {\n c[POS_KEY] = containerStyle.position;\n c[POS_COUNT] = 0;\n }\n c[POS_COUNT]++;\n containerStyle.position = 'relative';\n }\n const restorePosition = () => {\n if (isLayoutElement)\n return;\n c[POS_COUNT]--;\n if (c[POS_COUNT] <= 0) {\n containerStyle.position = c[POS_KEY];\n delete c[POS_KEY];\n delete c[POS_COUNT];\n }\n };\n const isSlotted = oldElement.hasAttribute('slot') || newElement.hasAttribute('slot');\n applyBaseTransitionStyles(oldElement, isSlotted, outDuration, 'all');\n applyBaseTransitionStyles(newElement, isSlotted, inDuration, 'all');\n Object.assign(newElement.style, inStartStyles);\n container.appendChild(newElement);\n void newElement.offsetHeight;\n // Animate\n switch (mode) {\n case TransitionMode.SIMULTANEOUS:\n Object.assign(oldElement.style, outStyles);\n Object.assign(newElement.style, inEndStyles);\n await new Promise(resolve => setTimeout(resolve, Math.max(outDuration, inDuration)));\n break;\n case TransitionMode.SEQUENTIAL:\n Object.assign(oldElement.style, outStyles);\n await new Promise(resolve => setTimeout(resolve, outDuration));\n if (isStale()) {\n if (newElement.parentNode === container)\n newElement.remove();\n restorePosition();\n return;\n }\n Object.assign(newElement.style, inEndStyles);\n await new Promise(resolve => setTimeout(resolve, inDuration));\n break;\n }\n if (isStale()) {\n // A newer navigation took over while we were animating. Don't touch\n // oldElement (the newer transition owns it now) and remove OUR newElement\n // since the newer transition appended its own.\n if (newElement.parentNode === container)\n newElement.remove();\n restorePosition();\n return;\n }\n // Cleanup\n oldElement.remove();\n resetTransitionStyles(newElement, isSlotted);\n Object.keys({ ...inStartStyles, ...inEndStyles }).forEach(prop => {\n newElement.style[prop] = '';\n });\n restorePosition();\n}\n/**\n * Predefined transitions\n */\n// Fade transition\nconst fadeTransition = {\n name: 'fade',\n outDuration: 200,\n inDuration: 200,\n out: 'opacity: 0',\n in: 'opacity: 1',\n mode: 'simultaneous'\n};\n// Slide transition (from left)\nconst slideTransition = {\n name: 'slide',\n outDuration: 300,\n inDuration: 300,\n out: 'transform: translateX(-100%)',\n in: 'transform: translateX(0)',\n mode: 'sequential'\n};\n// Slide from right\nconst slideRightTransition = {\n name: 'slide-right',\n outDuration: 300,\n inDuration: 300,\n out: 'transform: translateX(100%)',\n in: 'transform: translateX(0)',\n mode: 'sequential'\n};\n// Slide from top\nconst slideUpTransition = {\n name: 'slide-up',\n outDuration: 300,\n inDuration: 300,\n out: 'transform: translateY(-100%)',\n in: 'transform: translateY(0)',\n mode: 'sequential'\n};\n// Slide from bottom\nconst slideDownTransition = {\n name: 'slide-down',\n outDuration: 300,\n inDuration: 300,\n out: 'transform: translateY(100%)',\n in: 'transform: translateY(0)',\n mode: 'sequential'\n};\n// Scale transition\nconst scaleTransition = {\n name: 'scale',\n outDuration: 250,\n inDuration: 250,\n out: 'transform: scale(0.9); opacity: 0',\n in: 'transform: scale(1); opacity: 1',\n mode: 'simultaneous'\n};\n// Rotate transition\nconst rotateTransition = {\n name: 'rotate',\n outDuration: 400,\n inDuration: 400,\n out: 'transform: rotate(180deg) scale(0.5); opacity: 0',\n in: 'transform: rotate(0) scale(1); opacity: 1',\n mode: 'simultaneous'\n};\n// Flip transition\nconst flipTransition = {\n name: 'flip',\n outDuration: 400,\n inDuration: 400,\n out: 'transform: rotateY(180deg); opacity: 0',\n in: 'transform: rotateY(0); opacity: 1',\n mode: 'sequential'\n};\n// Zoom transition\nconst zoomTransition = {\n name: 'zoom',\n outDuration: 300,\n inDuration: 300,\n out: 'transform: scale(2); opacity: 0',\n in: 'transform: scale(1); opacity: 1',\n mode: 'simultaneous'\n};\n// None transition (instant swap)\nconst noneTransition = {\n name: 'none',\n outDuration: 0,\n inDuration: 0,\n out: '',\n in: '',\n mode: 'simultaneous'\n};\n\nexport { TransitionMode, fadeTransition, flipTransition, noneTransition, parseStyles, performTransition, rotateTransition, scaleTransition, slideDownTransition, slideRightTransition, slideTransition, slideUpTransition, zoomTransition };\n//# sourceMappingURL=transitions.esm.js.map\n","/*!\n * snice v7.0.1\n * A decorator-driven web component library with differential rendering, routing, controllers, and 130+ ready-made UI components. Use as much or as little as you want. Zero dependencies, works anywhere.\n * (c) 2024\n * Released under the MIT License.\n *\n * GENERATED FILE — DO NOT EDIT. Source: src/. Rebuild: npm run build:core\n */\n// Global namespace for Snice framework\n// Ensures all registries and symbols are shared across different JS files/modules\n// Initialize the global Snice namespace on globalThis\n// This ensures all module instances share the same registry\nif (!globalThis.snice) {\n globalThis.snice = {\n controllerRegistry: new Map(),\n pendingControllerAttachments: new Map(),\n controllerIdCounter: 0\n };\n}\n// Multiple copies of Snice can share a global created by an older build.\nglobalThis.snice.pendingControllerAttachments ??= new Map();\n// Helper function to get or create a global symbol\n// Symbol.for() already guarantees global uniqueness, no need for a Map cache\nfunction getSymbol(name) {\n return Symbol.for(`snice:${name}`);\n}\n\n// Central file for all symbols used in the framework\n// All symbols are stored globally to ensure consistency across modules\nconst IS_CONTROLLER_CLASS = getSymbol('is-controller-class');\nconst IS_CONTROLLER_INSTANCE = getSymbol('is-controller-instance');\nconst IS_ELEMENT_CLASS = getSymbol('is-element-class');\nconst CHANNEL_HANDLERS = getSymbol('channel-handlers');\n// Internal element state symbols\nconst READY_PROMISE = getSymbol('ready-promise');\nconst READY_RESOLVE = getSymbol('ready-resolve');\nconst RENDERED_PROMISE = getSymbol('rendered-promise');\nconst RENDERED_RESOLVE = getSymbol('rendered-resolve');\n// Set when a render is requested but dropped because the element was\n// disconnected; consumed on reconnect to replay exactly the missed render.\nconst PENDING_RECONNECT_RENDER = getSymbol('pending-reconnect-render');\n// Per-element synchronous render-nesting depth, used to cap runaway re-entry\n// without a shared global counter that one element could exhaust for others.\nconst RENDER_DEPTH = getSymbol('render-depth');\nconst RENDER_ROOT = getSymbol('render-root');\nconst ELEMENT_OPTIONS = getSymbol('element-options');\nconst CONTROLLER = getSymbol('controller');\nconst INITIALIZED = getSymbol('initialized');\n// Event handler symbols\nconst ON_HANDLERS = getSymbol('on-handlers');\n// Controller symbols\nconst CONTROLLER_KEY = getSymbol('controller-key');\nconst CONTROLLER_NAME_KEY = getSymbol('controller-name');\nconst CONTROLLER_ID = getSymbol('controller-id');\nconst CONTROLLER_OPERATIONS = getSymbol('controller-operations');\nconst NATIVE_CONTROLLER = getSymbol('native-controller');\n// Set while a controller CLASS (not a registry name) is attached — the\n// attribute/MutationObserver channel must not attach over or detach it.\nconst DIRECT_CONTROLLER = getSymbol('direct-controller');\n// A controller class bound by a template before the custom element was\n// defined/upgraded. Picked up by connectedCallback on first initialization.\nconst PENDING_CONTROLLER_BINDING = getSymbol('pending-controller-binding');\n// Cleanup symbol - holds an object with all cleanup arrays\nconst CLEANUP = getSymbol('cleanup');\n// Property symbols\nconst PROPERTIES = getSymbol('properties');\nconst PROPERTY_VALUES = getSymbol('property-values');\nconst PROPERTY_DEFAULTS = getSymbol('property-defaults');\nconst PROPERTY_WRAPPERS = getSymbol('property-wrappers');\nconst PRE_INIT_PROPERTY_VALUES = getSymbol('pre-init-property-values');\nconst PRE_UPGRADE_PROPERTY_BINDINGS = getSymbol('pre-upgrade-property-bindings');\nconst PROPERTIES_INITIALIZED = getSymbol('properties-initialized');\nconst PROPERTY_WATCHERS = getSymbol('property-watchers');\nconst EXPLICITLY_SET_PROPERTIES = getSymbol('explicitly-set-properties');\n// Router context symbol\nconst ROUTER_CONTEXT = getSymbol('router-context');\nconst CURRENT_PAGE_MARKER = getSymbol('current-page-marker');\nconst CONTEXT_REQUEST_HANDLER = getSymbol('context-request-handler');\nconst PAGE_TRANSITION = getSymbol('page-transition');\nconst CREATED_AT = getSymbol('created-at');\n// Lifecycle symbols\nconst READY_HANDLERS = getSymbol('ready-handlers');\nconst DISPOSE_HANDLERS = getSymbol('dispose-handlers');\nconst RECONNECT_HANDLERS = getSymbol('reconnect-handlers');\nconst MOVED_HANDLERS = getSymbol('moved-handlers');\nconst ADOPTED_HANDLERS = getSymbol('adopted-handlers');\n// Observer symbols\nconst OBSERVERS = getSymbol('observers');\n// Part symbols\nconst PARTS = getSymbol('parts');\nconst PART_TIMERS = getSymbol('part-timers');\n// Property setter flag (prevents attributeChangedCallback re-triggering watchers)\nconst SETTING_FROM_PROPERTY = getSymbol('setting-from-property');\n// Lifecycle callback timers\nconst MOVED_TIMERS = getSymbol('moved-timers');\nconst ADOPTED_TIMERS = getSymbol('adopted-timers');\n// Dispatch timing symbols\nconst DISPATCH_TIMERS = getSymbol('dispatch-timers');\n// Render symbols (v3.0.0)\nconst RENDER_METHOD = getSymbol('render-method');\nconst RENDER_OPTIONS = getSymbol('render-options');\nconst RENDER_INSTANCE = getSymbol('render-instance');\nconst RENDER_TIMERS = getSymbol('render-timers');\nconst RENDER_CALLBACKS = getSymbol('render-callbacks');\nconst STYLES_METHOD = getSymbol('styles-method');\nconst STYLES_APPLIED = getSymbol('styles-applied');\nconst PARENT_STYLES_METHODS = getSymbol('parent-styles-methods');\nconst SNICE_ELEMENT_BASE = getSymbol('snice-element-base');\n// Navigation context symbols\nconst CONTEXT_HANDLER = getSymbol('context-handler');\nconst CONTEXT_METHOD_NAME = getSymbol('context-method-name');\nconst NAVIGATION_CONTEXT_INSTANCE = getSymbol('navigation-context-instance');\nconst REGISTERED_ELEMENTS = getSymbol('registered-elements');\nconst IS_UPDATING = getSymbol('is-updating');\nconst CONTEXT_REGISTER = getSymbol('context-register');\nconst CONTEXT_UNREGISTER = getSymbol('context-unregister');\nconst CONTEXT_NOTIFY_ELEMENT = getSymbol('context-notify-element');\nconst CONTEXT_OPTIONS = getSymbol('context-options');\nconst CONTEXT_TIMER = getSymbol('context-timer');\nconst CONTEXT_CALLED = getSymbol('context-called');\nconst CONTEXT_UPDATE = getSymbol('context-update');\n// Registration de-dup sets on the constructor — replace previous `__*Methods`\n// expando strings that violated the no-double-underscore rule.\nconst CONTEXT_METHODS = getSymbol('context-methods');\nconst WATCH_METHODS = getSymbol('watch-methods');\nconst OBSERVE_METHODS = getSymbol('observe-methods');\nconst ON_METHODS = getSymbol('on-methods');\nconst RESPOND_METHODS = getSymbol('respond-methods');\nconst READY_METHODS = getSymbol('ready-methods');\nconst DISPOSE_METHODS = getSymbol('dispose-methods');\nconst RECONNECT_METHODS = getSymbol('reconnect-methods');\nconst MOVED_METHODS = getSymbol('moved-methods');\nconst ADOPTED_METHODS = getSymbol('adopted-methods');\n// Controller attach-abort — set to an AbortController while attachController\n// is awaiting element.ready, so detachController can short-circuit the wait.\nconst CONTROLLER_ABORT = getSymbol('controller-abort');\n// Set on a controller instance once it has gotten past element.ready and is\n// being attached, so detachController knows not to run detach() on a controller\n// whose attach() was aborted before it ever ran.\nconst CONTROLLER_ATTACHED = getSymbol('controller-attached');\nconst PROPERTY_DEFINERS = getSymbol('property-definers');\n\nexport { ADOPTED_HANDLERS, ADOPTED_METHODS, ADOPTED_TIMERS, CHANNEL_HANDLERS, CLEANUP, CONTEXT_CALLED, CONTEXT_HANDLER, CONTEXT_METHODS, CONTEXT_METHOD_NAME, CONTEXT_NOTIFY_ELEMENT, CONTEXT_OPTIONS, CONTEXT_REGISTER, CONTEXT_REQUEST_HANDLER, CONTEXT_TIMER, CONTEXT_UNREGISTER, CONTEXT_UPDATE, CONTROLLER, CONTROLLER_ABORT, CONTROLLER_ATTACHED, CONTROLLER_ID, CONTROLLER_KEY, CONTROLLER_NAME_KEY, CONTROLLER_OPERATIONS, CREATED_AT, CURRENT_PAGE_MARKER, DIRECT_CONTROLLER, DISPATCH_TIMERS, DISPOSE_HANDLERS, DISPOSE_METHODS, ELEMENT_OPTIONS, EXPLICITLY_SET_PROPERTIES, INITIALIZED, IS_CONTROLLER_CLASS, IS_CONTROLLER_INSTANCE, IS_ELEMENT_CLASS, IS_UPDATING, MOVED_HANDLERS, MOVED_METHODS, MOVED_TIMERS, NATIVE_CONTROLLER, NAVIGATION_CONTEXT_INSTANCE, OBSERVERS, OBSERVE_METHODS, ON_HANDLERS, ON_METHODS, PAGE_TRANSITION, PARENT_STYLES_METHODS, PARTS, PART_TIMERS, PENDING_CONTROLLER_BINDING, PENDING_RECONNECT_RENDER, PRE_INIT_PROPERTY_VALUES, PRE_UPGRADE_PROPERTY_BINDINGS, PROPERTIES, PROPERTIES_INITIALIZED, PROPERTY_DEFAULTS, PROPERTY_DEFINERS, PROPERTY_VALUES, PROPERTY_WATCHERS, PROPERTY_WRAPPERS, READY_HANDLERS, READY_METHODS, READY_PROMISE, READY_RESOLVE, RECONNECT_HANDLERS, RECONNECT_METHODS, REGISTERED_ELEMENTS, RENDERED_PROMISE, RENDERED_RESOLVE, RENDER_CALLBACKS, RENDER_DEPTH, RENDER_INSTANCE, RENDER_METHOD, RENDER_OPTIONS, RENDER_ROOT, RENDER_TIMERS, RESPOND_METHODS, ROUTER_CONTEXT, SETTING_FROM_PROPERTY, SNICE_ELEMENT_BASE, STYLES_APPLIED, STYLES_METHOD, WATCH_METHODS, getSymbol };\n//# sourceMappingURL=symbols.esm.js.map\n"],"names":["globalThis","snice","controllerRegistry","Map","pendingControllerAttachments","controllerIdCounter","getSymbol","name","Symbol","for","IS_CONTROLLER_CLASS","IS_CONTROLLER_INSTANCE","IS_ELEMENT_CLASS","CHANNEL_HANDLERS","READY_PROMISE","READY_RESOLVE","RENDERED_PROMISE","RENDERED_RESOLVE","PENDING_RECONNECT_RENDER","RENDER_DEPTH","RENDER_ROOT","ELEMENT_OPTIONS","CONTROLLER","INITIALIZED","CONTROLLER_KEY","CONTROLLER_NAME_KEY","CONTROLLER_ID","CONTROLLER_OPERATIONS","NATIVE_CONTROLLER","DIRECT_CONTROLLER","PENDING_CONTROLLER_BINDING","CLEANUP","PROPERTIES","PROPERTY_VALUES","PROPERTY_DEFAULTS","PROPERTY_WRAPPERS","PRE_INIT_PROPERTY_VALUES","PRE_UPGRADE_PROPERTY_BINDINGS","PROPERTIES_INITIALIZED","PROPERTY_WATCHERS","EXPLICITLY_SET_PROPERTIES","ROUTER_CONTEXT","PAGE_TRANSITION","CREATED_AT","READY_HANDLERS","DISPOSE_HANDLERS","RECONNECT_HANDLERS","MOVED_HANDLERS","ADOPTED_HANDLERS","OBSERVERS","SETTING_FROM_PROPERTY","MOVED_TIMERS","ADOPTED_TIMERS","DISPATCH_TIMERS","RENDER_METHOD","RENDER_OPTIONS","RENDER_INSTANCE","RENDER_TIMERS","RENDER_CALLBACKS","STYLES_METHOD","STYLES_APPLIED","PARENT_STYLES_METHODS","SNICE_ELEMENT_BASE","CONTEXT_HANDLER","NAVIGATION_CONTEXT_INSTANCE","REGISTERED_ELEMENTS","IS_UPDATING","CONTEXT_REGISTER","CONTEXT_UNREGISTER","CONTEXT_NOTIFY_ELEMENT","CONTEXT_TIMER","CONTEXT_CALLED","CONTEXT_UPDATE","CONTEXT_METHODS","WATCH_METHODS","OBSERVE_METHODS","ON_METHODS","RESPOND_METHODS","READY_METHODS","DISPOSE_METHODS","RECONNECT_METHODS","MOVED_METHODS","ADOPTED_METHODS","CONTROLLER_ABORT","CONTROLLER_ATTACHED","PROPERTY_DEFINERS","SimpleArray","this","SEPARATOR","serialize","arr","Array","isArray","map","item","includes","Error","String","join","parse","str","split","test","num","Number","isNaN","_a","_b","_c","TransitionMode","REGISTERED_ELEMENTS_SET","contextIdCounter","Context","constructor","context","placards","currentRoute","routeParams","fetcher","WeakMap","Set","id","application","navigation","route","params","create","fetch","bind","element","methodName","names","get","set","add","undefined","delete","size","notify","update","elementsSet","elementsMap","error","console","detectType","initialValue","Boolean","Date","BigInt","parseAttributeValue","attributeValue","propertyOptions","currentValue","typeToUse","type","converter","fromAttribute","endsWith","slice","JSON","Object","notEqual","value","old","getAttrName","opts","propName","attribute","toLowerCase","attributeNaming","replace","ensureSet","obj","sym","ensureObj","invokeWatchers","instance","oldValue","newValue","watchers","keys","propOpts","attrName","push","key","has","w","method","call","e","createDebounced","fn","delay","timer","args","clearTimeout","setTimeout","apply","createThrottled","lastCall","now","remaining","resolveScope","host","scope","document","closest","addEventListener","valueToAttribute","length","toAttribute","toISOString","toString","stringify","validatedWatchClasses","WeakSet","mediaQueryCache","setupObservers","observers","events","channels","observer","callback","options","throttle","setupIntersectionObserver","setupResizeObserver","setupMediaQueryObserver","setupMutationObserver","warn","threshold","rootMargin","root","IntersectionObserver","io","entries","entry","unobserve","target","targets","selector","from","shadowRoot","querySelectorAll","forEach","observe","takeRecords","disconnect","box","ResizeObserver","ro","_element","mediaQuery","mql","window","matchMedia","wrappedCallback","event","matches","changeHandler","removeEventListener","addListener","removeListener","parts","mutationType","attributeName","childList","attributes","attributeFilter","subtree","maxDepth","needsDepthFilter","mo","MutationObserver","mutations","filtered","filter","mutation","depth","current","parentNode","isController","cleanupObservers","cleanup","setupResponseHandlers","handlers","handler","boundMethod","eventName","channelName","debounceTimeout","throttleTimeout","throttleLastCall","throttleTrailingResolvers","throttleLatestArgs","timedMethod","originalMethod","debounce","Promise","resolve","reject","async","orphaned","splice","result","then","r","x","resolvers","finalArgs","createTimedMethod","responseHandler","data","discovery","payload","detail","preventDefault","stopImmediatePropagation","stopPropagation","catch","cleanupResponseHandlers","HTML_RESULT","CSS_RESULT","cssResultCache","isTemplateResult","_$litType$","isCSSResult","nothing","UNSAFE_HTML","isUnsafeHTML","REPEAT_RESULT","renderHosts","getRenderRoot","ensureRenderRoot","existing","renderRoot","shadow","createRenderRoot","attachShadow","mode","delegatesFocus","ShadowRoot","TypeError","findRenderHost","node","getRootNode","HTMLElement","marker","Math","random","toFixed","markerMatch","nodeMarker","markerRegex","RegExp","templateCache","NOT_COMMITTED","markPreUpgradePropertyBinding","propertyName","tagName","localName","registry","ownerDocument","defaultView","customElements","noChange","LIVE_MARKER","isPrimitive","isAsyncIterable","asyncIterator","Template","attrNamesForParts","keyIndex","walker","createTreeWalker","content","NodeFilter","SHOW_ELEMENT","SHOW_COMMENT","SHOW_TEXT","partIndex","nodesToRemove","nextNode","nodeType","Node","ELEMENT_NODE","parentTag","parentElement","valueAttr","getAttribute","removeAttribute","index","child","childNodes","branchTag","TEXT_NODE","textContent","trim","COMMENT_NODE","hasAttributes","attrsToRemove","i","attr","originalName","attrStrings","expressionCount","startsWith","hasStaticText","some","s","spreadName","comment","parent","endNode","createComment","insertBefore","nextSibling","startNode","commentStrings","text","lastIndex","createTextNode","removeChild","part","prepareTemplate","strings","cached","htmlParts","inTag","inAttrValue","inComment","attrQuoteChar","currentAttrName","j","char","attrStart","substring","trimmed","trimEnd","match","html","template","createElement","svg","innerHTML","wrapper","firstElementChild","firstChild","tmpl","getItemKey","values","TemplateInstance","fragment","conditionalParts","regularParts","isSameTemplate","renderFragment","cloneNode","SHOW_ALL","clonedWalker","nodeMap","templateNode","currentNode","clonedNode","dynamicWhenElements","definition","partDef","NodePart","attrElement","AttributePart","propElement","PropertyPart","boolElement","BooleanAttributePart","eventElement","EventPart","classElement","ClassPart","styleElement","StylePart","spreadElement","SpreadPart","controllerElement","ControllerPart","conditionalIfElement","ConditionalIfPart","conditionalElseIfElement","ConditionalElseIfPart","conditionalCaseElement","ConditionalCasePart","conditionalWhenElement","ConditionalWhenPart","commentNode","CommentPart","render","commit","flushed","coordinator","flush","lifecycleError","isConnected","reconnected","disconnected","clear","destroy","preserveEventListeners","Part","_preserveEventListeners","super","_committedValue","_itemKeys","_asyncSource","_asyncVersion","_asyncIterator","_asyncRunning","_asyncStarted","_asyncCompleted","_asyncPaused","_committingAsyncValue","isPromiseLike","_commitAsync","_cancelAsync","_commitText","_commitTemplateResult","_$repeat$","isRepeatResult","empty","_commitIterable","_commitUnsafeHTML","iterator","isIterable","_commitNode","cleanupError","_clear","textNode","_insertBefore","committedInstance","cachedTemplate","previousValue","previousKeys","previousFragment","createDocumentFragment","previousNode","next","appendChild","remove","_disposeCommitted","explicitKeys","items","newKeys","definedKeys","allKeyed","every","k","oldKeys","_reconcileKeyed","itemParts","itemPart","startMarker","endMarker","oldParts","oldByKey","reused","newParts","fill","candidate","ref","range","stop","prev","temp","source","_startAsyncSource","forceConnected","version","done","_commitAsyncValue","clearSource","return","committed","lastValues","lastValueIndex","valueIndex","finalValue","change","committedValues","v","_commitValue","setAttribute","_committedValues","startIndex","vals","enabled","classList","toggle","is","style","removeProperty","setProperty","listeners","consumedOnce","commitEvents","commitProperties","commitAttributes","prototype","hasOwnProperty","label","rawName","handleEvent","validateSpreadEvents","find","listener","listenerObject","once","resolveHost","detachListeners","_$liveMarker$","isLive","first","previous","el","controller","_detach","hasAttribute","_apply","controllerClass","_attach","ready","attachController","detachController","boolValue","listenerOptions","keyFilter","modifiers","onceConsumed","eventSpec","modifierSpecs","aliases","preventdefault","stoppropagation","stopimmediatepropagation","allowed","raw","normalized","isKeyboardEvent","dotIndex","indexOf","colonIndex","delimiterIndex","min","max","baseEvent","keySpec","parseKeyboardFilter","warnIfModifierMisuse","isListenerObject","passive","attachListener","matchesKeyboardFilter","valueOptions","capture","signal","detachListener","MODIFIER_WORDS","dot","lastIndexOf","suffix","spec","anyModifiers","lower","ctrl","alt","shift","meta","normalizeKey","esc","escape","enter","space","spacebar","up","down","left","right","arrowup","arrowdown","arrowleft","arrowright","del","backspace","tab","home","end","pageup","pagedown","ctrlKey","altKey","shiftKey","metaKey","NOT_SET","ifElement","conditions","branches","defaultBranch","currentBranch","primary","sawAlternative","lastBranch","tag","conditionalElseIfOwners","setAlternative","collectCurrent","hasChildNodes","owner","caseElement","children","childTag","dynamic","expected","conditionalWhenOwners","setExpected","findIndex","branch","ON_HANDLERS","throttle$1","NON_BUBBLING_EVENTS","setupEventHandlers","targetElement","cleanupEventHandlers","currentMethod","handlerOptions","baseEventName","keyModifier","keyModifierMethod","createKeyModifierHandler","hasExplicitScope","scopedTarget","eventRoot","delegatedHandler","needsCapture","handledSymbol","wrappedMethod","ControllerScope","cleanupFns","pendingOperations","register","unregister","all","runOperation","operation","promise","voidPromise","deferControllerAttachment","controllerName","queueMicrotask","nativeName","pending","controllerLabel","existingController","nativeController","ControllerClass","controllerInstance","controllerId","routerContext","abort","AbortController","race","_","onAbort","aborted","timerId","attach","dispatchEvent","CustomEvent","pendingAbort","controllerSource","detach","useNativeElementControllers","sniceNativeControllersInitialized","processElement","currentControllerName","message","debug","addedNodes","startObserving","body","readyState","sniceNativeControllerObserver","CONTEXT_HANDLERS","setupContextHandler","ctx","wrappedMethodName","called","callMethod","timerSlot","timerKey","timeout","strictRenderErrors","ensureRenderedPromise","resolveRendered","renderScheduler","scheduled","schedule","sync","performRender","elements","hasRendered","flushRenderCallbacks","callbacks","cbs","cb","MAX_RENDER_DEPTH","precomputedResult","hasPrecomputedResult","arguments","renderMethod","differential","removable","nextInstance","nextFragment","requestRender","immediate","reconnectRenderTree","lastThrottle","timers","throttleTimer","DEBOUNCE_TIMERS","THROTTLE_TIMERS","ONCE_CALLED","MEMOIZE_CACHE","clearDebounceTimers","clearThrottleTimers","invariantValue","property","descriptor","Reflect","getOwnPropertyDescriptor","configurable","locked","writable","applyElementFunctionality","originalConnectedCallback","connectedCallback","originalDisconnectedCallback","disconnectedCallback","originalAttributeChangedCallback","attributeChangedCallback","observedAttributes","properties","propOptions","defineProperty","enumerable","reconnectHandlers","attrValue","propValue","pendingControllerClass","pendingLabel","stylesMethod","staticResults","constructors","Function","unshift","getPrototypeOf","styles","allResults","parentMethods","existingStyles","cssText","styleSheet","adoptedStyleSheets","applyStyles","valid","known","validateWatchedProperties","invokeImmediateWatchers","readyHandlers","disconnectRenderTree","disposeHandlers","cleanupContextHandler","hadPending","clearRenderTimers","t","latestDetail","clearDispatchTimers","clearLifecycleTimers","defaultValue","parsedValue","wrap","hasChanged","connectedMoveCallback","movedHandlers","adoptedCallback","adoptedHandlers","defineElement","ancestors","reverse","ancestor","formAssociated","mergeParentMetadata","metadata","_pendingProperties","pop","inheritedOptions","ownOptions","mergedOptions","renderOptions","SNICE_DEBUG","define","nativeOwnPropertyDefaults","_value","propertyKey","markedBindings","wasTemplateBoundBeforeUpgrade","hasOwnValue","hadPreUpgradeValue","defaults","nativeElement","ownKeys","isNativeOwnPropertyDefault","preUpgradeValue","finalOptions","propertyAttributeNaming","notifyDeepMutation","reflect","attrKey","deep","wrapped","changed","cache","rawByProxy","unwrap","input","proxy","methods","Proxy","invariant","existed","deleted","thisArg","entryValue","isPlainObject","receiver","deleteProperty","nextDescriptor","second","firstIsData","descriptorsEqual","createDeepReactive","proto","definers","existingDefiner","incomingValue","wrappedInitialValue","getQueryRoot","registerHandler","handlersSymbol","methodsSymbol","extra","addInitializer","inherited","timersSymbol","debounceTimer","lastThrottleCall","createLifecycleDecorator","exec","a","execDeferred","moved","adopted","SniceElement","invalidate","rendered","renderNow","Route","pattern","parsed","parsePattern","pathPattern","queryPattern","queryOptional","queryIndex","pathSegments","parseSegments","querySegments","parseQuerySegments","segments","optionalSegments","endIndex","parseOptionalGroup","paramEndIndex","parseIdentifier","splatName","splatEndIndex","literalEndIndex","parseLiteral","cleanPattern","parseQueryLiteral","getAllParamNames","paramNames","collectParams","segment","canMatchRemainingSegments","path","pathIndex","literalIndex","url","pathPart","queryPart","pathParams","matchPath","queryParams","matchQuery","allParams","paramName","assign","remainingSegments","matchResult","matchSegment","nextIndex","nextSegment","stopChars","literalStart","decodeURIComponent","firstDotIndex","lastSlashIndex","lastSlash","findFirstLiteral","segs","seg","nested","firstLiteral","tempIndex","allMatched","innerSegment","remainingInner","innerResult","findNextLiteral","query","pathResult","reverseSegments","queryResult","inActivatedStructure","hasAllParams","hasLaterOptionalGroupNeedingParams","optionalResult","laterSegments","currentOptionalSegments","hasAnyParamInSegments","hasOnlyLiteralsAndOptionals","hasDirectParams","hasNestedParams","missingDirectParam","passToNested","hasOnlyOptionalMissingParams","routeSpecificity","score","parseStyles","styleString","rule","idx","prop","applyBaseTransitionStyles","isSlotted","duration","position","width","height","transition","top","RouteResult","DISABLE_ELEMENT_READY_WARNINGS","waitForElementDefined","warningTimeout","warningTimer","whenDefined","waitForElementReady","count","savedOverflow","TEST_HOOK","requestMiddlewares","responseMiddlewares","use","middleware","init","request","Request","reqIndex","nextRequest","response","resIndex","nextResponse","win","doc","routes","_404","_403","is_sorted","currentLayoutName","currentLayoutTimestamp","navigationContext","getCurrentLayoutElement","layoutElements","guards","layout","placard","collectPlacards","seen","p","emitContextUpdate","currentPath","getPath","location","hash","pathname","renderForbiddenPage","newPageElement","div","className","checkGuards","stale","guardsArray","spinner","spinnerTimer","container","createLoadingSpinner","guard","renderPage","pageElement","layoutToUse","pageLayout","layoutElement","needsNewLayout","timestamp","setupLayout","finalTransition","currentLayout","updateLayout","oldPageInLayout","querySelector","performTransition$1","page","renderWithLayout","currentElementInTarget","renderDirect","navGeneration","navigate","myGen","scrollTo","homeRoute","createHomeElement","routeResult","GUARDS_FAILED","SUCCESS","NOT_FOUND","resolveRoute","create404Element","oldElement","newElement","atGen","isStale","outDuration","inDuration","outStyles","out","opacity","inStartStyles","inEndStyles","in","containerStyle","isLayoutElement","POS_KEY","POS_COUNT","c","restorePosition","SIMULTANEOUS","SEQUENTIAL","resetTransitionStyles","performTransition","pageOptions","elementConnectedCallback","elementDisconnectedCallback","initialize","sort","b","setupEventListeners","classes","hasOwn","bubbles","cancelable","_context","cleanups","ce","CSSStyleSheet","Document","sheet","replaceSync","wait","leading","trailing","maxWait","isFirstCall","startTime","shouldInvokeFromMaxWait","lastArgs","doDispatch","dispatchOnUndefined","composed","timedDispatch","d","resolvedResult","URL","hasExplicitScheme","isNetworkPathReference","protocol","overflow","keyGenerator","maxSize","ttl","firstKey","observeTarget","selectorOrOptions","observeTargets","targetString","targetStr","eventNames","registrationKey","perInstance","globalResult","globalCalled","parseFloat","ms","milliseconds","seconds","minutes","light","managedRoot","results","array","requestName","actualRequest","responseTimeout","discoveryTimeout","generator","dataResolve","dataReject","dataPromise","discoveryResolve","discoveryReject","discoveryTimeoutId","discovered","discoveryPromise","responseTimeoutId","optional","recovered","throw","decls","lastInvoke","timeSinceLastInvoke","Element","DocumentFragment","propertyNames","registered","copy"],"mappings":"mCAYKA,WAAWC,QACZD,WAAWC,MAAQ,CACfC,mBAAoB,IAAIC,IACxBC,6BAA8B,IAAID,IAClCE,oBAAqB,IAI7BL,WAAWC,MAAMG,+BAAiC,IAAID,IAEtD,MAAMF,EAAQD,WAAWC,MAGzB,SAASK,EAAUC,GACf,OAAOC,OAAOC,IAAI,SAASF,IAC/B,CAIA,MAAMG,EAAsBJ,EAAU,uBAChCK,EAAyBL,EAAU,0BACnCM,EAAmBN,EAAU,oBAC7BO,EAAmBP,EAAU,oBAE7BQ,EAAgBR,EAAU,iBAC1BS,EAAgBT,EAAU,iBAC1BU,EAAmBV,EAAU,oBAC7BW,EAAmBX,EAAU,oBAG7BY,EAA2BZ,EAAU,4BAGrCa,EAAeb,EAAU,gBACzBc,EAAcd,EAAU,eACxBe,EAAkBf,EAAU,mBAC5BgB,EAAahB,EAAU,cACvBiB,EAAcjB,EAAU,eAExBkB,EAAiBlB,EAAU,kBAC3BmB,EAAsBnB,EAAU,mBAChCoB,EAAgBpB,EAAU,iBAC1BqB,EAAwBrB,EAAU,yBAClCsB,EAAoBtB,EAAU,qBAG9BuB,EAAoBvB,EAAU,qBAG9BwB,EAA6BxB,EAAU,8BAEvCyB,EAAUzB,EAAU,WAEpB0B,EAAa1B,EAAU,cACvB2B,EAAkB3B,EAAU,mBAC5B4B,EAAoB5B,EAAU,qBAC9B6B,EAAoB7B,EAAU,qBAC9B8B,EAA2B9B,EAAU,4BACrC+B,EAAgC/B,EAAU,iCAC1CgC,EAAyBh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