@pithyjs/core 0.1.0-beta.15 → 0.1.0-beta.17

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 (77) hide show
  1. package/README.md +4 -0
  2. package/dist/compile/binds/bindBoundAttributes.d.ts +4 -0
  3. package/dist/compile/binds/bindBoundAttributes.d.ts.map +1 -1
  4. package/dist/compile/binds/bindBoundAttributes.js +63 -3
  5. package/dist/compile/binds/bindBoundAttributes.js.map +1 -1
  6. package/dist/compile/binds/bindClassDirectives.d.ts.map +1 -1
  7. package/dist/compile/binds/bindClassDirectives.js +3 -2
  8. package/dist/compile/binds/bindClassDirectives.js.map +1 -1
  9. package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
  10. package/dist/compile/binds/bindComponentsTags.js +15 -1
  11. package/dist/compile/binds/bindComponentsTags.js.map +1 -1
  12. package/dist/compile/binds/bindDefaultTwoWay.d.ts.map +1 -1
  13. package/dist/compile/binds/bindDefaultTwoWay.js +2 -1
  14. package/dist/compile/binds/bindDefaultTwoWay.js.map +1 -1
  15. package/dist/compile/binds/bindDeferDirectives.d.ts.map +1 -1
  16. package/dist/compile/binds/bindDeferDirectives.js +17 -15
  17. package/dist/compile/binds/bindDeferDirectives.js.map +1 -1
  18. package/dist/compile/binds/bindErrorBoundary.d.ts.map +1 -1
  19. package/dist/compile/binds/bindErrorBoundary.js +6 -4
  20. package/dist/compile/binds/bindErrorBoundary.js.map +1 -1
  21. package/dist/compile/binds/bindEventHandlers.d.ts.map +1 -1
  22. package/dist/compile/binds/bindEventHandlers.js +2 -1
  23. package/dist/compile/binds/bindEventHandlers.js.map +1 -1
  24. package/dist/compile/binds/bindRefDirectives.d.ts.map +1 -1
  25. package/dist/compile/binds/bindRefDirectives.js +2 -1
  26. package/dist/compile/binds/bindRefDirectives.js.map +1 -1
  27. package/dist/compile/binds/bindStyleDirectives.d.ts.map +1 -1
  28. package/dist/compile/binds/bindStyleDirectives.js +2 -1
  29. package/dist/compile/binds/bindStyleDirectives.js.map +1 -1
  30. package/dist/compile/binds/bindTextInterpolations.d.ts +2 -1
  31. package/dist/compile/binds/bindTextInterpolations.d.ts.map +1 -1
  32. package/dist/compile/binds/bindTextInterpolations.js +25 -14
  33. package/dist/compile/binds/bindTextInterpolations.js.map +1 -1
  34. package/dist/compile/binds/declaredDirective.d.ts +12 -0
  35. package/dist/compile/binds/declaredDirective.d.ts.map +1 -0
  36. package/dist/compile/binds/declaredDirective.js +42 -0
  37. package/dist/compile/binds/declaredDirective.js.map +1 -0
  38. package/dist/compile/binds/forwardedAttrs.d.ts +4 -2
  39. package/dist/compile/binds/forwardedAttrs.d.ts.map +1 -1
  40. package/dist/compile/binds/forwardedAttrs.js +10 -2
  41. package/dist/compile/binds/forwardedAttrs.js.map +1 -1
  42. package/dist/compile/binds/staleRowProps.d.ts +9 -0
  43. package/dist/compile/binds/staleRowProps.d.ts.map +1 -0
  44. package/dist/compile/binds/staleRowProps.js +86 -0
  45. package/dist/compile/binds/staleRowProps.js.map +1 -0
  46. package/dist/compile/forLoops/loopSignals.d.ts.map +1 -1
  47. package/dist/compile/forLoops/loopSignals.js +15 -1
  48. package/dist/compile/forLoops/loopSignals.js.map +1 -1
  49. package/dist/compile/nodeExpando.d.ts +6 -0
  50. package/dist/compile/nodeExpando.d.ts.map +1 -1
  51. package/dist/compile/nodeExpando.js.map +1 -1
  52. package/dist/compile/pithyTreeToDom.js +1 -0
  53. package/dist/compile/pithyTreeToDom.js.map +1 -1
  54. package/dist/compile/renderChildren.d.ts.map +1 -1
  55. package/dist/compile/renderChildren.js +1 -1
  56. package/dist/compile/renderChildren.js.map +1 -1
  57. package/dist/runtime/applyBindings.d.ts.map +1 -1
  58. package/dist/runtime/applyBindings.js +3 -1
  59. package/dist/runtime/applyBindings.js.map +1 -1
  60. package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
  61. package/dist/runtime/bindings/applyComponent.js +9 -0
  62. package/dist/runtime/bindings/applyComponent.js.map +1 -1
  63. package/dist/runtime/bindings/applyDefer.d.ts.map +1 -1
  64. package/dist/runtime/bindings/applyDefer.js +10 -9
  65. package/dist/runtime/bindings/applyDefer.js.map +1 -1
  66. package/dist/runtime/bindings/applySimple.d.ts +2 -0
  67. package/dist/runtime/bindings/applySimple.d.ts.map +1 -1
  68. package/dist/runtime/bindings/applySimple.js +48 -8
  69. package/dist/runtime/bindings/applySimple.js.map +1 -1
  70. package/dist/runtime/bindings/helpers.d.ts.map +1 -1
  71. package/dist/runtime/bindings/helpers.js +2 -0
  72. package/dist/runtime/bindings/helpers.js.map +1 -1
  73. package/dist/runtime/bindings/index.d.ts +1 -1
  74. package/dist/runtime/bindings/index.d.ts.map +1 -1
  75. package/dist/runtime/bindings/index.js +1 -1
  76. package/dist/runtime/bindings/index.js.map +1 -1
  77. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"bindDefaultTwoWay.js","sourceRoot":"","sources":["../../../src/compile/binds/bindDefaultTwoWay.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAQpD,sDAAsD;AACtD,SAAS,aAAa,CAAC,OAAgB;IACrC,OAAO,OAAO,YAAY,WAAW,CAAC;AACxC,CAAC;AAED,8CAA8C;AAC9C,SAAS,gBAAgB,CAAC,MAAe;IACvC,OAAO,CACL,QAAQ,CAAC,MAAM,CAAC,IAAI,OAAQ,MAAyB,CAAC,GAAG,KAAK,UAAU,CACzE,CAAC;AACJ,CAAC;AACD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,qOAAqO;AACrO,MAAM,UAAU,iBAAiB,CAC/B,QAAoC,EACpC,OAAgC,EAChC,SAAyB;IAEzB,QAAQ,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QACzD,8CAA8C;QAC9C,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE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AsB,CAAC;QACvC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QAC1B,IAAI,IAAI,KAAK,QAAQ,EAAE,CAAC;YACtB,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACvC,OAAO,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC;QACpD,CAAC;QACD,OAAO,OAAO,CAAC,KAAK,CAAC;IACvB,CAAC;IAED,IAAI,GAAG,KAAK,UAAU,EAAE,CAAC;QACvB,OAAQ,EAA0B,CAAC,KAAK,CAAC;IAC3C,CAAC;IAED,IAAI,GAAG,KAAK,QAAQ,EAAE,CAAC;QACrB,OAAQ,EAAwB,CAAC,KAAK,CAAC;IACzC,CAAC;IAED,OAAQ,EAA4C,CAAC,IAAI,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.two-way-binding\",\n \"title\": \"Two-Way Data Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { effect, isSignal } from '@pithyjs/signals';\n\n// Define a type for writable signals\ninterface WritableSignal<T = unknown> {\n (): T;\n set(value: T): void;\n}\n\n// Type guard to check if an element is an HTMLElement\nfunction isHTMLElement(element: Element): element is HTMLElement {\n return element instanceof HTMLElement;\n}\n\n// Type guard to check if a signal is writable\nfunction isWritableSignal(signal: unknown): signal is WritableSignal {\n return (\n isSignal(signal) && typeof (signal as WritableSignal).set === 'function'\n );\n}\n/**\n * Establishes two-way data binding between HTML elements with `data-bind` attributes and writable signals.\n *\n * This function scans the provided fragment for elements with `data-bind` attributes and creates\n * bidirectional synchronization between the DOM elements and their corresponding signals in the context.\n *\n * **How it works:**\n * 1. Finds all elements with `data-bind` attributes within the fragment\n * 2. For each element, retrieves the corresponding signal from the context using the attribute value\n * 3. Sets up reactive updates: when the signal changes, the DOM element is updated\n * 4. Sets up event listeners: when the user interacts with the element, the signal is updated\n * 5. Automatically infers the appropriate property and event based on the element type\n *\n * **Supported elements:**\n * - `<input>` elements: binds to `value` property (or `checked` for checkboxes/radio buttons)\n * - `<textarea>` elements: binds to `value` property\n * - `<select>` elements: binds to `value` property\n * - Other elements: falls back to `value` property\n *\n * @param fragment - The DOM fragment or element to search for bindable elements\n * @param context - Object containing the signals referenced by `data-bind` attributes\n * @param disposers - Array to collect cleanup functions for proper resource disposal\n *\n * @throws Will log warnings for elements that are not HTMLElements or signals that are not writable\n */\n\n/** @codexApi {\"parent\":\"pithy.runtime.two-way-binding\",\"name\":\"bindDefaultTwoWay\",\"stability\":\"stable\",\"signature\":\"(fragment: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindDefaultTwoWay(\n fragment: Element | DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n fragment.querySelectorAll('[data-bind]').forEach(element => {\n // Type guard to ensure we have an HTMLElement\n if (!isHTMLElement(element)) {\n console.warn(\n `[PithyJS] Element with data-bind is not an HTMLElement:`,\n element\n );\n return;\n }\n\n const el = element; // Now TypeScript knows this is HTMLElement\n\n Array.from(el.attributes).forEach(attr => {\n if (attr.name !== 'data-bind') return;\n\n const signal = context[attr.value];\n\n if (!isWritableSignal(signal)) {\n console.warn(\n `[PithyJS] @bind=\"${attr.value}\" must refer to a writable signal`\n );\n return;\n }\n\n const prop = inferBindableProperty(el);\n const target = el as HTMLElement & Record<string, unknown>;\n\n // Reactive update: signal → DOM\n const effectDisposer = effect(() => {\n const value = signal();\n const currentValue = target[prop];\n if (currentValue !== value) {\n target[prop] = value;\n }\n });\n\n // Event listener: DOM → signal\n const event = inferBindableEvent(el, prop);\n const eventHandler = () => {\n const newVal = extractBindableValue(el, prop);\n signal.set(newVal);\n };\n\n el.addEventListener(event, eventHandler);\n el.removeAttribute('data-bind');\n\n // Add proper cleanup\n disposers.push(() => {\n el.removeEventListener(event, eventHandler);\n if (typeof effectDisposer === 'function') {\n effectDisposer();\n }\n });\n });\n });\n}\n\nfunction inferBindableProperty(el: HTMLElement): string {\n const tag = el.tagName.toLowerCase();\n\n if (tag === 'input') {\n const inputEl = el as HTMLInputElement;\n const type = inputEl.type;\n if (type === 'checkbox' || type === 'radio') return 'checked';\n return 'value';\n }\n\n if (tag === 'textarea') return 'value';\n if (tag === 'select') return 'value';\n\n return 'value'; // fallback\n}\n\nfunction inferBindableEvent(el: HTMLElement, prop: string): string {\n if (prop === 'checked') return 'change';\n return 'input';\n}\n\nfunction extractBindableValue(el: HTMLElement, prop: string): unknown {\n if (prop === 'checked') {\n return (el as HTMLInputElement).checked;\n }\n\n const tag = el.tagName.toLowerCase();\n if (tag === 'input') {\n const inputEl = el as HTMLInputElement;\n const type = inputEl.type;\n if (type === 'number') {\n const numValue = Number(inputEl.value);\n return isNaN(numValue) ? inputEl.value : numValue;\n }\n return inputEl.value;\n }\n\n if (tag === 'textarea') {\n return (el as HTMLTextAreaElement).value;\n }\n\n if (tag === 'select') {\n return (el as HTMLSelectElement).value;\n }\n\n return (el as HTMLElement & Record<string, unknown>)[prop];\n}\n"]}
1
+ {"version":3,"file":"bindDefaultTwoWay.js","sourceRoot":"","sources":["../../../src/compile/binds/bindDefaultTwoWay.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAQpD,sDAAsD;AACtD,SAAS,aAAa,CAAC,OAAgB;IACrC,OAAO,OAAO,YAAY,WAAW,CAAC;AACxC,CAAC;AAED,8CAA8C;AAC9C,SAAS,gBAAgB,CAAC,MAAe;IACvC,OAAO,CACL,QAAQ,CAAC,MAAM,CAAC,IAAI,OAAQ,MAAyB,CAAC,GAAG,KAAK,UAAU,CACzE,CAAC;AACJ,CAAC;AACD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,qOAAqO;A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AAC,EAAe,EAAE,IAAY;IACzD,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,OAAQ,EAAuB,CAAC,OAAO,CAAC;IAC1C,CAAC;IAED,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;IACrC,IAAI,GAAG,KAAK,OAAO,EAAE,CAAC;QACpB,MAAM,OAAO,GAAG,EAAsB,CAAC;QACvC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QAC1B,IAAI,IAAI,KAAK,QAAQ,EAAE,CAAC;YACtB,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACvC,OAAO,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC;QACpD,CAAC;QACD,OAAO,OAAO,CAAC,KAAK,CAAC;IACvB,CAAC;IAED,IAAI,GAAG,KAAK,UAAU,EAAE,CAAC;QACvB,OAAQ,EAA0B,CAAC,KAAK,CAAC;IAC3C,CAAC;IAED,IAAI,GAAG,KAAK,QAAQ,EAAE,CAAC;QACrB,OAAQ,EAAwB,CAAC,KAAK,CAAC;IACzC,CAAC;IAED,OAAQ,EAA4C,CAAC,IAAI,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.two-way-binding\",\n \"title\": \"Two-Way Data Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { isDeclaredDirective } from './declaredDirective';\nimport { effect, isSignal } from '@pithyjs/signals';\n\n// Define a type for writable signals\ninterface WritableSignal<T = unknown> {\n (): T;\n set(value: T): void;\n}\n\n// Type guard to check if an element is an HTMLElement\nfunction isHTMLElement(element: Element): element is HTMLElement {\n return element instanceof HTMLElement;\n}\n\n// Type guard to check if a signal is writable\nfunction isWritableSignal(signal: unknown): signal is WritableSignal {\n return (\n isSignal(signal) && typeof (signal as WritableSignal).set === 'function'\n );\n}\n/**\n * Establishes two-way data binding between HTML elements with `data-bind` attributes and writable signals.\n *\n * This function scans the provided fragment for elements with `data-bind` attributes and creates\n * bidirectional synchronization between the DOM elements and their corresponding signals in the context.\n *\n * **How it works:**\n * 1. Finds all elements with `data-bind` attributes within the fragment\n * 2. For each element, retrieves the corresponding signal from the context using the attribute value\n * 3. Sets up reactive updates: when the signal changes, the DOM element is updated\n * 4. Sets up event listeners: when the user interacts with the element, the signal is updated\n * 5. Automatically infers the appropriate property and event based on the element type\n *\n * **Supported elements:**\n * - `<input>` elements: binds to `value` property (or `checked` for checkboxes/radio buttons)\n * - `<textarea>` elements: binds to `value` property\n * - `<select>` elements: binds to `value` property\n * - Other elements: falls back to `value` property\n *\n * @param fragment - The DOM fragment or element to search for bindable elements\n * @param context - Object containing the signals referenced by `data-bind` attributes\n * @param disposers - Array to collect cleanup functions for proper resource disposal\n *\n * @throws Will log warnings for elements that are not HTMLElements or signals that are not writable\n */\n\n/** @codexApi {\"parent\":\"pithy.runtime.two-way-binding\",\"name\":\"bindDefaultTwoWay\",\"stability\":\"stable\",\"signature\":\"(fragment: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindDefaultTwoWay(\n fragment: Element | DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n fragment.querySelectorAll('[data-bind]').forEach(element => {\n // Type guard to ensure we have an HTMLElement\n if (!isHTMLElement(element)) {\n console.warn(\n `[PithyJS] Element with data-bind is not an HTMLElement:`,\n element\n );\n return;\n }\n\n const el = element; // Now TypeScript knows this is HTMLElement\n\n Array.from(el.attributes).forEach(attr => {\n if (attr.name !== 'data-bind' || !isDeclaredDirective(attr)) return;\n\n const signal = context[attr.value];\n\n if (!isWritableSignal(signal)) {\n console.warn(\n `[PithyJS] @bind=\"${attr.value}\" must refer to a writable signal`\n );\n return;\n }\n\n const prop = inferBindableProperty(el);\n const target = el as HTMLElement & Record<string, unknown>;\n\n // Reactive update: signal → DOM\n const effectDisposer = effect(() => {\n const value = signal();\n const currentValue = target[prop];\n if (currentValue !== value) {\n target[prop] = value;\n }\n });\n\n // Event listener: DOM → signal\n const event = inferBindableEvent(el, prop);\n const eventHandler = () => {\n const newVal = extractBindableValue(el, prop);\n signal.set(newVal);\n };\n\n el.addEventListener(event, eventHandler);\n el.removeAttribute('data-bind');\n\n // Add proper cleanup\n disposers.push(() => {\n el.removeEventListener(event, eventHandler);\n if (typeof effectDisposer === 'function') {\n effectDisposer();\n }\n });\n });\n });\n}\n\nfunction inferBindableProperty(el: HTMLElement): string {\n const tag = el.tagName.toLowerCase();\n\n if (tag === 'input') {\n const inputEl = el as HTMLInputElement;\n const type = inputEl.type;\n if (type === 'checkbox' || type === 'radio') return 'checked';\n return 'value';\n }\n\n if (tag === 'textarea') return 'value';\n if (tag === 'select') return 'value';\n\n return 'value'; // fallback\n}\n\nfunction inferBindableEvent(el: HTMLElement, prop: string): string {\n if (prop === 'checked') return 'change';\n return 'input';\n}\n\nfunction extractBindableValue(el: HTMLElement, prop: string): unknown {\n if (prop === 'checked') {\n return (el as HTMLInputElement).checked;\n }\n\n const tag = el.tagName.toLowerCase();\n if (tag === 'input') {\n const inputEl = el as HTMLInputElement;\n const type = inputEl.type;\n if (type === 'number') {\n const numValue = Number(inputEl.value);\n return isNaN(numValue) ? inputEl.value : numValue;\n }\n return inputEl.value;\n }\n\n if (tag === 'textarea') {\n return (el as HTMLTextAreaElement).value;\n }\n\n if (tag === 'select') {\n return (el as HTMLSelectElement).value;\n }\n\n return (el as HTMLElement & Record<string, unknown>)[prop];\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bindDeferDirectives.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindDeferDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAmCF;;;;;;;;;;GAUG;AACH,mOAAmO;AACnO,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,gBAAgB,EAC1B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,KAAK,CAAC,MAAM,IAAI,CAAC,GAC3B,IAAI,CAkiBN"}
1
+ {"version":3,"file":"bindDeferDirectives.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindDeferDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAqCF;;;;;;;;;;GAUG;AACH,mOAAmO;AACnO,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,gBAAgB,EAC1B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,KAAK,CAAC,MAAM,IAAI,CAAC,GAC3B,IAAI,CAoiBN"}
@@ -16,9 +16,11 @@
16
16
  import { createRoot, effect } from '@pithyjs/signals';
17
17
  import { DEFAULT_LAZY_TIMEOUT, } from '@pithyjs/compiler';
18
18
  import { compileExpression } from '../compileExpression.js';
19
+ import { declaredValue } from './declaredDirective.js';
19
20
  import { DEFAULT_VISIBILITY_MARGIN, isLazyHandle, observeVisibilityOnce, } from '../../runtime/index.js';
20
21
  import { boundaryForElement, setBoundaryError } from './bindErrorBoundary.js';
21
22
  import { loadWithTimeout, scheduleByPriority, } from '../../runtime/deferHelpers.js';
23
+ import { setStyleProp } from './bindBoundAttributes.js';
22
24
  /** Unique ID counter for defer anchors */
23
25
  let deferIdCounter = 0;
24
26
  /**
@@ -43,12 +45,12 @@ export function bindDeferDirectives(fragment, context, disposers) {
43
45
  if (element.hasAttribute('data-defer-state'))
44
46
  continue;
45
47
  // Read directive values from data attributes
46
- const trigger = element.dataset.defer;
47
- const loadExpr = element.dataset.load;
48
- const placeholderExpr = element.dataset.placeholder;
49
- const whenExpr = element.dataset.when;
50
- const priority = element.dataset.deferPriority;
51
- const timeoutStr = element.dataset.deferTimeout;
48
+ const trigger = declaredValue(element, 'data-defer');
49
+ const loadExpr = declaredValue(element, 'data-load');
50
+ const placeholderExpr = declaredValue(element, 'data-placeholder');
51
+ const whenExpr = declaredValue(element, 'data-when');
52
+ const priority = declaredValue(element, 'data-defer-priority');
53
+ const timeoutStr = declaredValue(element, 'data-defer-timeout');
52
54
  const timeout = timeoutStr ? parseInt(timeoutStr, 10) : undefined;
53
55
  // Validate required attributes
54
56
  if (!trigger) {
@@ -131,7 +133,7 @@ export function bindDeferDirectives(fragment, context, disposers) {
131
133
  // Add data attribute for test accessibility
132
134
  errorEl.setAttribute('data-defer-error', deferId);
133
135
  // Keep error slot hidden until needed
134
- errorEl.style.display = 'none';
136
+ setStyleProp(errorEl, 'display', 'none');
135
137
  }
136
138
  // Insert anchor and placeholder
137
139
  const parent = element.parentNode;
@@ -142,7 +144,7 @@ export function bindDeferDirectives(fragment, context, disposers) {
142
144
  // For @defer="when", placeholder starts hidden (only shows during loading)
143
145
  // For @defer="visible", placeholder shows immediately (triggers on visibility)
144
146
  if (trigger === 'when' && placeholderEl instanceof HTMLElement) {
145
- placeholderEl.style.display = 'none';
147
+ setStyleProp(placeholderEl, 'display', 'none');
146
148
  }
147
149
  parent.insertBefore(placeholderEl, element);
148
150
  }
@@ -151,7 +153,7 @@ export function bindDeferDirectives(fragment, context, disposers) {
151
153
  parent.insertBefore(errorEl, element);
152
154
  }
153
155
  // Hide the original element (it becomes the container after load)
154
- element.style.display = 'none';
156
+ setStyleProp(element, 'display', 'none');
155
157
  // Track mounted component for cleanup
156
158
  let mountedDestroy = null;
157
159
  let disposeMountedSetup = null;
@@ -208,7 +210,7 @@ export function bindDeferDirectives(fragment, context, disposers) {
208
210
  isMounted = false;
209
211
  // Hide placeholder if it was shown during a cancelled in-flight mount
210
212
  if (placeholderEl && placeholderEl instanceof HTMLElement) {
211
- placeholderEl.style.display = 'none';
213
+ setStyleProp(placeholderEl, 'display', 'none');
212
214
  }
213
215
  // Reset state to pending (ready for re-mount on next trigger)
214
216
  element.setAttribute('data-defer-state', 'pending');
@@ -226,7 +228,7 @@ export function bindDeferDirectives(fragment, context, disposers) {
226
228
  element.setAttribute('data-defer-state', 'loading');
227
229
  // Show placeholder during loading (for @defer="when" it starts hidden)
228
230
  if (placeholderEl && placeholderEl instanceof HTMLElement) {
229
- placeholderEl.style.display = '';
231
+ setStyleProp(placeholderEl, 'display', null);
230
232
  }
231
233
  try {
232
234
  // Load the module with timeout (chunk is cached after first load)
@@ -321,7 +323,7 @@ export function bindDeferDirectives(fragment, context, disposers) {
321
323
  }
322
324
  else if (errorEl) {
323
325
  // No error boundary - fall back to local error slot
324
- errorEl.style.display = '';
326
+ setStyleProp(errorEl, 'display', null);
325
327
  }
326
328
  // Dispatch error event (for programmatic handling)
327
329
  element.dispatchEvent(new CustomEvent('error', {
@@ -330,7 +332,7 @@ export function bindDeferDirectives(fragment, context, disposers) {
330
332
  retry: () => {
331
333
  // Hide error, re-show placeholder if we had one
332
334
  if (errorEl) {
333
- errorEl.style.display = 'none';
335
+ setStyleProp(errorEl, 'display', 'none');
334
336
  }
335
337
  lazyHandle.retry().then(mountComponent);
336
338
  },
@@ -417,7 +419,7 @@ export function bindDeferDirectives(fragment, context, disposers) {
417
419
  elementState === 'error') {
418
420
  // Hide error slot
419
421
  if (errorEl) {
420
- errorEl.style.display = 'none';
422
+ setStyleProp(errorEl, 'display', 'none');
421
423
  }
422
424
  // Mount the component - it will handle state transitions
423
425
  mountComponent();
@@ -476,7 +478,7 @@ export function bindDeferDirectives(fragment, context, disposers) {
476
478
  }
477
479
  // Hide error slot when condition becomes false (after a failed load)
478
480
  if (errorEl) {
479
- errorEl.style.display = 'none';
481
+ setStyleProp(errorEl, 'display', 'none');
480
482
  }
481
483
  }
482
484
  });
@@ -1 +1 @@
1
- {"version":3,"file":"bindDeferDirectives.js","sourceRoot":"","sources":["../../../src/compile/binds/bindDeferDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EACL,oBAAoB,GAGrB,MAAM,mBAAmB,CAAC;AAC3B,OA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AiB,CACvC,QAAQ,EACR,OAAO,EACP,KAAK,CACN,CAAC;YAEF,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,EAAE;gBAC7B,MAAM,UAAU,GAAG,eAAe,EAAE,CAAC;gBAErC,IAAI,UAAU,EAAE,CAAC;oBACf,4EAA4E;oBAC5E,IAAI,CAAC,SAAS,IAAI,CAAC,UAAU,IAAI,CAAC,cAAc,EAAE,CAAC;wBACjD,YAAY,EAAE,CAAC;oBACjB,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,0EAA0E;oBAC1E,kBAAkB,EAAE,CAAC;oBAErB,iDAAiD;oBACjD,uEAAuE;oBACvE,IAAI,SAAS,IAAI,UAAU,EAAE,CAAC;wBAC5B,gBAAgB,EAAE,CAAC;oBACrB,CAAC;oBACD,qEAAqE;oBACrE,IAAI,OAAO,EAAE,CAAC;wBACZ,OAAO,CAAC,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC;oBACjC,CAAC;gBACH,CAAC;YACH,CAAC,CAAC,CAAC;YAEH,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE;gBAClB,UAAU,EAAE,CAAC;gBACb,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC,CAAC;QACL,CAAC;aAAM,CAAC;YACN,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;gBACzB,OAAO,CAAC,IAAI,CAAC,gDAAgD,EAAE,OAAO,CAAC,CAAC;YAC1E,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.core.bind-defer-directives\",\n \"title\": \"Defer Directive Binder for Lazy Loading\",\n \"category\": \"directive\"\n}\n*/\n\n/**\n * Lazy Loading Directive Binder\n *\n * Handles @defer directives to lazily load components based on\n * visibility (IntersectionObserver) or boolean conditions.\n *\n * @module compile/binds/bindDeferDirectives\n */\n\nimport { createRoot, effect } from '@pithyjs/signals';\nimport {\n DEFAULT_LAZY_TIMEOUT,\n type DeferTrigger,\n type LoadingPriority,\n} from '@pithyjs/compiler';\nimport { compileExpression } from '../compileExpression';\n\nimport {\n DEFAULT_VISIBILITY_MARGIN,\n isLazyHandle,\n observeVisibilityOnce,\n type LazyHandle,\n} from '../../runtime';\n\nimport { boundaryForElement, setBoundaryError } from './bindErrorBoundary';\nimport {\n loadWithTimeout,\n scheduleByPriority,\n} from '../../runtime/deferHelpers';\n\n/** Unique ID counter for defer anchors */\nlet deferIdCounter = 0;\n\n/**\n * Bind @defer directives to enable lazy loading of components.\n *\n * Supports two trigger modes:\n * - `visible`: Load when element scrolls into viewport (IntersectionObserver)\n * - `when`: Load when a boolean expression becomes truthy\n *\n * @param fragment - The root document fragment\n * @param context - Template context with signals and lazy handles\n * @param disposers - Array to collect cleanup functions\n */\n/** @codexApi {\"parent\":\"pithy.core.bind-defer-directives\",\"name\":\"bindDeferDirectives\",\"stability\":\"stable\",\"signature\":\"(fragment: DocumentFragment, context: Record<string, unknown>, disposers: Array<() => void>) => void\"} */\nexport function bindDeferDirectives(\n fragment: DocumentFragment,\n context: Record<string, unknown>,\n disposers: Array<() => void>\n): void {\n // Find all elements with @defer directive\n const deferElements = fragment.querySelectorAll('[data-defer]');\n\n for (const el of deferElements) {\n const element = el as HTMLElement;\n\n // Skip elements already processed (e.g., inside component subtrees that\n // ran their own bindDeferDirectives before being inserted into the outer DOM)\n if (element.hasAttribute('data-defer-state')) continue;\n\n // Read directive values from data attributes\n const trigger = element.dataset.defer as DeferTrigger | undefined;\n const loadExpr = element.dataset.load;\n const placeholderExpr = element.dataset.placeholder;\n const whenExpr = element.dataset.when;\n const priority = element.dataset.deferPriority as\n | LoadingPriority\n | undefined;\n const timeoutStr = element.dataset.deferTimeout;\n const timeout = timeoutStr ? parseInt(timeoutStr, 10) : undefined;\n\n // Validate required attributes\n if (!trigger) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer element missing trigger type', element);\n }\n continue;\n }\n\n if (!loadExpr) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer element missing @load directive', element);\n }\n continue;\n }\n\n // Get the lazy handle from context\n const lazyHandleGetter = compileExpression<LazyHandle<unknown>>(\n loadExpr,\n context,\n undefined\n );\n const lazyHandle = lazyHandleGetter();\n\n if (!isLazyHandle(lazyHandle)) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[pithy] @load=\"${loadExpr}\" did not resolve to a LazyHandle`,\n element\n );\n }\n continue;\n }\n\n // Use existing data-defer-id or generate a unique one\n const existingId = element.getAttribute('data-defer-id');\n const deferId = existingId || `defer-${++deferIdCounter}`;\n\n // Set data attributes for SSR markers (preserve existing ID if present)\n if (!existingId) {\n element.setAttribute('data-defer-id', deferId);\n }\n element.setAttribute('data-defer-state', 'pending');\n\n // Create anchor comment\n const anchor = document.createComment(`defer:${deferId}`);\n\n // Setup placeholder - check both data-placeholder attribute and slot=\"placeholder\" children\n let placeholderEl: HTMLElement | Text | null = null;\n\n // First, try to extract slot=\"placeholder\" from element children\n const slotPlaceholder = element.querySelector('[slot=\"placeholder\"]');\n if (slotPlaceholder) {\n // Remove from original parent and use as placeholder\n placeholderEl = slotPlaceholder as HTMLElement;\n placeholderEl.removeAttribute('slot');\n // Add data attribute for test accessibility\n placeholderEl.setAttribute('data-defer-placeholder', deferId);\n } else if (placeholderExpr) {\n // Fallback to data-placeholder attribute\n // Check if it's a string literal\n if (\n (placeholderExpr.startsWith(\"'\") && placeholderExpr.endsWith(\"'\")) ||\n (placeholderExpr.startsWith('\"') && placeholderExpr.endsWith('\"'))\n ) {\n // String placeholder\n const text = placeholderExpr.slice(1, -1);\n placeholderEl = document.createTextNode(text) as unknown as HTMLElement;\n } else {\n // Component placeholder - get from context\n const placeholderGetter = compileExpression<unknown>(\n placeholderExpr,\n context,\n null\n );\n const placeholder = placeholderGetter();\n\n if (typeof placeholder === 'function') {\n // It's a component function\n try {\n const result = (placeholder as () => unknown)();\n if (result && typeof result === 'object' && 'el' in result) {\n placeholderEl = (result as { el: HTMLElement }).el as HTMLElement;\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[pithy] Error rendering placeholder component:`,\n err\n );\n }\n }\n }\n }\n }\n\n // Also extract slot=\"error\" for error handling\n const slotError = element.querySelector('[slot=\"error\"]');\n let errorEl: HTMLElement | null = null;\n if (slotError) {\n errorEl = slotError as HTMLElement;\n errorEl.removeAttribute('slot');\n // Add data attribute for test accessibility\n errorEl.setAttribute('data-defer-error', deferId);\n // Keep error slot hidden until needed\n errorEl.style.display = 'none';\n }\n\n // Insert anchor and placeholder\n const parent = element.parentNode;\n if (!parent) continue;\n\n parent.insertBefore(anchor, element);\n\n if (placeholderEl) {\n // For @defer=\"when\", placeholder starts hidden (only shows during loading)\n // For @defer=\"visible\", placeholder shows immediately (triggers on visibility)\n if (trigger === 'when' && placeholderEl instanceof HTMLElement) {\n placeholderEl.style.display = 'none';\n }\n parent.insertBefore(placeholderEl, element);\n }\n\n // Insert error element (hidden) after placeholder\n if (errorEl) {\n parent.insertBefore(errorEl, element);\n }\n\n // Hide the original element (it becomes the container after load)\n element.style.display = 'none';\n\n // Track mounted component for cleanup\n let mountedDestroy: (() => void) | null = null;\n let disposeMountedSetup: (() => void) | null = null;\n let isMounted = false;\n let isMounting = false; // true while an async mount is in-flight\n\n // Mount generation counter — incremented on every unmount/cleanup to\n // invalidate in-flight async mounts that started before the unmount.\n let mountGeneration = 0;\n\n // Track inserted nodes directly (no wrapper div)\n let insertedNodes: Node[] = [];\n\n /**\n * Run and clear the mounted instance's teardown. Claimed before DOM\n * insertion, so a throw between the two still reaches it.\n */\n function releaseMountedComponent(): void {\n const destroyMounted = mountedDestroy;\n const disposeSetup = disposeMountedSetup;\n mountedDestroy = null;\n disposeMountedSetup = null;\n try {\n destroyMounted?.();\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer error in component destroy():', err);\n }\n } finally {\n try {\n disposeSetup?.();\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer error in setup cleanup:', err);\n }\n }\n }\n }\n\n /**\n * Remove mounted component nodes from DOM\n */\n function unmountComponent(): void {\n // Invalidate any in-flight async mount\n mountGeneration++;\n isMounting = false;\n\n releaseMountedComponent();\n\n // Remove all inserted nodes\n for (const node of insertedNodes) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n insertedNodes = [];\n isMounted = false;\n\n // Hide placeholder if it was shown during a cancelled in-flight mount\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n placeholderEl.style.display = 'none';\n }\n\n // Reset state to pending (ready for re-mount on next trigger)\n element.setAttribute('data-defer-state', 'pending');\n }\n\n /**\n * Mount the lazy component with timeout support\n */\n async function mountComponent(): Promise<void> {\n // If already mounted or a mount is in-flight, skip\n if (isMounted || isMounting) return;\n\n isMounting = true;\n\n // Capture generation so we can detect if an unmount happened while awaiting\n const thisGeneration = mountGeneration;\n\n element.setAttribute('data-defer-state', 'loading');\n\n // Show placeholder during loading (for @defer=\"when\" it starts hidden)\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n placeholderEl.style.display = '';\n }\n\n try {\n // Load the module with timeout (chunk is cached after first load)\n const effectiveTimeout = timeout ?? DEFAULT_LAZY_TIMEOUT;\n const module = await loadWithTimeout(lazyHandle, effectiveTimeout);\n\n // Check if an unmount/cleanup happened during async load (generation changed)\n if (thisGeneration !== mountGeneration) {\n isMounting = false;\n return;\n }\n\n // Use fresh parentNode — the element may have been moved into the real DOM\n // by bindComponentTags.replaceWith() during the async gap\n const freshParent = element.parentNode;\n if (!freshParent) {\n isMounting = false;\n return;\n }\n\n element.setAttribute('data-defer-state', 'loaded');\n\n // Remove placeholder\n if (placeholderEl && placeholderEl.parentNode) {\n placeholderEl.parentNode.removeChild(placeholderEl);\n placeholderEl = null;\n }\n\n // Remove error element (no longer needed on success)\n if (errorEl && errorEl.parentNode) {\n errorEl.parentNode.removeChild(errorEl);\n errorEl = null;\n }\n\n // Get the component from the module\n const Component = (module as { default?: unknown }).default || module;\n\n if (typeof Component === 'function') {\n // Render the component\n let disposeSetup: (() => void) | undefined;\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return (Component as () => unknown)();\n });\n\n if (result && typeof result === 'object' && 'el' in result) {\n const { el, destroy } = result as {\n el: HTMLElement | DocumentFragment;\n destroy?: () => void;\n };\n\n mountedDestroy = destroy ?? null;\n disposeMountedSetup = disposeSetup ?? null;\n\n // Insert component content directly (no wrapper div)\n if (el instanceof DocumentFragment) {\n // Track all children before moving them\n const nodes = Array.from(el.childNodes);\n insertedNodes = nodes;\n // Insert fragment directly - this moves all children to the DOM\n freshParent.insertBefore(el, element);\n } else {\n insertedNodes = [el];\n freshParent.insertBefore(el, element);\n }\n\n isMounted = true;\n isMounting = false;\n\n // Dispatch loaded event\n element.dispatchEvent(\n new CustomEvent('loaded', {\n detail: {\n ttiMs: Date.now(), // Could track actual load time\n chunkId: lazyHandle.key,\n },\n bubbles: true,\n })\n );\n } else {\n disposeSetup?.();\n isMounting = false;\n }\n } else {\n isMounting = false;\n }\n } catch (err) {\n isMounting = false;\n if (!isMounted) releaseMountedComponent();\n\n // Check if an unmount/cleanup happened during async load\n if (thisGeneration !== mountGeneration) return;\n\n element.setAttribute('data-defer-state', 'error');\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n // Remove placeholder and show error slot if available\n if (placeholderEl && placeholderEl.parentNode) {\n placeholderEl.parentNode.removeChild(placeholderEl);\n placeholderEl = null;\n }\n\n // Propagate error to nearest error boundary (if one exists)\n const boundary = boundaryForElement(element);\n if (boundary) {\n setBoundaryError(boundary, error);\n } else if (errorEl) {\n // No error boundary - fall back to local error slot\n errorEl.style.display = '';\n }\n\n // Dispatch error event (for programmatic handling)\n element.dispatchEvent(\n new CustomEvent('error', {\n detail: {\n error,\n retry: () => {\n // Hide error, re-show placeholder if we had one\n if (errorEl) {\n errorEl.style.display = 'none';\n }\n lazyHandle.retry().then(mountComponent);\n },\n },\n bubbles: true,\n })\n );\n\n if (import.meta.env?.DEV) {\n console.error(`[pithy] Failed to load lazy component:`, err);\n }\n }\n }\n\n // Track idle callback for cancellation\n let idleCallbackId: number | undefined;\n\n /**\n * Cleanup function\n */\n function cleanup(): void {\n // Cancel any scheduled-but-not-started mount\n cancelPendingMount();\n\n // Invalidate any in-flight async mount (unmountComponent also does this,\n // but we bump it here too in case unmountComponent is skipped)\n mountGeneration++;\n\n // Cancel pending idle callback (cancelPendingMount handles the scheduled\n // case, but cover the already-in-flight case too)\n if (\n idleCallbackId !== undefined &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(idleCallbackId);\n idleCallbackId = undefined;\n }\n\n // Unmount component (calls destroy and removes nodes)\n unmountComponent();\n\n // Cancel any in-flight load\n lazyHandle.cancel();\n }\n\n // Track whether a mount has been scheduled but not yet started.\n // This is needed so that unmount/cancel can invalidate pending\n // scheduled mounts (e.g., rapid toggle: true → false → true).\n let mountScheduled = false;\n\n /**\n * Trigger mount with priority scheduling\n */\n function triggerMount(): void {\n mountScheduled = true;\n // Capture current generation so the microtask can detect cancellation.\n // cancelPendingMount bumps mountGeneration, so if it fires between\n // scheduling and execution, the microtask will see the mismatch.\n const expectedGen = mountGeneration;\n const result = scheduleByPriority(() => {\n mountScheduled = false;\n if (expectedGen !== mountGeneration) return; // cancelled\n mountComponent();\n }, priority);\n\n // Track idle callback ID for cleanup\n if (typeof result === 'number') {\n idleCallbackId = result;\n }\n }\n\n /**\n * Cancel any pending scheduled mount that hasn't started yet.\n * Bumps mountGeneration to also invalidate any in-flight async mounts.\n */\n function cancelPendingMount(): void {\n if (mountScheduled) {\n mountScheduled = false;\n mountGeneration++;\n // Cancel pending idle callback if one is tracked\n if (\n idleCallbackId !== undefined &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(idleCallbackId);\n idleCallbackId = undefined;\n }\n }\n }\n\n // Subscribe to lazy handle state for external retry support\n // This allows calling lazyHandle.retry() from error slot buttons\n const stopStateEffect = effect(() => {\n const handleState = lazyHandle.state();\n const elementState = element.getAttribute('data-defer-state');\n\n // If handle loaded externally (via retry) and we're in error state, try to mount\n if (\n handleState === 'loaded' &&\n !isMounted &&\n !isMounting &&\n elementState === 'error'\n ) {\n // Hide error slot\n if (errorEl) {\n errorEl.style.display = 'none';\n }\n // Mount the component - it will handle state transitions\n mountComponent();\n }\n });\n\n disposers.push(stopStateEffect);\n\n // Setup trigger based on mode\n if (trigger === 'visible') {\n // Visibility trigger using IntersectionObserver\n // IMPORTANT: Observe the placeholder (which is visible), not the hidden element\n // If no placeholder exists, create a sentinel element to observe\n let observeTarget: Element;\n let sentinelEl: HTMLElement | null = null;\n\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n observeTarget = placeholderEl;\n } else {\n // Create a minimal sentinel element to observe\n sentinelEl = document.createElement('span');\n sentinelEl.style.display = 'inline-block';\n sentinelEl.style.width = '1px';\n sentinelEl.style.height = '1px';\n parent.insertBefore(sentinelEl, element);\n observeTarget = sentinelEl;\n }\n\n const stopObserving = observeVisibilityOnce(observeTarget, triggerMount, {\n rootMargin: DEFAULT_VISIBILITY_MARGIN,\n });\n\n disposers.push(() => {\n stopObserving();\n // Remove sentinel if we created one\n if (sentinelEl && sentinelEl.parentNode) {\n sentinelEl.parentNode.removeChild(sentinelEl);\n }\n cleanup();\n });\n } else if (trigger === 'when' && whenExpr) {\n // Boolean trigger using effect\n const conditionGetter = compileExpression<boolean>(\n whenExpr,\n context,\n false\n );\n\n const stopEffect = effect(() => {\n const shouldShow = conditionGetter();\n\n if (shouldShow) {\n // Mount component (chunk is cached after first load, so remounting is fast)\n if (!isMounted && !isMounting && !mountScheduled) {\n triggerMount();\n }\n } else {\n // Cancel any scheduled-but-not-started mount first (handles rapid toggle)\n cancelPendingMount();\n\n // Destroy component when condition becomes false\n // This is consistent with React, Vue, Angular - no automatic show/hide\n if (isMounted || isMounting) {\n unmountComponent();\n }\n // Hide error slot when condition becomes false (after a failed load)\n if (errorEl) {\n errorEl.style.display = 'none';\n }\n }\n });\n\n disposers.push(() => {\n stopEffect();\n cleanup();\n });\n } else {\n if (import.meta.env?.DEV) {\n console.warn(`[pithy] @defer=\"when\" requires @when attribute`, element);\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"bindDeferDirectives.js","sourceRoot":"","sources":["../../../src/compile/binds/bindDeferDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EACL,oBAAoB,GAGrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EACL,yBAAyB,EACzB,YAAY,EACZ,qBAAqB,GAEtB,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD,0CAA0C;AAC1C,IAAI,cAAc,GAAG,CAAC,CAAC;AAEvB;;;;;;;;;;GAUG;AACH,mOAAmO;AACnO,MAAM,UAAU,mBAAmB,CACjC,QAA0B,EAC1B,OAAgC,EAChC,SAA4B;IAE5B,0CAA0C;IAC1C,MAAM,aAAa,GAAG,QAAQ,CAAC,gBAAgB,CAAC,cAAc,CAAC,CAAC;IAEhE,KAAK,MAAM,EAAE,IAAI,aAAa,EAAE,CAAC;QAC/B,MAAM,OAAO,GAAG,EAAiB,CAAC;QAElC,wEAAwE;QACxE,8EAA8E;QAC9E,IAAI,OAAO,CAAC,YAAY,CAAC,kBAAkB,CAAC;YAAE,SAAS;QAEvD,6CAA6C;QAC7C,MAAM,OAAO,GAAG,aAAa,CAAC,OAAO,EAAE,YA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S,CAAC,IAAI,CAAC,GAAG,EAAE;gBAClB,UAAU,EAAE,CAAC;gBACb,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC,CAAC;QACL,CAAC;aAAM,CAAC;YACN,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;gBACzB,OAAO,CAAC,IAAI,CAAC,gDAAgD,EAAE,OAAO,CAAC,CAAC;YAC1E,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.core.bind-defer-directives\",\n \"title\": \"Defer Directive Binder for Lazy Loading\",\n \"category\": \"directive\"\n}\n*/\n\n/**\n * Lazy Loading Directive Binder\n *\n * Handles @defer directives to lazily load components based on\n * visibility (IntersectionObserver) or boolean conditions.\n *\n * @module compile/binds/bindDeferDirectives\n */\n\nimport { createRoot, effect } from '@pithyjs/signals';\nimport {\n DEFAULT_LAZY_TIMEOUT,\n type DeferTrigger,\n type LoadingPriority,\n} from '@pithyjs/compiler';\nimport { compileExpression } from '../compileExpression';\nimport { declaredValue } from './declaredDirective';\n\nimport {\n DEFAULT_VISIBILITY_MARGIN,\n isLazyHandle,\n observeVisibilityOnce,\n type LazyHandle,\n} from '../../runtime';\n\nimport { boundaryForElement, setBoundaryError } from './bindErrorBoundary';\nimport {\n loadWithTimeout,\n scheduleByPriority,\n} from '../../runtime/deferHelpers';\nimport { setStyleProp } from './bindBoundAttributes';\n\n/** Unique ID counter for defer anchors */\nlet deferIdCounter = 0;\n\n/**\n * Bind @defer directives to enable lazy loading of components.\n *\n * Supports two trigger modes:\n * - `visible`: Load when element scrolls into viewport (IntersectionObserver)\n * - `when`: Load when a boolean expression becomes truthy\n *\n * @param fragment - The root document fragment\n * @param context - Template context with signals and lazy handles\n * @param disposers - Array to collect cleanup functions\n */\n/** @codexApi {\"parent\":\"pithy.core.bind-defer-directives\",\"name\":\"bindDeferDirectives\",\"stability\":\"stable\",\"signature\":\"(fragment: DocumentFragment, context: Record<string, unknown>, disposers: Array<() => void>) => void\"} */\nexport function bindDeferDirectives(\n fragment: DocumentFragment,\n context: Record<string, unknown>,\n disposers: Array<() => void>\n): void {\n // Find all elements with @defer directive\n const deferElements = fragment.querySelectorAll('[data-defer]');\n\n for (const el of deferElements) {\n const element = el as HTMLElement;\n\n // Skip elements already processed (e.g., inside component subtrees that\n // ran their own bindDeferDirectives before being inserted into the outer DOM)\n if (element.hasAttribute('data-defer-state')) continue;\n\n // Read directive values from data attributes\n const trigger = declaredValue(element, 'data-defer') as\n | DeferTrigger\n | undefined;\n const loadExpr = declaredValue(element, 'data-load');\n const placeholderExpr = declaredValue(element, 'data-placeholder');\n const whenExpr = declaredValue(element, 'data-when');\n const priority = declaredValue(element, 'data-defer-priority') as\n | LoadingPriority\n | undefined;\n const timeoutStr = declaredValue(element, 'data-defer-timeout');\n const timeout = timeoutStr ? parseInt(timeoutStr, 10) : undefined;\n\n // Validate required attributes\n if (!trigger) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer element missing trigger type', element);\n }\n continue;\n }\n\n if (!loadExpr) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer element missing @load directive', element);\n }\n continue;\n }\n\n // Get the lazy handle from context\n const lazyHandleGetter = compileExpression<LazyHandle<unknown>>(\n loadExpr,\n context,\n undefined\n );\n const lazyHandle = lazyHandleGetter();\n\n if (!isLazyHandle(lazyHandle)) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[pithy] @load=\"${loadExpr}\" did not resolve to a LazyHandle`,\n element\n );\n }\n continue;\n }\n\n // Use existing data-defer-id or generate a unique one\n const existingId = element.getAttribute('data-defer-id');\n const deferId = existingId || `defer-${++deferIdCounter}`;\n\n // Set data attributes for SSR markers (preserve existing ID if present)\n if (!existingId) {\n element.setAttribute('data-defer-id', deferId);\n }\n element.setAttribute('data-defer-state', 'pending');\n\n // Create anchor comment\n const anchor = document.createComment(`defer:${deferId}`);\n\n // Setup placeholder - check both data-placeholder attribute and slot=\"placeholder\" children\n let placeholderEl: HTMLElement | Text | null = null;\n\n // First, try to extract slot=\"placeholder\" from element children\n const slotPlaceholder = element.querySelector('[slot=\"placeholder\"]');\n if (slotPlaceholder) {\n // Remove from original parent and use as placeholder\n placeholderEl = slotPlaceholder as HTMLElement;\n placeholderEl.removeAttribute('slot');\n // Add data attribute for test accessibility\n placeholderEl.setAttribute('data-defer-placeholder', deferId);\n } else if (placeholderExpr) {\n // Fallback to data-placeholder attribute\n // Check if it's a string literal\n if (\n (placeholderExpr.startsWith(\"'\") && placeholderExpr.endsWith(\"'\")) ||\n (placeholderExpr.startsWith('\"') && placeholderExpr.endsWith('\"'))\n ) {\n // String placeholder\n const text = placeholderExpr.slice(1, -1);\n placeholderEl = document.createTextNode(text) as unknown as HTMLElement;\n } else {\n // Component placeholder - get from context\n const placeholderGetter = compileExpression<unknown>(\n placeholderExpr,\n context,\n null\n );\n const placeholder = placeholderGetter();\n\n if (typeof placeholder === 'function') {\n // It's a component function\n try {\n const result = (placeholder as () => unknown)();\n if (result && typeof result === 'object' && 'el' in result) {\n placeholderEl = (result as { el: HTMLElement }).el as HTMLElement;\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[pithy] Error rendering placeholder component:`,\n err\n );\n }\n }\n }\n }\n }\n\n // Also extract slot=\"error\" for error handling\n const slotError = element.querySelector('[slot=\"error\"]');\n let errorEl: HTMLElement | null = null;\n if (slotError) {\n errorEl = slotError as HTMLElement;\n errorEl.removeAttribute('slot');\n // Add data attribute for test accessibility\n errorEl.setAttribute('data-defer-error', deferId);\n // Keep error slot hidden until needed\n setStyleProp(errorEl, 'display', 'none');\n }\n\n // Insert anchor and placeholder\n const parent = element.parentNode;\n if (!parent) continue;\n\n parent.insertBefore(anchor, element);\n\n if (placeholderEl) {\n // For @defer=\"when\", placeholder starts hidden (only shows during loading)\n // For @defer=\"visible\", placeholder shows immediately (triggers on visibility)\n if (trigger === 'when' && placeholderEl instanceof HTMLElement) {\n setStyleProp(placeholderEl, 'display', 'none');\n }\n parent.insertBefore(placeholderEl, element);\n }\n\n // Insert error element (hidden) after placeholder\n if (errorEl) {\n parent.insertBefore(errorEl, element);\n }\n\n // Hide the original element (it becomes the container after load)\n setStyleProp(element, 'display', 'none');\n\n // Track mounted component for cleanup\n let mountedDestroy: (() => void) | null = null;\n let disposeMountedSetup: (() => void) | null = null;\n let isMounted = false;\n let isMounting = false; // true while an async mount is in-flight\n\n // Mount generation counter — incremented on every unmount/cleanup to\n // invalidate in-flight async mounts that started before the unmount.\n let mountGeneration = 0;\n\n // Track inserted nodes directly (no wrapper div)\n let insertedNodes: Node[] = [];\n\n /**\n * Run and clear the mounted instance's teardown. Claimed before DOM\n * insertion, so a throw between the two still reaches it.\n */\n function releaseMountedComponent(): void {\n const destroyMounted = mountedDestroy;\n const disposeSetup = disposeMountedSetup;\n mountedDestroy = null;\n disposeMountedSetup = null;\n try {\n destroyMounted?.();\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer error in component destroy():', err);\n }\n } finally {\n try {\n disposeSetup?.();\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer error in setup cleanup:', err);\n }\n }\n }\n }\n\n /**\n * Remove mounted component nodes from DOM\n */\n function unmountComponent(): void {\n // Invalidate any in-flight async mount\n mountGeneration++;\n isMounting = false;\n\n releaseMountedComponent();\n\n // Remove all inserted nodes\n for (const node of insertedNodes) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n insertedNodes = [];\n isMounted = false;\n\n // Hide placeholder if it was shown during a cancelled in-flight mount\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n setStyleProp(placeholderEl, 'display', 'none');\n }\n\n // Reset state to pending (ready for re-mount on next trigger)\n element.setAttribute('data-defer-state', 'pending');\n }\n\n /**\n * Mount the lazy component with timeout support\n */\n async function mountComponent(): Promise<void> {\n // If already mounted or a mount is in-flight, skip\n if (isMounted || isMounting) return;\n\n isMounting = true;\n\n // Capture generation so we can detect if an unmount happened while awaiting\n const thisGeneration = mountGeneration;\n\n element.setAttribute('data-defer-state', 'loading');\n\n // Show placeholder during loading (for @defer=\"when\" it starts hidden)\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n setStyleProp(placeholderEl, 'display', null);\n }\n\n try {\n // Load the module with timeout (chunk is cached after first load)\n const effectiveTimeout = timeout ?? DEFAULT_LAZY_TIMEOUT;\n const module = await loadWithTimeout(lazyHandle, effectiveTimeout);\n\n // Check if an unmount/cleanup happened during async load (generation changed)\n if (thisGeneration !== mountGeneration) {\n isMounting = false;\n return;\n }\n\n // Use fresh parentNode — the element may have been moved into the real DOM\n // by bindComponentTags.replaceWith() during the async gap\n const freshParent = element.parentNode;\n if (!freshParent) {\n isMounting = false;\n return;\n }\n\n element.setAttribute('data-defer-state', 'loaded');\n\n // Remove placeholder\n if (placeholderEl && placeholderEl.parentNode) {\n placeholderEl.parentNode.removeChild(placeholderEl);\n placeholderEl = null;\n }\n\n // Remove error element (no longer needed on success)\n if (errorEl && errorEl.parentNode) {\n errorEl.parentNode.removeChild(errorEl);\n errorEl = null;\n }\n\n // Get the component from the module\n const Component = (module as { default?: unknown }).default || module;\n\n if (typeof Component === 'function') {\n // Render the component\n let disposeSetup: (() => void) | undefined;\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return (Component as () => unknown)();\n });\n\n if (result && typeof result === 'object' && 'el' in result) {\n const { el, destroy } = result as {\n el: HTMLElement | DocumentFragment;\n destroy?: () => void;\n };\n\n mountedDestroy = destroy ?? null;\n disposeMountedSetup = disposeSetup ?? null;\n\n // Insert component content directly (no wrapper div)\n if (el instanceof DocumentFragment) {\n // Track all children before moving them\n const nodes = Array.from(el.childNodes);\n insertedNodes = nodes;\n // Insert fragment directly - this moves all children to the DOM\n freshParent.insertBefore(el, element);\n } else {\n insertedNodes = [el];\n freshParent.insertBefore(el, element);\n }\n\n isMounted = true;\n isMounting = false;\n\n // Dispatch loaded event\n element.dispatchEvent(\n new CustomEvent('loaded', {\n detail: {\n ttiMs: Date.now(), // Could track actual load time\n chunkId: lazyHandle.key,\n },\n bubbles: true,\n })\n );\n } else {\n disposeSetup?.();\n isMounting = false;\n }\n } else {\n isMounting = false;\n }\n } catch (err) {\n isMounting = false;\n if (!isMounted) releaseMountedComponent();\n\n // Check if an unmount/cleanup happened during async load\n if (thisGeneration !== mountGeneration) return;\n\n element.setAttribute('data-defer-state', 'error');\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n // Remove placeholder and show error slot if available\n if (placeholderEl && placeholderEl.parentNode) {\n placeholderEl.parentNode.removeChild(placeholderEl);\n placeholderEl = null;\n }\n\n // Propagate error to nearest error boundary (if one exists)\n const boundary = boundaryForElement(element);\n if (boundary) {\n setBoundaryError(boundary, error);\n } else if (errorEl) {\n // No error boundary - fall back to local error slot\n setStyleProp(errorEl, 'display', null);\n }\n\n // Dispatch error event (for programmatic handling)\n element.dispatchEvent(\n new CustomEvent('error', {\n detail: {\n error,\n retry: () => {\n // Hide error, re-show placeholder if we had one\n if (errorEl) {\n setStyleProp(errorEl, 'display', 'none');\n }\n lazyHandle.retry().then(mountComponent);\n },\n },\n bubbles: true,\n })\n );\n\n if (import.meta.env?.DEV) {\n console.error(`[pithy] Failed to load lazy component:`, err);\n }\n }\n }\n\n // Track idle callback for cancellation\n let idleCallbackId: number | undefined;\n\n /**\n * Cleanup function\n */\n function cleanup(): void {\n // Cancel any scheduled-but-not-started mount\n cancelPendingMount();\n\n // Invalidate any in-flight async mount (unmountComponent also does this,\n // but we bump it here too in case unmountComponent is skipped)\n mountGeneration++;\n\n // Cancel pending idle callback (cancelPendingMount handles the scheduled\n // case, but cover the already-in-flight case too)\n if (\n idleCallbackId !== undefined &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(idleCallbackId);\n idleCallbackId = undefined;\n }\n\n // Unmount component (calls destroy and removes nodes)\n unmountComponent();\n\n // Cancel any in-flight load\n lazyHandle.cancel();\n }\n\n // Track whether a mount has been scheduled but not yet started.\n // This is needed so that unmount/cancel can invalidate pending\n // scheduled mounts (e.g., rapid toggle: true → false → true).\n let mountScheduled = false;\n\n /**\n * Trigger mount with priority scheduling\n */\n function triggerMount(): void {\n mountScheduled = true;\n // Capture current generation so the microtask can detect cancellation.\n // cancelPendingMount bumps mountGeneration, so if it fires between\n // scheduling and execution, the microtask will see the mismatch.\n const expectedGen = mountGeneration;\n const result = scheduleByPriority(() => {\n mountScheduled = false;\n if (expectedGen !== mountGeneration) return; // cancelled\n mountComponent();\n }, priority);\n\n // Track idle callback ID for cleanup\n if (typeof result === 'number') {\n idleCallbackId = result;\n }\n }\n\n /**\n * Cancel any pending scheduled mount that hasn't started yet.\n * Bumps mountGeneration to also invalidate any in-flight async mounts.\n */\n function cancelPendingMount(): void {\n if (mountScheduled) {\n mountScheduled = false;\n mountGeneration++;\n // Cancel pending idle callback if one is tracked\n if (\n idleCallbackId !== undefined &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(idleCallbackId);\n idleCallbackId = undefined;\n }\n }\n }\n\n // Subscribe to lazy handle state for external retry support\n // This allows calling lazyHandle.retry() from error slot buttons\n const stopStateEffect = effect(() => {\n const handleState = lazyHandle.state();\n const elementState = element.getAttribute('data-defer-state');\n\n // If handle loaded externally (via retry) and we're in error state, try to mount\n if (\n handleState === 'loaded' &&\n !isMounted &&\n !isMounting &&\n elementState === 'error'\n ) {\n // Hide error slot\n if (errorEl) {\n setStyleProp(errorEl, 'display', 'none');\n }\n // Mount the component - it will handle state transitions\n mountComponent();\n }\n });\n\n disposers.push(stopStateEffect);\n\n // Setup trigger based on mode\n if (trigger === 'visible') {\n // Visibility trigger using IntersectionObserver\n // IMPORTANT: Observe the placeholder (which is visible), not the hidden element\n // If no placeholder exists, create a sentinel element to observe\n let observeTarget: Element;\n let sentinelEl: HTMLElement | null = null;\n\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n observeTarget = placeholderEl;\n } else {\n // Create a minimal sentinel element to observe\n sentinelEl = document.createElement('span');\n sentinelEl.style.display = 'inline-block';\n sentinelEl.style.width = '1px';\n sentinelEl.style.height = '1px';\n parent.insertBefore(sentinelEl, element);\n observeTarget = sentinelEl;\n }\n\n const stopObserving = observeVisibilityOnce(observeTarget, triggerMount, {\n rootMargin: DEFAULT_VISIBILITY_MARGIN,\n });\n\n disposers.push(() => {\n stopObserving();\n // Remove sentinel if we created one\n if (sentinelEl && sentinelEl.parentNode) {\n sentinelEl.parentNode.removeChild(sentinelEl);\n }\n cleanup();\n });\n } else if (trigger === 'when' && whenExpr) {\n // Boolean trigger using effect\n const conditionGetter = compileExpression<boolean>(\n whenExpr,\n context,\n false\n );\n\n const stopEffect = effect(() => {\n const shouldShow = conditionGetter();\n\n if (shouldShow) {\n // Mount component (chunk is cached after first load, so remounting is fast)\n if (!isMounted && !isMounting && !mountScheduled) {\n triggerMount();\n }\n } else {\n // Cancel any scheduled-but-not-started mount first (handles rapid toggle)\n cancelPendingMount();\n\n // Destroy component when condition becomes false\n // This is consistent with React, Vue, Angular - no automatic show/hide\n if (isMounted || isMounting) {\n unmountComponent();\n }\n // Hide error slot when condition becomes false (after a failed load)\n if (errorEl) {\n setStyleProp(errorEl, 'display', 'none');\n }\n }\n });\n\n disposers.push(() => {\n stopEffect();\n cleanup();\n });\n } else {\n if (import.meta.env?.DEV) {\n console.warn(`[pithy] @defer=\"when\" requires @when attribute`, element);\n }\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bindErrorBoundary.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindErrorBoundary.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAU,MAAM,EAAW,MAAM,kBAAkB,CAAC;AAI3D;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;IAClC,eAAe,EAAE,OAAO,GAAG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H,oOAAoO;AACpO,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,OAAO,GAAG,gBAAgB,EACpC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAuCN"}
@@ -5,7 +5,9 @@
5
5
  "category": "feature"
6
6
  }
7
7
  */
8
+ import { declaredValue } from './declaredDirective.js';
8
9
  import { effect, untrack } from '@pithyjs/signals';
10
+ import { setStyleProp } from './bindBoundAttributes.js';
9
11
  const boundElements = new WeakSet();
10
12
  /**
11
13
  * Global registry of active error boundaries
@@ -404,7 +406,7 @@ function hideContent(boundary) {
404
406
  }
405
407
  // Always show the fallback element if it exists
406
408
  if (fallbackElement) {
407
- fallbackElement.style.display = '';
409
+ setStyleProp(fallbackElement, 'display', null);
408
410
  }
409
411
  }
410
412
  /**
@@ -418,7 +420,7 @@ function restoreContent(boundary) {
418
420
  contentPlaceholders.delete(node);
419
421
  }
420
422
  if (fallbackElement) {
421
- fallbackElement.style.display = 'none';
423
+ setStyleProp(fallbackElement, 'display', 'none');
422
424
  }
423
425
  }
424
426
  /**
@@ -426,7 +428,7 @@ function restoreContent(boundary) {
426
428
  * @param fallbackEl - The fallback element to hide
427
429
  */
428
430
  function hideFallback(fallbackEl) {
429
- fallbackEl.style.display = 'none';
431
+ setStyleProp(fallbackEl, 'display', 'none');
430
432
  }
431
433
  /**
432
434
  * Creates and registers an error boundary
@@ -529,7 +531,7 @@ export function bindErrorBoundary(fragment, context, disposers) {
529
531
  for (const boundaryEl of boundaryElements) {
530
532
  if (boundElements.has(boundaryEl))
531
533
  continue;
532
- const signalName = boundaryEl.getAttribute('data-error');
534
+ const signalName = declaredValue(boundaryEl, 'data-error');
533
535
  if (!signalName)
534
536
  continue;
535
537
  const errorSignal = context[signalName];
@@ -1 +1 @@
1
- {"version":3,"file":"bindErrorBoundary.js","sourceRoot":"","sources":["../../../src/compile/binds/bindErrorB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AAU;YAAE,SAAS;QAE1B,MAAM,WAAW,GAAG,OAAO,CAAC,UAAU,CAAqC,CAAC;QAC5E,IAAI,CAAC,WAAW,IAAI,OAAO,WAAW,KAAK,UAAU,EAAE,CAAC;YACtD,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;gBACzB,OAAO,CAAC,IAAI,CACV,2BAA2B,UAAU,uCAAuC,UAAU,CAAC,OAAO,EAAE,CACjG,CAAC;YACJ,CAAC;YACD,SAAS;QACX,CAAC;QAED,wEAAwE;QACxE,qEAAqE;QACrE,IAAI,OAAO,WAAW,CAAC,GAAG,KAAK,UAAU,EAAE,CAAC;YAC1C,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;gBACzB,OAAO,CAAC,IAAI,CACV,2BAA2B,UAAU,mDAAmD,UAAU,CAAC,OAAO,EAAE,CAC7G,CAAC;YACJ,CAAC;YACD,SAAS;QACX,CAAC;QAED,gFAAgF;QAChF,cAAc,CAAC,UAAU,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;QACnD,aAAa,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC9B,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;IACzD,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.feature.error-boundary\",\n \"title\": \"Error Boundary System\",\n \"category\": \"feature\"\n}\n*/\n\nimport { effect, Signal, untrack } from '@pithyjs/signals';\n\nconst boundElements = new WeakSet<Element>();\n\n/**\n * Represents an active error boundary in the DOM\n */\nexport interface BoundaryInfo {\n element: Element;\n errorSignal: Signal<Error | null>;\n fallbackElement: Element | null;\n contentPlaceholders: Map<Node, Comment>;\n isActive: boolean;\n /** The receiving boundary of the slot this one was rendered in, detached. */\n slotParent?: BoundaryInfo | null;\n}\n\n/**\n * Global registry of active error boundaries\n */\nconst activeBoundaries: BoundaryInfo[] = [];\n\n/**\n * Current boundary context for async error routing (used in later phases)\n */\nlet currentBoundaryContext: BoundaryInfo | null = null;\n\n/** A slot being rendered, detached, so its content cannot `closest()` its boundary. */\ninterface SlotFrame {\n boundary: BoundaryInfo | null;\n anchor: Node;\n /** The component placeholder whose render mounts this slot. */\n host: Element | undefined;\n /** The slot rendering `host`. */\n outer: SlotFrame | null;\n /** Whether `boundary` was resolved here rather than inherited from `outer`. */\n own: boolean;\n /** Whether the slot's nodes land directly in `boundary.element`, when `own`. */\n direct: boolean;\n /** Whether the slot is the boundary's normal content, which its fallback replaces. */\n isContent: boolean;\n}\nlet slotFrame: SlotFrame | null = null;\n\n/**\n * Flag to ensure timer patching happens only once\n */\nlet timersPatched = false;\n\n/**\n * Finds the BoundaryInfo for a given DOM element by traversing up the tree\n * @param el - Element to find boundary for\n * @returns BoundaryInfo if found, null otherwise\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"boundaryForElement\",\"stability\":\"stable\",\"signature\":\"(el: Element | null) => BoundaryInfo | null\"} */\nexport function boundaryForElement(el: Element | null): BoundaryInfo | null {\n const boundaryEl = el?.closest('[data-error]');\n if (!boundaryEl) return slotFrame?.boundary ?? null;\n\n // Find the registered boundary info\n return (\n activeBoundaries.find(boundary => boundary.element === boundaryEl) || null\n );\n}\n\nfunction liveSlotParent(boundary: BoundaryInfo): BoundaryInfo | null {\n const parent = boundary.slotParent;\n return parent && activeBoundaries.includes(parent) ? parent : null;\n}\n\n/**\n * Renders a slot whose receiving `<slot>` sits at `anchor`, mounted by the\n * component placeholder `host`. Its content is detached while it renders, so\n * boundaries are resolved through the anchor, then the host's render. Without an\n * anchor (`renderChildren()`), the host is the frame's anchor.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"withSlotBoundary\",\"stability\":\"experimental\",\"signature\":\"<T>(anchor: Node | undefined, host: Element | undefined, fn: () => T) => T\"} */\nexport function withSlotBoundary<T>(\n anchor: Node | undefined,\n host: Element | undefined,\n fn: () => T\n): T {\n const outer = slotFrame;\n const at = anchor ?? host;\n if (at) {\n // An anchor an earlier crash hid has no parent to resolve from.\n const hider = hiderOf(at);\n const boundary =\n hider ??\n registeredClosest(anchor?.parentElement) ??\n outer?.boundary ??\n currentBoundaryContext;\n slotFrame =\n boundary === outer?.boundary\n ? { ...outer, anchor: at, host, outer, own: false, direct: false }\n : {\n boundary,\n anchor: at,\n host,\n outer,\n own: true,\n direct: hider\n ? hider.contentPlaceholders.has(at)\n : (anchor ?? host)?.parentElement === boundary?.element,\n isContent: !!hider || !boundary?.fallbackElement?.contains(at),\n };\n }\n try {\n return fn();\n } finally {\n slotFrame = outer;\n }\n}\n\n/** The registered boundary of `el`'s nearest `[data-error]`, ignoring slot frames. */\nfunction registeredClosest(\n el: Element | null | undefined\n): BoundaryInfo | null {\n const boundaryEl = el?.closest('[data-error]');\n return (\n (boundaryEl && activeBoundaries.find(b => b.element === boundaryEl)) || null\n );\n}\n\n/** Whether `el`, in the slot being rendered, is normal content an active fallback has replaced. */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"slotContentHidden\",\"stability\":\"experimental\",\"signature\":\"(el: Element) => boolean\"} */\nexport function slotContentHidden(el: Element): boolean {\n // Every boundary the slot frames pass through can hide it, not just the nearest.\n const inner = slotFrame;\n let up = 0;\n for (let frame = inner; frame; up++) {\n if (frame.isContent && frame.boundary?.isActive) {\n // As `hideContent`: an active nested boundary stays visible beside the fallback.\n const child = receiverChild(el, inner as SlotFrame, up);\n if (!activeBoundaries.some(b => b.element === child && b.isActive))\n return true;\n }\n while (!frame.own && frame.outer) frame = frame.outer;\n frame = frame.outer;\n }\n return false;\n}\n\n/**\n * The direct child of a boundary element that will hold `node`: the boundary\n * of `frame` when `up` is 0, else that many boundary changes further out.\n */\nfunction receiverChild(node: Node, frame: SlotFrame, up: number): Node | null {\n const top = rootOf(node);\n if (frame.own && up === 0) return frame.direct ? top : null;\n if (!frame.host || !frame.outer) return null;\n const hostChild = receiverChild(\n frame.host,\n frame.outer,\n frame.own ? up - 1 : up\n );\n if (hostChild !== frame.host) return hostChild;\n // The host's output replaces it; a bare slot puts this content in its place.\n // Anchorless (`renderChildren()`), the host is the anchor: whether it wraps its\n // children is unknown while they render, so they count as unwrapped.\n // A boundary may have hidden the anchor since: its stand-in holds the place.\n const at = standInOf(frame.anchor) ?? frame.anchor;\n const anchorTop = rootOf(at);\n return anchorTop === at ? top : anchorTop;\n}\n\nfunction standInOf(node: Node): Comment | undefined {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(node);\n if (standIn) return standIn;\n }\n return undefined;\n}\n\nfunction rootOf(node: Node): Node {\n let top = node;\n while (\n top.parentNode &&\n top.parentNode.nodeType !== Node.DOCUMENT_FRAGMENT_NODE\n )\n top = top.parentNode;\n return top;\n}\n\nfunction hiderOf(node: Node): BoundaryInfo | undefined {\n let top = node;\n while (top.parentNode) top = top.parentNode;\n return activeBoundaries.find(b => b.contentPlaceholders.has(top));\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"isHiddenByBoundary\",\"stability\":\"experimental\",\"signature\":\"(node: Node) => boolean\"} */\nexport function isHiddenByBoundary(node: Node): boolean {\n return activeBoundaries.some(\n b => !!b.contentPlaceholders.get(node)?.parentNode\n );\n}\n\n/**\n * Inserts `content` after `anchor` when an active boundary has hidden the\n * anchor, which a crash during a slot's render can do, and hides it too.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"insertBesideHidden\",\"stability\":\"experimental\",\"signature\":\"(anchor: Node, content: Node) => boolean\"} */\nexport function insertBesideHidden(anchor: Node, content: Node): boolean {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(anchor);\n if (!standIn?.parentNode) continue;\n standIn.parentNode.insertBefore(content, standIn.nextSibling);\n if (boundary.isActive) hideContent(boundary);\n return true;\n }\n return false;\n}\n\n/**\n * Puts `content` in the place of `node` when an active boundary has hidden it,\n * which a crash during `node`'s own render can do, and hides it there instead.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"replaceHidden\",\"stability\":\"experimental\",\"signature\":\"(node: Node, content: Node[]) => boolean\"} */\nexport function replaceHidden(node: Node, content: Node[]): boolean {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(node);\n if (!standIn?.parentNode) continue;\n boundary.contentPlaceholders.delete(node);\n standIn.replaceWith(...content);\n if (boundary.isActive) hideContent(boundary);\n return true;\n }\n return false;\n}\n\n/**\n * Finds the parent boundary for a given boundary (for error escalation)\n * @param childBoundary - The child boundary to find parent for\n * @returns Parent BoundaryInfo if found, null otherwise\n */\nfunction findParentBoundary(childBoundary: BoundaryInfo): BoundaryInfo | null {\n // Start searching from the child boundary's parent element\n const parentEl = childBoundary.element.parentElement;\n if (!parentEl) return liveSlotParent(childBoundary);\n\n // Find the closest ancestor boundary element\n const parentBoundaryEl = parentEl.closest('[data-error]');\n if (!parentBoundaryEl) return liveSlotParent(childBoundary);\n\n // Find the registered boundary info\n return (\n activeBoundaries.find(boundary => boundary.element === parentBoundaryEl) ||\n null\n );\n}\n\n/**\n * Clears the error state of a boundary, restoring normal content\n * @param boundary - The boundary to clear\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"clearBoundaryError\",\"stability\":\"stable\",\"signature\":\"(boundary: BoundaryInfo) => void\"} */\nexport function clearBoundaryError(boundary: BoundaryInfo): void {\n if (untrack(() => boundary.errorSignal()) !== null) {\n boundary.errorSignal.set(null);\n }\n}\n\n/**\n * Sets an error on a boundary with escalation logic\n * If the boundary is already in error state, escalates to parent boundary\n * Matches React behavior: first error wins, subsequent errors ignored\n *\n * @param boundary - The boundary to set error on\n * @param error - The error to set\n * @returns `true` if some boundary took ownership of `error`; `false` if it was\n * dropped because this boundary was already showing an error and no ancestor\n * boundary was free to take it.\n *\n * Callers must not assume the error was handled. A component rendering inside an\n * *active* boundary's `@fallback` hits exactly the `false` path — the fallback is\n * the part the user actually sees, so a crash there that nobody records ships a\n * visibly broken page with a green build. `bindComponentTags` and\n * `applyComponent` use the return value to decide between retracting an SSR\n * crash record and adding one.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"setBoundaryError\",\"stability\":\"stable\",\"signature\":\"(boundary: BoundaryInfo, error: Error) => boolean\"} */\nexport function setBoundaryError(\n boundary: BoundaryInfo,\n error: Error\n): boolean {\n // Check if this boundary is already in error state\n if (untrack(() => boundary.errorSignal()) !== null) {\n // Escalate to parent boundary\n const parentBoundary = findParentBoundary(boundary);\n if (parentBoundary) {\n return setBoundaryError(parentBoundary, error);\n }\n // IGNORE subsequent errors (React behavior - first error wins).\n // Nobody owns this error now, and the caller needs to know.\n return false;\n }\n\n // Set the error on this boundary\n boundary.errorSignal.set(error);\n return true;\n}\n\n/** The boundary the component being rendered sits under. */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"currentBoundary\",\"stability\":\"experimental\",\"signature\":\"() => BoundaryInfo | null\"} */\nexport function currentBoundary(): BoundaryInfo | null {\n return currentBoundaryContext;\n}\n\n/**\n * Runs a function within the context of a specific boundary\n * Used for scoping async operations to the correct boundary\n * @param boundary - Boundary to run within\n * @param fn - Function to execute\n * @returns Result of function execution\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"runWithBoundary\",\"stability\":\"stable\",\"signature\":\"<T>(boundary: BoundaryInfo | null, fn: () => T) => T\"} */\nexport function runWithBoundary<T>(\n boundary: BoundaryInfo | null,\n fn: () => T\n): T {\n const previousContext = currentBoundaryContext;\n currentBoundaryContext = boundary;\n try {\n return fn();\n } finally {\n currentBoundaryContext = previousContext;\n }\n}\n\nfunction patchTimersOnce(): void {\n if (timersPatched) return;\n timersPatched = true;\n\n // Patch setTimeout\n const originalSetTimeout = window.setTimeout;\n window.setTimeout = ((\n callback: TimerHandler,\n delay?: number,\n ...args: unknown[]\n ) => {\n // Don't wrap string callbacks; let the browser handle them\n if (typeof callback !== 'function') {\n return originalSetTimeout(callback, delay, ...args);\n }\n\n const capturedBoundary = currentBoundaryContext;\n const fn = callback as (...callbackArgs: unknown[]) => unknown;\n const wrappedCallback = (...callbackArgs: unknown[]) => {\n return runWithBoundary(capturedBoundary, () => {\n try {\n return fn(...callbackArgs);\n } catch (error) {\n if (capturedBoundary) {\n const err =\n error instanceof Error ? error : new Error(String(error));\n setBoundaryError(capturedBoundary, err);\n } else {\n throw error;\n }\n }\n });\n };\n return originalSetTimeout(wrappedCallback, delay, ...args);\n }) as typeof window.setTimeout;\n\n // Patch setInterval\n const originalSetInterval = window.setInterval;\n window.setInterval = ((\n callback: TimerHandler,\n delay?: number,\n ...args: unknown[]\n ) => {\n // Don't wrap string callbacks; let the browser handle them\n if (typeof callback !== 'function') {\n return originalSetInterval(callback, delay, ...args);\n }\n\n const capturedBoundary = currentBoundaryContext;\n const fn = callback as (...callbackArgs: unknown[]) => unknown;\n const wrappedCallback = (...callbackArgs: unknown[]) => {\n return runWithBoundary(capturedBoundary, () => {\n try {\n return fn(...callbackArgs);\n } catch (error) {\n if (capturedBoundary) {\n const err =\n error instanceof Error ? error : new Error(String(error));\n setBoundaryError(capturedBoundary, err);\n } else {\n throw error;\n }\n }\n });\n };\n return originalSetInterval(wrappedCallback, delay, ...args);\n }) as typeof window.setInterval;\n}\n\n/**\n * Finds the fallback element within a boundary\n * @param boundaryEl - The boundary element to search within\n * @returns The fallback element or null if not found\n */\nfunction findFallbackElement(boundaryEl: Element): Element | null {\n // Look through direct children first to avoid nested boundary fallbacks\n for (const child of Array.from(boundaryEl.children)) {\n if (child.hasAttribute('data-fallback')) {\n // Double-check that this fallback belongs to this boundary\n const fallbackBoundary = child.closest('[data-error]');\n if (fallbackBoundary === boundaryEl) {\n return child;\n }\n }\n }\n\n // If no direct child fallback found, search deeper but be more careful\n const allFallbacks = Array.from(\n boundaryEl.querySelectorAll('[data-fallback]')\n );\n for (const fallback of allFallbacks) {\n const fallbackBoundary = fallback.closest('[data-error]');\n if (fallbackBoundary === boundaryEl) {\n return fallback;\n }\n }\n\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] No fallback element found for boundary`,\n boundaryEl.tagName,\n 'Available children:',\n Array.from(boundaryEl.children).map(\n c =>\n c.tagName +\n (c.hasAttribute('data-fallback') ? '[fallback]' : '') +\n (c.hasAttribute('data-error') ? '[boundary]' : '')\n )\n );\n }\n\n return null;\n}\n\n/**\n * Gets current content nodes (excluding fallback) - recomputed each time\n * @param boundaryEl - The boundary element\n * @param fallbackEl - The fallback element to exclude\n * @returns Array of content nodes\n */\nfunction getCurrentContentNodes(\n boundaryEl: Element,\n fallbackEl: Element | null\n): Node[] {\n return Array.from(boundaryEl.childNodes).filter(n => {\n // Exclude the fallback element for this boundary\n if (n === fallbackEl) return false;\n\n // Exclude placeholder comments from other boundaries\n if (\n n.nodeType === Node.COMMENT_NODE &&\n (n as Comment).data === 'pithy-boundary-hidden'\n ) {\n return false;\n }\n\n // Don't hide nested boundary elements that are currently showing their fallback\n if (n.nodeType === Node.ELEMENT_NODE) {\n const element = n as Element;\n if (element.hasAttribute('data-error')) {\n // This is a nested boundary - check if it's currently in error state\n const nestedBoundary = activeBoundaries.find(\n b => b.element === element\n );\n if (nestedBoundary && nestedBoundary.isActive) {\n // If a nested boundary is already active, keep it visible instead of replacing with our fallback\n return false;\n }\n }\n }\n\n return true;\n });\n}\n\n/**\n * Hides content by replacing nodes with comment placeholders\n * @param boundary - The boundary info\n */\nfunction hideContent(boundary: BoundaryInfo): void {\n const { element, fallbackElement, contentPlaceholders } = boundary;\n const nodes = getCurrentContentNodes(element, fallbackElement);\n\n for (const node of nodes) {\n if (contentPlaceholders.has(node)) continue;\n const placeholder = document.createComment('pithy-boundary-hidden');\n node.parentNode?.replaceChild(placeholder, node);\n contentPlaceholders.set(node, placeholder);\n }\n\n // Always show the fallback element if it exists\n if (fallbackElement) {\n (fallbackElement as HTMLElement).style.display = '';\n }\n}\n\n/**\n * Restores content by replacing comment placeholders with original nodes\n * @param boundary - The boundary info\n */\nfunction restoreContent(boundary: BoundaryInfo): void {\n const { fallbackElement, contentPlaceholders } = boundary;\n\n for (const [node, placeholder] of Array.from(contentPlaceholders.entries())) {\n placeholder.parentNode?.replaceChild(node, placeholder);\n contentPlaceholders.delete(node);\n }\n\n if (fallbackElement) {\n (fallbackElement as HTMLElement).style.display = 'none';\n }\n}\n\n/**\n * Hides the fallback element\n * @param fallbackEl - The fallback element to hide\n */\nfunction hideFallback(fallbackEl: Element): void {\n (fallbackEl as HTMLElement).style.display = 'none';\n}\n\n/**\n * Creates and registers an error boundary\n * @param boundaryEl - The boundary element\n * @param errorSignal - The error signal from context\n * @param disposers - Array to add cleanup functions to\n * @returns The created BoundaryInfo\n */\nfunction createBoundary(\n boundaryEl: Element,\n errorSignal: Signal<Error | null>,\n disposers: (() => void)[]\n): BoundaryInfo {\n const fallbackEl = findFallbackElement(boundaryEl);\n\n const boundary: BoundaryInfo = {\n element: boundaryEl,\n errorSignal,\n fallbackElement: fallbackEl,\n contentPlaceholders: new Map(),\n isActive: false,\n slotParent: slotFrame?.boundary ?? null,\n };\n\n // Register BEFORE effect so nested lookups can find us\n activeBoundaries.push(boundary);\n\n // Initially hide fallback\n if (fallbackEl) {\n hideFallback(fallbackEl);\n }\n\n // Set up reactive effect to toggle content/fallback based on error state\n const dispose = effect(() => {\n const error = errorSignal();\n const hasError = error !== null;\n\n if (hasError && !boundary.isActive) {\n // Show error state\n boundary.isActive = true;\n hideContent(boundary);\n } else if (!hasError && boundary.isActive) {\n // Show normal state\n boundary.isActive = false;\n restoreContent(boundary);\n }\n });\n\n // Add cleanup function\n disposers.push(() => {\n dispose();\n\n // Restore any hidden content\n if (boundary.isActive) {\n restoreContent(boundary);\n }\n\n // Remove from registry\n const index = activeBoundaries.indexOf(boundary);\n if (index >= 0) {\n activeBoundaries.splice(index, 1);\n }\n });\n\n return boundary;\n}\n\n/**\n * Register a single element as an error boundary.\n * Used by AOT applyBindings where the boundary element is known directly\n * (unlike bindErrorBoundary which scans children via querySelectorAll).\n *\n * @param boundaryEl - The element with data-error attribute\n * @param context - Reactive context containing error signals\n * @param disposers - Array to add cleanup functions to\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"registerBoundary\",\"stability\":\"stable\",\"signature\":\"(boundaryEl: Element, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function registerBoundary(\n boundaryEl: Element,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n patchTimersOnce();\n\n const signalName = boundaryEl.getAttribute('data-error');\n if (!signalName) return;\n\n const errorSignal = context[signalName] as Signal<Error | null> | undefined;\n if (!errorSignal || typeof errorSignal !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" not found in context for boundary ${boundaryEl.tagName}`\n );\n }\n return;\n }\n\n // Validate that the signal is writable — computed signals or non-signal\n // functions will throw at runtime when setBoundaryError calls .set()\n if (typeof errorSignal.set !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" is not writable (no .set method) for boundary ${boundaryEl.tagName}`\n );\n }\n return;\n }\n\n createBoundary(boundaryEl, errorSignal, disposers);\n}\n\n/**\n * Binds error boundaries in the DOM fragment\n * Scans for [data-error] elements and sets up error boundary behavior\n *\n * @param fragment - DOM fragment to scan\n * @param context - Reactive context containing error signals\n * @param disposers - Array to add cleanup functions to\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"bindErrorBoundary\",\"stability\":\"stable\",\"signature\":\"(fragment: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindErrorBoundary(\n fragment: Element | DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // Patch timers on first boundary registration\n patchTimersOnce();\n\n const boundaryElements = Array.from(\n fragment.querySelectorAll('[data-error]')\n );\n\n for (const boundaryEl of boundaryElements) {\n if (boundElements.has(boundaryEl)) continue;\n const signalName = boundaryEl.getAttribute('data-error');\n if (!signalName) continue;\n\n const errorSignal = context[signalName] as Signal<Error | null> | undefined;\n if (!errorSignal || typeof errorSignal !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" not found in context for boundary ${boundaryEl.tagName}`\n );\n }\n continue;\n }\n\n // Validate that the signal is writable — computed signals or non-signal\n // functions will throw at runtime when setBoundaryError calls .set()\n if (typeof errorSignal.set !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" is not writable (no .set method) for boundary ${boundaryEl.tagName}`\n );\n }\n continue;\n }\n\n // Create and register the boundary (registration happens inside createBoundary)\n createBoundary(boundaryEl, errorSignal, disposers);\n boundElements.add(boundaryEl);\n disposers.push(() => boundElements.delete(boundaryEl));\n }\n}\n"]}
1
+ {"version":3,"file":"bindErrorBoundary.js","sourceRoot":"","sources":["../../../src/compile/binds/bindErrorBoundary.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,MAAM,EAAU,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD,MAAM,aAAa,GAAG,IAAI,OAAO,EAAW,CAAC;AAe7C;;GAEG;AACH,MAAM,gBAAgB,GAAmB,EAAE,CAAC;AAE5C;;GAEG;AACH,IAAI,sBAAsB,GAAwB,IAAI,CAAC;AAiBvD,IAAI,SAAS,GAAqB,IAAI,CAAC;AAEvC;;GAEG;AACH,IAAI,aAAa,GAAG,KAAK,CAAC;AAE1B;;;;GAIG;AACH,qKAAqK;AACrK,MAAM,UAAU,kBAAkB,CAAC,EAAkB;IACnD,MAAM,UAAU,GAAG,EAAE,EAAE,OAAO,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IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;gBACzB,OAAO,CAAC,IAAI,CACV,2BAA2B,UAAU,mDAAmD,UAAU,CAAC,OAAO,EAAE,CAC7G,CAAC;YACJ,CAAC;YACD,SAAS;QACX,CAAC;QAED,gFAAgF;QAChF,cAAc,CAAC,UAAU,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;QACnD,aAAa,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC9B,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;IACzD,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.feature.error-boundary\",\n \"title\": \"Error Boundary System\",\n \"category\": \"feature\"\n}\n*/\n\nimport { declaredValue } from './declaredDirective';\nimport { effect, Signal, untrack } from '@pithyjs/signals';\nimport { setStyleProp } from './bindBoundAttributes';\n\nconst boundElements = new WeakSet<Element>();\n\n/**\n * Represents an active error boundary in the DOM\n */\nexport interface BoundaryInfo {\n element: Element;\n errorSignal: Signal<Error | null>;\n fallbackElement: Element | null;\n contentPlaceholders: Map<Node, Comment>;\n isActive: boolean;\n /** The receiving boundary of the slot this one was rendered in, detached. */\n slotParent?: BoundaryInfo | null;\n}\n\n/**\n * Global registry of active error boundaries\n */\nconst activeBoundaries: BoundaryInfo[] = [];\n\n/**\n * Current boundary context for async error routing (used in later phases)\n */\nlet currentBoundaryContext: BoundaryInfo | null = null;\n\n/** A slot being rendered, detached, so its content cannot `closest()` its boundary. */\ninterface SlotFrame {\n boundary: BoundaryInfo | null;\n anchor: Node;\n /** The component placeholder whose render mounts this slot. */\n host: Element | undefined;\n /** The slot rendering `host`. */\n outer: SlotFrame | null;\n /** Whether `boundary` was resolved here rather than inherited from `outer`. */\n own: boolean;\n /** Whether the slot's nodes land directly in `boundary.element`, when `own`. */\n direct: boolean;\n /** Whether the slot is the boundary's normal content, which its fallback replaces. */\n isContent: boolean;\n}\nlet slotFrame: SlotFrame | null = null;\n\n/**\n * Flag to ensure timer patching happens only once\n */\nlet timersPatched = false;\n\n/**\n * Finds the BoundaryInfo for a given DOM element by traversing up the tree\n * @param el - Element to find boundary for\n * @returns BoundaryInfo if found, null otherwise\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"boundaryForElement\",\"stability\":\"stable\",\"signature\":\"(el: Element | null) => BoundaryInfo | null\"} */\nexport function boundaryForElement(el: Element | null): BoundaryInfo | null {\n const boundaryEl = el?.closest('[data-error]');\n if (!boundaryEl) return slotFrame?.boundary ?? null;\n\n // Find the registered boundary info\n return (\n activeBoundaries.find(boundary => boundary.element === boundaryEl) || null\n );\n}\n\nfunction liveSlotParent(boundary: BoundaryInfo): BoundaryInfo | null {\n const parent = boundary.slotParent;\n return parent && activeBoundaries.includes(parent) ? parent : null;\n}\n\n/**\n * Renders a slot whose receiving `<slot>` sits at `anchor`, mounted by the\n * component placeholder `host`. Its content is detached while it renders, so\n * boundaries are resolved through the anchor, then the host's render. Without an\n * anchor (`renderChildren()`), the host is the frame's anchor.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"withSlotBoundary\",\"stability\":\"experimental\",\"signature\":\"<T>(anchor: Node | undefined, host: Element | undefined, fn: () => T) => T\"} */\nexport function withSlotBoundary<T>(\n anchor: Node | undefined,\n host: Element | undefined,\n fn: () => T\n): T {\n const outer = slotFrame;\n const at = anchor ?? host;\n if (at) {\n // An anchor an earlier crash hid has no parent to resolve from.\n const hider = hiderOf(at);\n const boundary =\n hider ??\n registeredClosest(anchor?.parentElement) ??\n outer?.boundary ??\n currentBoundaryContext;\n slotFrame =\n boundary === outer?.boundary\n ? { ...outer, anchor: at, host, outer, own: false, direct: false }\n : {\n boundary,\n anchor: at,\n host,\n outer,\n own: true,\n direct: hider\n ? hider.contentPlaceholders.has(at)\n : (anchor ?? host)?.parentElement === boundary?.element,\n isContent: !!hider || !boundary?.fallbackElement?.contains(at),\n };\n }\n try {\n return fn();\n } finally {\n slotFrame = outer;\n }\n}\n\n/** The registered boundary of `el`'s nearest `[data-error]`, ignoring slot frames. */\nfunction registeredClosest(\n el: Element | null | undefined\n): BoundaryInfo | null {\n const boundaryEl = el?.closest('[data-error]');\n return (\n (boundaryEl && activeBoundaries.find(b => b.element === boundaryEl)) || null\n );\n}\n\n/** Whether `el`, in the slot being rendered, is normal content an active fallback has replaced. */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"slotContentHidden\",\"stability\":\"experimental\",\"signature\":\"(el: Element) => boolean\"} */\nexport function slotContentHidden(el: Element): boolean {\n // Every boundary the slot frames pass through can hide it, not just the nearest.\n const inner = slotFrame;\n let up = 0;\n for (let frame = inner; frame; up++) {\n if (frame.isContent && frame.boundary?.isActive) {\n // As `hideContent`: an active nested boundary stays visible beside the fallback.\n const child = receiverChild(el, inner as SlotFrame, up);\n if (!activeBoundaries.some(b => b.element === child && b.isActive))\n return true;\n }\n while (!frame.own && frame.outer) frame = frame.outer;\n frame = frame.outer;\n }\n return false;\n}\n\n/**\n * The direct child of a boundary element that will hold `node`: the boundary\n * of `frame` when `up` is 0, else that many boundary changes further out.\n */\nfunction receiverChild(node: Node, frame: SlotFrame, up: number): Node | null {\n const top = rootOf(node);\n if (frame.own && up === 0) return frame.direct ? top : null;\n if (!frame.host || !frame.outer) return null;\n const hostChild = receiverChild(\n frame.host,\n frame.outer,\n frame.own ? up - 1 : up\n );\n if (hostChild !== frame.host) return hostChild;\n // The host's output replaces it; a bare slot puts this content in its place.\n // Anchorless (`renderChildren()`), the host is the anchor: whether it wraps its\n // children is unknown while they render, so they count as unwrapped.\n // A boundary may have hidden the anchor since: its stand-in holds the place.\n const at = standInOf(frame.anchor) ?? frame.anchor;\n const anchorTop = rootOf(at);\n return anchorTop === at ? top : anchorTop;\n}\n\nfunction standInOf(node: Node): Comment | undefined {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(node);\n if (standIn) return standIn;\n }\n return undefined;\n}\n\nfunction rootOf(node: Node): Node {\n let top = node;\n while (\n top.parentNode &&\n top.parentNode.nodeType !== Node.DOCUMENT_FRAGMENT_NODE\n )\n top = top.parentNode;\n return top;\n}\n\nfunction hiderOf(node: Node): BoundaryInfo | undefined {\n let top = node;\n while (top.parentNode) top = top.parentNode;\n return activeBoundaries.find(b => b.contentPlaceholders.has(top));\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"isHiddenByBoundary\",\"stability\":\"experimental\",\"signature\":\"(node: Node) => boolean\"} */\nexport function isHiddenByBoundary(node: Node): boolean {\n return activeBoundaries.some(\n b => !!b.contentPlaceholders.get(node)?.parentNode\n );\n}\n\n/**\n * Inserts `content` after `anchor` when an active boundary has hidden the\n * anchor, which a crash during a slot's render can do, and hides it too.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"insertBesideHidden\",\"stability\":\"experimental\",\"signature\":\"(anchor: Node, content: Node) => boolean\"} */\nexport function insertBesideHidden(anchor: Node, content: Node): boolean {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(anchor);\n if (!standIn?.parentNode) continue;\n standIn.parentNode.insertBefore(content, standIn.nextSibling);\n if (boundary.isActive) hideContent(boundary);\n return true;\n }\n return false;\n}\n\n/**\n * Puts `content` in the place of `node` when an active boundary has hidden it,\n * which a crash during `node`'s own render can do, and hides it there instead.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"replaceHidden\",\"stability\":\"experimental\",\"signature\":\"(node: Node, content: Node[]) => boolean\"} */\nexport function replaceHidden(node: Node, content: Node[]): boolean {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(node);\n if (!standIn?.parentNode) continue;\n boundary.contentPlaceholders.delete(node);\n standIn.replaceWith(...content);\n if (boundary.isActive) hideContent(boundary);\n return true;\n }\n return false;\n}\n\n/**\n * Finds the parent boundary for a given boundary (for error escalation)\n * @param childBoundary - The child boundary to find parent for\n * @returns Parent BoundaryInfo if found, null otherwise\n */\nfunction findParentBoundary(childBoundary: BoundaryInfo): BoundaryInfo | null {\n // Start searching from the child boundary's parent element\n const parentEl = childBoundary.element.parentElement;\n if (!parentEl) return liveSlotParent(childBoundary);\n\n // Find the closest ancestor boundary element\n const parentBoundaryEl = parentEl.closest('[data-error]');\n if (!parentBoundaryEl) return liveSlotParent(childBoundary);\n\n // Find the registered boundary info\n return (\n activeBoundaries.find(boundary => boundary.element === parentBoundaryEl) ||\n null\n );\n}\n\n/**\n * Clears the error state of a boundary, restoring normal content\n * @param boundary - The boundary to clear\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"clearBoundaryError\",\"stability\":\"stable\",\"signature\":\"(boundary: BoundaryInfo) => void\"} */\nexport function clearBoundaryError(boundary: BoundaryInfo): void {\n if (untrack(() => boundary.errorSignal()) !== null) {\n boundary.errorSignal.set(null);\n }\n}\n\n/**\n * Sets an error on a boundary with escalation logic\n * If the boundary is already in error state, escalates to parent boundary\n * Matches React behavior: first error wins, subsequent errors ignored\n *\n * @param boundary - The boundary to set error on\n * @param error - The error to set\n * @returns `true` if some boundary took ownership of `error`; `false` if it was\n * dropped because this boundary was already showing an error and no ancestor\n * boundary was free to take it.\n *\n * Callers must not assume the error was handled. A component rendering inside an\n * *active* boundary's `@fallback` hits exactly the `false` path — the fallback is\n * the part the user actually sees, so a crash there that nobody records ships a\n * visibly broken page with a green build. `bindComponentTags` and\n * `applyComponent` use the return value to decide between retracting an SSR\n * crash record and adding one.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"setBoundaryError\",\"stability\":\"stable\",\"signature\":\"(boundary: BoundaryInfo, error: Error) => boolean\"} */\nexport function setBoundaryError(\n boundary: BoundaryInfo,\n error: Error\n): boolean {\n // Check if this boundary is already in error state\n if (untrack(() => boundary.errorSignal()) !== null) {\n // Escalate to parent boundary\n const parentBoundary = findParentBoundary(boundary);\n if (parentBoundary) {\n return setBoundaryError(parentBoundary, error);\n }\n // IGNORE subsequent errors (React behavior - first error wins).\n // Nobody owns this error now, and the caller needs to know.\n return false;\n }\n\n // Set the error on this boundary\n boundary.errorSignal.set(error);\n return true;\n}\n\n/** The boundary the component being rendered sits under. */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"currentBoundary\",\"stability\":\"experimental\",\"signature\":\"() => BoundaryInfo | null\"} */\nexport function currentBoundary(): BoundaryInfo | null {\n return currentBoundaryContext;\n}\n\n/**\n * Runs a function within the context of a specific boundary\n * Used for scoping async operations to the correct boundary\n * @param boundary - Boundary to run within\n * @param fn - Function to execute\n * @returns Result of function execution\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"runWithBoundary\",\"stability\":\"stable\",\"signature\":\"<T>(boundary: BoundaryInfo | null, fn: () => T) => T\"} */\nexport function runWithBoundary<T>(\n boundary: BoundaryInfo | null,\n fn: () => T\n): T {\n const previousContext = currentBoundaryContext;\n currentBoundaryContext = boundary;\n try {\n return fn();\n } finally {\n currentBoundaryContext = previousContext;\n }\n}\n\nfunction patchTimersOnce(): void {\n if (timersPatched) return;\n timersPatched = true;\n\n // Patch setTimeout\n const originalSetTimeout = window.setTimeout;\n window.setTimeout = ((\n callback: TimerHandler,\n delay?: number,\n ...args: unknown[]\n ) => {\n // Don't wrap string callbacks; let the browser handle them\n if (typeof callback !== 'function') {\n return originalSetTimeout(callback, delay, ...args);\n }\n\n const capturedBoundary = currentBoundaryContext;\n const fn = callback as (...callbackArgs: unknown[]) => unknown;\n const wrappedCallback = (...callbackArgs: unknown[]) => {\n return runWithBoundary(capturedBoundary, () => {\n try {\n return fn(...callbackArgs);\n } catch (error) {\n if (capturedBoundary) {\n const err =\n error instanceof Error ? error : new Error(String(error));\n setBoundaryError(capturedBoundary, err);\n } else {\n throw error;\n }\n }\n });\n };\n return originalSetTimeout(wrappedCallback, delay, ...args);\n }) as typeof window.setTimeout;\n\n // Patch setInterval\n const originalSetInterval = window.setInterval;\n window.setInterval = ((\n callback: TimerHandler,\n delay?: number,\n ...args: unknown[]\n ) => {\n // Don't wrap string callbacks; let the browser handle them\n if (typeof callback !== 'function') {\n return originalSetInterval(callback, delay, ...args);\n }\n\n const capturedBoundary = currentBoundaryContext;\n const fn = callback as (...callbackArgs: unknown[]) => unknown;\n const wrappedCallback = (...callbackArgs: unknown[]) => {\n return runWithBoundary(capturedBoundary, () => {\n try {\n return fn(...callbackArgs);\n } catch (error) {\n if (capturedBoundary) {\n const err =\n error instanceof Error ? error : new Error(String(error));\n setBoundaryError(capturedBoundary, err);\n } else {\n throw error;\n }\n }\n });\n };\n return originalSetInterval(wrappedCallback, delay, ...args);\n }) as typeof window.setInterval;\n}\n\n/**\n * Finds the fallback element within a boundary\n * @param boundaryEl - The boundary element to search within\n * @returns The fallback element or null if not found\n */\nfunction findFallbackElement(boundaryEl: Element): Element | null {\n // Look through direct children first to avoid nested boundary fallbacks\n for (const child of Array.from(boundaryEl.children)) {\n if (child.hasAttribute('data-fallback')) {\n // Double-check that this fallback belongs to this boundary\n const fallbackBoundary = child.closest('[data-error]');\n if (fallbackBoundary === boundaryEl) {\n return child;\n }\n }\n }\n\n // If no direct child fallback found, search deeper but be more careful\n const allFallbacks = Array.from(\n boundaryEl.querySelectorAll('[data-fallback]')\n );\n for (const fallback of allFallbacks) {\n const fallbackBoundary = fallback.closest('[data-error]');\n if (fallbackBoundary === boundaryEl) {\n return fallback;\n }\n }\n\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] No fallback element found for boundary`,\n boundaryEl.tagName,\n 'Available children:',\n Array.from(boundaryEl.children).map(\n c =>\n c.tagName +\n (c.hasAttribute('data-fallback') ? '[fallback]' : '') +\n (c.hasAttribute('data-error') ? '[boundary]' : '')\n )\n );\n }\n\n return null;\n}\n\n/**\n * Gets current content nodes (excluding fallback) - recomputed each time\n * @param boundaryEl - The boundary element\n * @param fallbackEl - The fallback element to exclude\n * @returns Array of content nodes\n */\nfunction getCurrentContentNodes(\n boundaryEl: Element,\n fallbackEl: Element | null\n): Node[] {\n return Array.from(boundaryEl.childNodes).filter(n => {\n // Exclude the fallback element for this boundary\n if (n === fallbackEl) return false;\n\n // Exclude placeholder comments from other boundaries\n if (\n n.nodeType === Node.COMMENT_NODE &&\n (n as Comment).data === 'pithy-boundary-hidden'\n ) {\n return false;\n }\n\n // Don't hide nested boundary elements that are currently showing their fallback\n if (n.nodeType === Node.ELEMENT_NODE) {\n const element = n as Element;\n if (element.hasAttribute('data-error')) {\n // This is a nested boundary - check if it's currently in error state\n const nestedBoundary = activeBoundaries.find(\n b => b.element === element\n );\n if (nestedBoundary && nestedBoundary.isActive) {\n // If a nested boundary is already active, keep it visible instead of replacing with our fallback\n return false;\n }\n }\n }\n\n return true;\n });\n}\n\n/**\n * Hides content by replacing nodes with comment placeholders\n * @param boundary - The boundary info\n */\nfunction hideContent(boundary: BoundaryInfo): void {\n const { element, fallbackElement, contentPlaceholders } = boundary;\n const nodes = getCurrentContentNodes(element, fallbackElement);\n\n for (const node of nodes) {\n if (contentPlaceholders.has(node)) continue;\n const placeholder = document.createComment('pithy-boundary-hidden');\n node.parentNode?.replaceChild(placeholder, node);\n contentPlaceholders.set(node, placeholder);\n }\n\n // Always show the fallback element if it exists\n if (fallbackElement) {\n setStyleProp(fallbackElement, 'display', null);\n }\n}\n\n/**\n * Restores content by replacing comment placeholders with original nodes\n * @param boundary - The boundary info\n */\nfunction restoreContent(boundary: BoundaryInfo): void {\n const { fallbackElement, contentPlaceholders } = boundary;\n\n for (const [node, placeholder] of Array.from(contentPlaceholders.entries())) {\n placeholder.parentNode?.replaceChild(node, placeholder);\n contentPlaceholders.delete(node);\n }\n\n if (fallbackElement) {\n setStyleProp(fallbackElement, 'display', 'none');\n }\n}\n\n/**\n * Hides the fallback element\n * @param fallbackEl - The fallback element to hide\n */\nfunction hideFallback(fallbackEl: Element): void {\n setStyleProp(fallbackEl, 'display', 'none');\n}\n\n/**\n * Creates and registers an error boundary\n * @param boundaryEl - The boundary element\n * @param errorSignal - The error signal from context\n * @param disposers - Array to add cleanup functions to\n * @returns The created BoundaryInfo\n */\nfunction createBoundary(\n boundaryEl: Element,\n errorSignal: Signal<Error | null>,\n disposers: (() => void)[]\n): BoundaryInfo {\n const fallbackEl = findFallbackElement(boundaryEl);\n\n const boundary: BoundaryInfo = {\n element: boundaryEl,\n errorSignal,\n fallbackElement: fallbackEl,\n contentPlaceholders: new Map(),\n isActive: false,\n slotParent: slotFrame?.boundary ?? null,\n };\n\n // Register BEFORE effect so nested lookups can find us\n activeBoundaries.push(boundary);\n\n // Initially hide fallback\n if (fallbackEl) {\n hideFallback(fallbackEl);\n }\n\n // Set up reactive effect to toggle content/fallback based on error state\n const dispose = effect(() => {\n const error = errorSignal();\n const hasError = error !== null;\n\n if (hasError && !boundary.isActive) {\n // Show error state\n boundary.isActive = true;\n hideContent(boundary);\n } else if (!hasError && boundary.isActive) {\n // Show normal state\n boundary.isActive = false;\n restoreContent(boundary);\n }\n });\n\n // Add cleanup function\n disposers.push(() => {\n dispose();\n\n // Restore any hidden content\n if (boundary.isActive) {\n restoreContent(boundary);\n }\n\n // Remove from registry\n const index = activeBoundaries.indexOf(boundary);\n if (index >= 0) {\n activeBoundaries.splice(index, 1);\n }\n });\n\n return boundary;\n}\n\n/**\n * Register a single element as an error boundary.\n * Used by AOT applyBindings where the boundary element is known directly\n * (unlike bindErrorBoundary which scans children via querySelectorAll).\n *\n * @param boundaryEl - The element with data-error attribute\n * @param context - Reactive context containing error signals\n * @param disposers - Array to add cleanup functions to\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"registerBoundary\",\"stability\":\"stable\",\"signature\":\"(boundaryEl: Element, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function registerBoundary(\n boundaryEl: Element,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n patchTimersOnce();\n\n const signalName = boundaryEl.getAttribute('data-error');\n if (!signalName) return;\n\n const errorSignal = context[signalName] as Signal<Error | null> | undefined;\n if (!errorSignal || typeof errorSignal !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" not found in context for boundary ${boundaryEl.tagName}`\n );\n }\n return;\n }\n\n // Validate that the signal is writable — computed signals or non-signal\n // functions will throw at runtime when setBoundaryError calls .set()\n if (typeof errorSignal.set !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" is not writable (no .set method) for boundary ${boundaryEl.tagName}`\n );\n }\n return;\n }\n\n createBoundary(boundaryEl, errorSignal, disposers);\n}\n\n/**\n * Binds error boundaries in the DOM fragment\n * Scans for [data-error] elements and sets up error boundary behavior\n *\n * @param fragment - DOM fragment to scan\n * @param context - Reactive context containing error signals\n * @param disposers - Array to add cleanup functions to\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"bindErrorBoundary\",\"stability\":\"stable\",\"signature\":\"(fragment: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindErrorBoundary(\n fragment: Element | DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // Patch timers on first boundary registration\n patchTimersOnce();\n\n const boundaryElements = Array.from(\n fragment.querySelectorAll('[data-error]')\n );\n\n for (const boundaryEl of boundaryElements) {\n if (boundElements.has(boundaryEl)) continue;\n const signalName = declaredValue(boundaryEl, 'data-error');\n if (!signalName) continue;\n\n const errorSignal = context[signalName] as Signal<Error | null> | undefined;\n if (!errorSignal || typeof errorSignal !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" not found in context for boundary ${boundaryEl.tagName}`\n );\n }\n continue;\n }\n\n // Validate that the signal is writable — computed signals or non-signal\n // functions will throw at runtime when setBoundaryError calls .set()\n if (typeof errorSignal.set !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" is not writable (no .set method) for boundary ${boundaryEl.tagName}`\n );\n }\n continue;\n }\n\n // Create and register the boundary (registration happens inside createBoundary)\n createBoundary(boundaryEl, errorSignal, disposers);\n boundElements.add(boundaryEl);\n disposers.push(() => boundElements.delete(boundaryEl));\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bindEventHandlers.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindEventHandlers.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAyGF;;;;;;GAMG;AACH,wNAAwN;AACxN,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAgFN"}
1
+ {"version":3,"file":"bindEventHandlers.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindEventHandlers.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AA0GF;;;;;;GAMG;AACH,wNAAwN;AACxN,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAiFN"}