@pithyjs/core 0.1.0-beta.22 → 0.1.0-beta.24

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 (71) hide show
  1. package/README.md +6 -0
  2. package/dist/compile/bindSwitchCases.d.ts.map +1 -1
  3. package/dist/compile/bindSwitchCases.js +2 -1
  4. package/dist/compile/bindSwitchCases.js.map +1 -1
  5. package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
  6. package/dist/compile/binds/bindComponentsTags.js +41 -78
  7. package/dist/compile/binds/bindComponentsTags.js.map +1 -1
  8. package/dist/compile/binds/bindDefaultTwoWay.d.ts.map +1 -1
  9. package/dist/compile/binds/bindDefaultTwoWay.js +2 -1
  10. package/dist/compile/binds/bindDefaultTwoWay.js.map +1 -1
  11. package/dist/compile/binds/bindDeferDirectives.d.ts +3 -3
  12. package/dist/compile/binds/bindDeferDirectives.d.ts.map +1 -1
  13. package/dist/compile/binds/bindDeferDirectives.js +7 -5
  14. package/dist/compile/binds/bindDeferDirectives.js.map +1 -1
  15. package/dist/compile/binds/bindErrorBoundary.d.ts +8 -2
  16. package/dist/compile/binds/bindErrorBoundary.d.ts.map +1 -1
  17. package/dist/compile/binds/bindErrorBoundary.js +99 -25
  18. package/dist/compile/binds/bindErrorBoundary.js.map +1 -1
  19. package/dist/compile/binds/propNames.d.ts +5 -1
  20. package/dist/compile/binds/propNames.d.ts.map +1 -1
  21. package/dist/compile/binds/propNames.js +36 -1
  22. package/dist/compile/binds/propNames.js.map +1 -1
  23. package/dist/compile/binds/propWarnings.d.ts +11 -0
  24. package/dist/compile/binds/propWarnings.d.ts.map +1 -0
  25. package/dist/compile/binds/propWarnings.js +43 -0
  26. package/dist/compile/binds/propWarnings.js.map +1 -0
  27. package/dist/compile/contentProjection.d.ts +14 -2
  28. package/dist/compile/contentProjection.d.ts.map +1 -1
  29. package/dist/compile/contentProjection.js +47 -9
  30. package/dist/compile/contentProjection.js.map +1 -1
  31. package/dist/compile/evalDiagnostics.d.ts +5 -0
  32. package/dist/compile/evalDiagnostics.d.ts.map +1 -1
  33. package/dist/compile/evalDiagnostics.js +5 -0
  34. package/dist/compile/evalDiagnostics.js.map +1 -1
  35. package/dist/compile/forLoops/createLoopManager.d.ts +3 -1
  36. package/dist/compile/forLoops/createLoopManager.d.ts.map +1 -1
  37. package/dist/compile/forLoops/createLoopManager.js +9 -5
  38. package/dist/compile/forLoops/createLoopManager.js.map +1 -1
  39. package/dist/compile/nodeExpando.d.ts +1 -0
  40. package/dist/compile/nodeExpando.d.ts.map +1 -1
  41. package/dist/compile/nodeExpando.js.map +1 -1
  42. package/dist/compile/ssrCrashes.d.ts +6 -0
  43. package/dist/compile/ssrCrashes.d.ts.map +1 -1
  44. package/dist/compile/ssrCrashes.js +91 -19
  45. package/dist/compile/ssrCrashes.js.map +1 -1
  46. package/dist/runtime/applyBindings.d.ts +6 -0
  47. package/dist/runtime/applyBindings.d.ts.map +1 -1
  48. package/dist/runtime/applyBindings.js +13 -2
  49. package/dist/runtime/applyBindings.js.map +1 -1
  50. package/dist/runtime/bindings/applyComponent.d.ts +3 -1
  51. package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
  52. package/dist/runtime/bindings/applyComponent.js +14 -4
  53. package/dist/runtime/bindings/applyComponent.js.map +1 -1
  54. package/dist/runtime/bindings/applyDefer.js +2 -2
  55. package/dist/runtime/bindings/applyDefer.js.map +1 -1
  56. package/dist/runtime/bindings/applySimple.d.ts.map +1 -1
  57. package/dist/runtime/bindings/applySimple.js +10 -4
  58. package/dist/runtime/bindings/applySimple.js.map +1 -1
  59. package/dist/runtime/bindings/applyStructural.d.ts.map +1 -1
  60. package/dist/runtime/bindings/applyStructural.js +19 -5
  61. package/dist/runtime/bindings/applyStructural.js.map +1 -1
  62. package/dist/runtime/bindings/helpers.d.ts.map +1 -1
  63. package/dist/runtime/bindings/helpers.js +2 -1
  64. package/dist/runtime/bindings/helpers.js.map +1 -1
  65. package/dist/runtime/bindings/types.d.ts +4 -0
  66. package/dist/runtime/bindings/types.d.ts.map +1 -1
  67. package/dist/runtime/bindings/types.js.map +1 -1
  68. package/dist/types/globals.d.ts +3 -0
  69. package/dist/types/globals.d.ts.map +1 -1
  70. package/dist/types/globals.js.map +1 -1
  71. package/package.json +2 -2
package/README.md CHANGED
@@ -292,11 +292,14 @@ The `@for` directive provides keyed, reactive list rendering with:
292
292
  | reportComponentFailure | ssr-crashes | `(el: Element, tag: string, error: Error, boundary: BoundaryInfo | null, attribution?: Attribution) => boolean` | internal | - |
293
293
  | hasCrashed | ssr-crashes | `(el: Element) => boolean` | internal | - |
294
294
  | withinRender | ssr-crashes | `<T>(fn: () => T) => T` | internal | - |
295
+ | logFailure | ssr-crashes | `(el: Element, log: () => void) => void` | internal | - |
296
+ | failedInBranch | ssr-crashes | `(el: Element) => boolean` | internal | - |
295
297
  | deferCrash | ssr-crashes | `(el: Element, tag: string, error: Error, attribution?: Attribution) => boolean` | internal | - |
296
298
  | resolveAttributedCrashes | ssr-crashes | `(mode?: 'render' | 'task' | 'collect', scope?: ParentNode) => void` | internal | - |
297
299
  | resolveBeforeFallback | ssr-crashes | `(el: Element) => void` | internal | - |
298
300
  | isSSRMode | ssr-mode | `() => boolean` | stable | - |
299
301
  | toTextValue | dom-safety | `(input: unknown) => string` | internal | - |
302
+ | __slotDup | apply-bindings | `true` | internal | - |
300
303
  | __applyBindings | apply-bindings | `(fragment: DocumentFragment, bindings: Desc[], context: Record<string, unknown>, ownsDestroyCallbacks?: boolean) => { el: DocumentFragment; destroy: () => void }` | experimental | - |
301
304
  | bootstrap | bootstrap | `(options: BootstrapOptions) => Promise<void>` | stable | - |
302
305
  | createContextProxy | context | `(contexts: Record<string, unknown>[]) => Record<string, unknown>` | stable | - |
@@ -435,11 +438,14 @@ pnpm test -- --watch # Watch mode
435
438
  | reportComponentFailure | - | - | - | Missing unit, integration, e2e |
436
439
  | hasCrashed | - | - | - | Missing unit, integration, e2e |
437
440
  | withinRender | - | - | - | Missing unit, integration, e2e |
441
+ | logFailure | - | - | - | Missing unit, integration, e2e |
442
+ | failedInBranch | - | - | - | Missing unit, integration, e2e |
438
443
  | deferCrash | - | - | - | Missing unit, integration, e2e |
439
444
  | resolveAttributedCrashes | - | - | - | Missing unit, integration, e2e |
440
445
  | resolveBeforeFallback | - | - | - | Missing unit, integration, e2e |
441
446
  | isSSRMode | - | - | - | Missing unit, integration, e2e |
442
447
  | toTextValue | - | - | - | Missing unit, integration, e2e |
448
+ | __slotDup | - | - | - | Missing unit, integration, e2e |
443
449
  | __applyBindings | - | - | - | Missing unit, integration, e2e |
444
450
  | bootstrap | ✓ | - | - | Missing integration, e2e |
445
451
  | createContextProxy | - | - | - | Missing unit, integration, e2e |
@@ -1 +1 @@
1
- {"version":3,"file":"bindSwitchCases.d.ts","sourceRoot":"","sources":["../../src/compile/bindSwitchCases.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAGL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAS3B;;;GAGG;AACH,kRAAkR;AAClR,wBAAgB,eAAe,CAC7B,KAAK,EAAE,SAAS,EAAE,EAClB,MAAM,EAAE,OAAO,GAAG,gBAAgB,EAClC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,gBAAgB,GAAE,GAAG,CAAC,MAAM,CAAa,EAAE,gCAAgC;AAC3E,SAAS,GAAE,CAAC,MAAM,IAAI,CAAC,EAAO,GAC7B,GAAG,CAAC,MAAM,CAAC,CAyEb;AAUD;;GAEG;AACH,yQAAyQ;AACzQ,wBAAgB,eAAe,CAC7B,UAAU,EAAE,SAAS,EACrB,aAAa,EAAE,OAAO,EACtB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,gBAAgB,EAAE,GAAG,CAAC,MAAM,CAAC,EAC7B,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,OAAO,CA2CT"}
1
+ {"version":3,"file":"bindSwitchCases.d.ts","sourceRoot":"","sources":["../../src/compile/bindSwitchCases.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAGL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAU3B;;;GAGG;AACH,kRAAkR;AAClR,wBAAgB,eAAe,CAC7B,KAAK,EAAE,SAAS,EAAE,EAClB,MAAM,EAAE,OAAO,GAAG,gBAAgB,EAClC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,gBAAgB,GAAE,GAAG,CAAC,MAAM,CAAa,EAAE,gCAAgC;AAC3E,SAAS,GAAE,CAAC,MAAM,IAAI,CAAC,EAAO,GAC7B,GAAG,CAAC,MAAM,CAAC,CAyEb;AAUD;;GAEG;AACH,yQAAyQ;AACzQ,wBAAgB,eAAe,CAC7B,UAAU,EAAE,SAAS,EACrB,aAAa,EAAE,OAAO,EACtB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,gBAAgB,EAAE,GAAG,CAAC,MAAM,CAAC,EAC7B,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,OAAO,CA2CT"}
@@ -8,6 +8,7 @@
8
8
  import { isDefaultCase, loopConflictMessage, } from '@pithyjs/compiler';
9
9
  import { effect } from '@pithyjs/signals';
10
10
  import { compileExpression } from './compileExpression.js';
11
+ import { switchEvalMessage } from './evalDiagnostics.js';
11
12
  import { findAllNestedLoopNodes } from './forLoops/loopTraversal.js';
12
13
  import { blockDisposer } from './disposeOrder.js';
13
14
  import { nodeExpando } from './nodeExpando.js';
@@ -201,7 +202,7 @@ function handleSwitchBlock(parentElement, caseElements, switchNode, caseNodes, c
201
202
  return fn();
202
203
  }
203
204
  catch (err) {
204
- console.error(`[Switch-${switchId}] Error evaluating ${kind}:`, err);
205
+ console.error(switchEvalMessage(kind, expr), err);
205
206
  return undefined;
206
207
  }
207
208
  }
@@ -1 +1 @@
1
- {"version":3,"file":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C;YACvB,kCAAkC;YAClC,kBAAkB,GAAG,UAAU,CAAC;YAChC,OAAO,GAAG,iBAAiB,CAAC,UAAU,CAAC,CAAC;YAExC,4DAA4D;YAC5D,gEAAgE;YAChE,mEAAmE;QACrE,CAAC,CAAC,CAAC;QAEH,SAAS,CAAC,IAAI,CACZ,aAAa,CAAC,UAAU,EAAE,oBAAoB,EAAE,WAAW,CAAC,CAC7D,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.switch\",\n \"title\": \"@switch directive\",\n \"category\": \"directive\"\n}\n*/\n\nimport {\n isDefaultCase,\n loopConflictMessage,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { effect } from '@pithyjs/signals';\nimport { compileExpression } from './compileExpression';\nimport { findAllNestedLoopNodes } from './forLoops/loopTraversal';\nimport { blockDisposer } from './disposeOrder';\nimport { nodeExpando } from './nodeExpando';\nimport { clearBranch, renderBranch, type Branch } from './renderBranch';\nimport { isSSRMode } from './ssrMode';\n\n/**\n * Processes switch case directives (@switch, @case, @default) in the template.\n * Identifies switch blocks and delegates their handling to handleSwitchBlock.\n */\n/** @codexApi {\"parent\":\"pithy.directive.switch\",\"name\":\"bindSwitchCases\",\"stability\":\"stable\",\"signature\":\"(nodes: PithyNode[], rootEl: Element | DocumentFragment, ctx: Record<string, unknown>, processedNodeIds?: Set<string>, disposers?: (() => void)[]) => Set<string>\"} */\nexport function bindSwitchCases(\n nodes: PithyNode[],\n rootEl: Element | DocumentFragment,\n ctx: Record<string, unknown>,\n processedNodeIds: Set<string> = new Set(), // Track already processed nodes\n disposers: (() => void)[] = [] // Collect disposers for cleanup\n): Set<string> {\n // Performance optimization: Create a Map of all elements by data-pid\n // This makes element lookups O(1) instead of O(n) with querySelector\n const elMap = new Map<string, Element>();\n if (rootEl instanceof Element || rootEl instanceof DocumentFragment) {\n const elements = rootEl.querySelectorAll('[data-pid]');\n elements.forEach(el => {\n const pid = el.getAttribute('data-pid');\n if (pid) {\n elMap.set(pid, el as Element);\n }\n });\n }\n\n const switchIds = new Set<string>();\n\n for (const node of nodes) {\n if (node.type !== 'element') continue;\n if (\n (node.directives?.case !== undefined || isDefaultCase(node)) &&\n node.nodeId &&\n !processedNodeIds.has(node.nodeId) &&\n !isConditionalBranch(node)\n ) {\n processedNodeIds.add(node.nodeId);\n elMap.get(node.nodeId)?.remove();\n if (import.meta.env?.DEV && !warnedOrphans.has(node)) {\n warnedOrphans.add(node);\n console.warn(\n `[bindSwitchCases] ${node.directives?.case !== undefined ? '@case' : '@default'} has no @switch parent, or its @switch is on a @for element, which ignores it; <${node.originalTagName ?? node.tagName}> is dropped, as in a build`\n );\n }\n continue;\n }\n if (node.directives?.switch === undefined) continue;\n if (isConditionalBranch(node)) continue;\n\n const parentElement = node.nodeId ? elMap.get(node.nodeId) : null;\n if (!parentElement) {\n console.error(\n '[bindSwitchCases] Could not find parent element for switch block'\n );\n continue;\n }\n if (\n bindSwitchBlock(node, parentElement, ctx, processedNodeIds, disposers) &&\n node.nodeId\n )\n switchIds.add(node.nodeId);\n }\n\n for (const node of nodes) {\n if (node.nodeId && switchIds.has(node.nodeId)) continue;\n if (node.nodeId && processedNodeIds.has(node.nodeId)) continue;\n if (isConditionalBranch(node)) continue;\n if (node.isComponent) continue;\n\n if (node.type === 'element' && node.children?.length) {\n const element = node.nodeId ? elMap.get(node.nodeId) : null;\n\n if (element instanceof Element) {\n bindSwitchCases(\n node.children,\n element,\n ctx,\n processedNodeIds,\n disposers\n );\n }\n }\n }\n\n return processedNodeIds;\n}\n\nfunction isConditionalBranch(node: PithyNode): boolean {\n return (\n node.directives?.if !== undefined ||\n node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined\n );\n}\n\n/**\n * Binds one @switch element whose DOM is already built.\n */\n/** @codexApi {\"parent\":\"pithy.directive.switch\",\"name\":\"bindSwitchBlock\",\"stability\":\"experimental\",\"signature\":\"(switchNode: PithyNode, parentElement: Element, ctx: Record<string, unknown>, processedNodeIds: Set<string>, disposers: (() => void)[]) => boolean\"} */\nexport function bindSwitchBlock(\n switchNode: PithyNode,\n parentElement: Element,\n ctx: Record<string, unknown>,\n processedNodeIds: Set<string>,\n disposers: (() => void)[]\n): boolean {\n const caseNodes = (switchNode.children || []).filter(\n child =>\n child.type === 'element' &&\n (child.directives?.case !== undefined || isDefaultCase(child))\n );\n if (caseNodes.length === 0) {\n removeNonCaseChildren(parentElement, [], switchNode);\n return true;\n }\n\n for (const node of caseNodes) {\n if (node.nodeId) processedNodeIds.add(node.nodeId);\n for (const loopNode of findAllNestedLoopNodes(node)) {\n if (loopNode.nodeId) processedNodeIds.add(loopNode.nodeId);\n }\n }\n\n const childByPid = new Map<string, Element>();\n for (const child of Array.from(parentElement.children)) {\n const pid = child.getAttribute('data-pid');\n if (pid) childByPid.set(pid, child as Element);\n }\n const caseElements = caseNodes\n .map(node => (node.nodeId ? childByPid.get(node.nodeId) : undefined))\n .filter((el): el is Element => el !== undefined);\n\n if (caseElements.length !== caseNodes.length) {\n console.error('[bindSwitchCases] Could not find all case elements');\n return true;\n }\n\n removeNonCaseChildren(parentElement, caseElements, switchNode);\n\n handleSwitchBlock(\n parentElement,\n caseElements,\n switchNode,\n caseNodes,\n ctx,\n disposers\n );\n return true;\n}\n\nconst warnedSwitches = new WeakSet<PithyNode>();\nconst warnedConflicts = new WeakSet<PithyNode>();\nconst warnedOrphans = new WeakSet<PithyNode>();\n\nfunction removeNonCaseChildren(\n parentElement: Element,\n caseElements: Element[],\n switchNode: PithyNode\n): void {\n const cases = new Set<Node>(caseElements);\n let dropped: string | undefined;\n for (const child of Array.from(parentElement.childNodes)) {\n if (cases.has(child)) continue;\n if (child.nodeType === Node.TEXT_NODE && !child.textContent?.trim()) {\n child.remove();\n continue;\n }\n const node = nodeExpando(child).__pithyNode;\n if (import.meta.env?.DEV && node && !warnedConflicts.has(node)) {\n warnedConflicts.add(node);\n for (const name of node.loopConflicts ?? [])\n console.warn(\n `[pithy] ${loopConflictMessage(node.originalTagName ?? node.tagName ?? '', name)}`\n );\n }\n if (child.nodeType === Node.TEXT_NODE)\n dropped ??= JSON.stringify(child.textContent?.trim());\n else if (node?.type === 'slot') dropped ??= '<slot>';\n else if (node) dropped ??= `<${node.originalTagName ?? node.tagName}>`;\n else if (child.nodeType === Node.ELEMENT_NODE)\n dropped ??= `<${(child as Element).localName}>`;\n child.remove();\n }\n if (dropped && import.meta.env?.DEV && !warnedSwitches.has(switchNode)) {\n warnedSwitches.add(switchNode);\n console.warn(\n `[bindSwitchCases] @switch renders only its @case/@default children; ${dropped} is dropped, as in a build`\n );\n }\n}\n\n/**\n * Handles rendering and reactivity for an @switch/@case/@default block.\n */\nfunction handleSwitchBlock(\n parentElement: Element,\n caseElements: Element[],\n switchNode: PithyNode,\n caseNodes: PithyNode[],\n ctx: Record<string, unknown>,\n disposers: (() => void)[]\n) {\n // Generate a unique ID for this switch block for debugging\n const switchId = Math.random().toString(36).substring(2, 8);\n\n // Create a placeholder comment to mark where our switch content should go\n const placeholder = document.createComment(`switch-block-${switchId}`);\n\n // Insert the placeholder at the beginning of the parent element\n parentElement.insertBefore(placeholder, parentElement.firstChild);\n\n // Remove all case elements from the DOM immediately\n for (const el of caseElements) {\n el.remove();\n }\n\n let current: Branch | null = null;\n\n // Cache for compiled expressions to avoid recompiling on each change\n const compiledExpressions = new Map<string, () => unknown>();\n\n // Helper function to compile and cache expressions\n function getCompiledExpression(expr: string, kind: string): () => unknown {\n if (!expr || expr.trim() === '') {\n return () => undefined;\n }\n\n // Check if we already compiled this expression\n const cacheKey = `${kind}:${expr}`;\n if (compiledExpressions.has(cacheKey)) {\n return compiledExpressions.get(cacheKey)!;\n }\n\n try {\n const fn = compileExpression(expr, ctx, undefined);\n compiledExpressions.set(cacheKey, fn);\n return fn;\n } catch (err) {\n console.error(`[Switch-${switchId}] Error compiling ${kind}:`, err);\n const fallbackFn = () => undefined;\n compiledExpressions.set(cacheKey, fallbackFn);\n return fallbackFn;\n }\n }\n\n // Helper function to safely evaluate expressions\n function safeEvaluate(expr: string, kind: string): unknown {\n const fn = getCompiledExpression(expr, kind);\n try {\n return fn();\n } catch (err) {\n console.error(`[Switch-${switchId}] Error evaluating ${kind}:`, err);\n return undefined;\n }\n }\n\n function cleanupCurrentBranch() {\n if (current) clearBranch(current);\n current = null;\n }\n\n // Shared logic for finding the matching case\n function findMatchingCase(): number {\n // Evaluate the switch expression\n const switchValue = safeEvaluate(switchNode.directives!.switch!, '@switch');\n\n // Find the matching case\n let matchIndex = -1;\n let defaultIndex = -1;\n\n for (let i = 0; i < caseNodes.length; i++) {\n const node = caseNodes[i];\n\n if (node.directives?.case !== undefined) {\n // This is a @case node\n const caseValue = safeEvaluate(node.directives.case, '@case');\n\n // Check if the case value matches the switch value\n if (caseValue === switchValue) {\n matchIndex = i;\n break;\n }\n } else if (isDefaultCase(node)) {\n // This is a @default node, remember its index but continue checking other cases\n if (defaultIndex === -1) defaultIndex = i;\n }\n }\n\n // If no case matched but we have a default, use that\n if (matchIndex === -1 && defaultIndex !== -1) {\n matchIndex = defaultIndex;\n }\n\n return matchIndex;\n }\n\n function renderMatchedCase(matchIndex: number): Branch | null {\n if (matchIndex < 0 || !placeholder.parentNode) return null;\n return renderBranch(caseNodes[matchIndex], ctx, placeholder);\n }\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n const matchIndex = findMatchingCase();\n const branch = renderMatchedCase(matchIndex);\n // Ensure nested directive disposers created during SSR are added\n // to the parent disposers array for proper cleanup on destroy()\n if (branch) disposers.push(...branch.disposers);\n } else {\n // Client mode: reactive effect for dynamic updates\n // Track the previous match index to avoid unnecessary DOM operations\n let previousMatchIndex = -1;\n\n // Set up the reactive effect and capture the stop function\n const stopEffect = effect(() => {\n const matchIndex = findMatchingCase();\n\n // Skip re-insertion if match hasn't changed\n if (matchIndex === previousMatchIndex) {\n return;\n }\n\n // Clean up the current branch before showing a new one\n cleanupCurrentBranch();\n // Update the previous match index\n previousMatchIndex = matchIndex;\n current = renderMatchedCase(matchIndex);\n\n // Don't return cleanup here - we handle cleanup explicitly:\n // 1. When match changes: cleanupCurrentBranch() is called above\n // 2. When effect stops: cleanupCurrentBranch is in disposers array\n });\n\n disposers.push(\n blockDisposer(stopEffect, cleanupCurrentBranch, placeholder)\n );\n }\n}\n"]}
1
+ {"version":3,"file":"bindSwitchCases.js","sourceRoot":"","sources":["../../src/compile/bindSwitchCases.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EACL,aAAa,EACb,mBAAmB,GAEpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAe,MAAM,gBAAgB,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC;;;GAGG;AACH,kRAAkR;AAClR,MAAM,UAAU,eAAe,CAC7B,KAAkB,EAClB,MAAkC,EAClC,GAA4B,EAC5B,mBAAgC,IAAI,GAAG,EAAE,EAAE,gCAAgC;AAC3E,YAA4B,EAAE,CAAC,gCAAgC;;IAE/D,qEAAqE;IACrE,qEAAqE;IACrE,MAAM,KAAK,GAAG,IAAI,GAAG,EAAmB,CAAC;IACzC,IAAI,MAAM,YAAY,OAAO,IAAI,MAAM,YAAY,gBAAgB,EAAE,CAAC;QACpE,MAAM,QAAQ,GAAG,MAAM,CAAC,gBAAgB,CAAC,YAAY,CAAC,CAAC;QACvD,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;YACpB,M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,kBAAkB,GAAG,CAAC,CAAC,CAAC;QAE5B,2DAA2D;QAC3D,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,EAAE;YAC7B,MAAM,UAAU,GAAG,gBAAgB,EAAE,CAAC;YAEtC,4CAA4C;YAC5C,IAAI,UAAU,KAAK,kBAAkB,EAAE,CAAC;gBACtC,OAAO;YACT,CAAC;YAED,uDAAuD;YACvD,oBAAoB,EAAE,CAAC;YACvB,kCAAkC;YAClC,kBAAkB,GAAG,UAAU,CAAC;YAChC,OAAO,GAAG,iBAAiB,CAAC,UAAU,CAAC,CAAC;YAExC,4DAA4D;YAC5D,gEAAgE;YAChE,mEAAmE;QACrE,CAAC,CAAC,CAAC;QAEH,SAAS,CAAC,IAAI,CACZ,aAAa,CAAC,UAAU,EAAE,oBAAoB,EAAE,WAAW,CAAC,CAC7D,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.switch\",\n \"title\": \"@switch directive\",\n \"category\": \"directive\"\n}\n*/\n\nimport {\n isDefaultCase,\n loopConflictMessage,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { effect } from '@pithyjs/signals';\nimport { compileExpression } from './compileExpression';\nimport { switchEvalMessage } from './evalDiagnostics';\nimport { findAllNestedLoopNodes } from './forLoops/loopTraversal';\nimport { blockDisposer } from './disposeOrder';\nimport { nodeExpando } from './nodeExpando';\nimport { clearBranch, renderBranch, type Branch } from './renderBranch';\nimport { isSSRMode } from './ssrMode';\n\n/**\n * Processes switch case directives (@switch, @case, @default) in the template.\n * Identifies switch blocks and delegates their handling to handleSwitchBlock.\n */\n/** @codexApi {\"parent\":\"pithy.directive.switch\",\"name\":\"bindSwitchCases\",\"stability\":\"stable\",\"signature\":\"(nodes: PithyNode[], rootEl: Element | DocumentFragment, ctx: Record<string, unknown>, processedNodeIds?: Set<string>, disposers?: (() => void)[]) => Set<string>\"} */\nexport function bindSwitchCases(\n nodes: PithyNode[],\n rootEl: Element | DocumentFragment,\n ctx: Record<string, unknown>,\n processedNodeIds: Set<string> = new Set(), // Track already processed nodes\n disposers: (() => void)[] = [] // Collect disposers for cleanup\n): Set<string> {\n // Performance optimization: Create a Map of all elements by data-pid\n // This makes element lookups O(1) instead of O(n) with querySelector\n const elMap = new Map<string, Element>();\n if (rootEl instanceof Element || rootEl instanceof DocumentFragment) {\n const elements = rootEl.querySelectorAll('[data-pid]');\n elements.forEach(el => {\n const pid = el.getAttribute('data-pid');\n if (pid) {\n elMap.set(pid, el as Element);\n }\n });\n }\n\n const switchIds = new Set<string>();\n\n for (const node of nodes) {\n if (node.type !== 'element') continue;\n if (\n (node.directives?.case !== undefined || isDefaultCase(node)) &&\n node.nodeId &&\n !processedNodeIds.has(node.nodeId) &&\n !isConditionalBranch(node)\n ) {\n processedNodeIds.add(node.nodeId);\n elMap.get(node.nodeId)?.remove();\n if (import.meta.env?.DEV && !warnedOrphans.has(node)) {\n warnedOrphans.add(node);\n console.warn(\n `[bindSwitchCases] ${node.directives?.case !== undefined ? '@case' : '@default'} has no @switch parent, or its @switch is on a @for element, which ignores it; <${node.originalTagName ?? node.tagName}> is dropped, as in a build`\n );\n }\n continue;\n }\n if (node.directives?.switch === undefined) continue;\n if (isConditionalBranch(node)) continue;\n\n const parentElement = node.nodeId ? elMap.get(node.nodeId) : null;\n if (!parentElement) {\n console.error(\n '[bindSwitchCases] Could not find parent element for switch block'\n );\n continue;\n }\n if (\n bindSwitchBlock(node, parentElement, ctx, processedNodeIds, disposers) &&\n node.nodeId\n )\n switchIds.add(node.nodeId);\n }\n\n for (const node of nodes) {\n if (node.nodeId && switchIds.has(node.nodeId)) continue;\n if (node.nodeId && processedNodeIds.has(node.nodeId)) continue;\n if (isConditionalBranch(node)) continue;\n if (node.isComponent) continue;\n\n if (node.type === 'element' && node.children?.length) {\n const element = node.nodeId ? elMap.get(node.nodeId) : null;\n\n if (element instanceof Element) {\n bindSwitchCases(\n node.children,\n element,\n ctx,\n processedNodeIds,\n disposers\n );\n }\n }\n }\n\n return processedNodeIds;\n}\n\nfunction isConditionalBranch(node: PithyNode): boolean {\n return (\n node.directives?.if !== undefined ||\n node.directives?.elseIf !== undefined ||\n node.directives?.else !== undefined\n );\n}\n\n/**\n * Binds one @switch element whose DOM is already built.\n */\n/** @codexApi {\"parent\":\"pithy.directive.switch\",\"name\":\"bindSwitchBlock\",\"stability\":\"experimental\",\"signature\":\"(switchNode: PithyNode, parentElement: Element, ctx: Record<string, unknown>, processedNodeIds: Set<string>, disposers: (() => void)[]) => boolean\"} */\nexport function bindSwitchBlock(\n switchNode: PithyNode,\n parentElement: Element,\n ctx: Record<string, unknown>,\n processedNodeIds: Set<string>,\n disposers: (() => void)[]\n): boolean {\n const caseNodes = (switchNode.children || []).filter(\n child =>\n child.type === 'element' &&\n (child.directives?.case !== undefined || isDefaultCase(child))\n );\n if (caseNodes.length === 0) {\n removeNonCaseChildren(parentElement, [], switchNode);\n return true;\n }\n\n for (const node of caseNodes) {\n if (node.nodeId) processedNodeIds.add(node.nodeId);\n for (const loopNode of findAllNestedLoopNodes(node)) {\n if (loopNode.nodeId) processedNodeIds.add(loopNode.nodeId);\n }\n }\n\n const childByPid = new Map<string, Element>();\n for (const child of Array.from(parentElement.children)) {\n const pid = child.getAttribute('data-pid');\n if (pid) childByPid.set(pid, child as Element);\n }\n const caseElements = caseNodes\n .map(node => (node.nodeId ? childByPid.get(node.nodeId) : undefined))\n .filter((el): el is Element => el !== undefined);\n\n if (caseElements.length !== caseNodes.length) {\n console.error('[bindSwitchCases] Could not find all case elements');\n return true;\n }\n\n removeNonCaseChildren(parentElement, caseElements, switchNode);\n\n handleSwitchBlock(\n parentElement,\n caseElements,\n switchNode,\n caseNodes,\n ctx,\n disposers\n );\n return true;\n}\n\nconst warnedSwitches = new WeakSet<PithyNode>();\nconst warnedConflicts = new WeakSet<PithyNode>();\nconst warnedOrphans = new WeakSet<PithyNode>();\n\nfunction removeNonCaseChildren(\n parentElement: Element,\n caseElements: Element[],\n switchNode: PithyNode\n): void {\n const cases = new Set<Node>(caseElements);\n let dropped: string | undefined;\n for (const child of Array.from(parentElement.childNodes)) {\n if (cases.has(child)) continue;\n if (child.nodeType === Node.TEXT_NODE && !child.textContent?.trim()) {\n child.remove();\n continue;\n }\n const node = nodeExpando(child).__pithyNode;\n if (import.meta.env?.DEV && node && !warnedConflicts.has(node)) {\n warnedConflicts.add(node);\n for (const name of node.loopConflicts ?? [])\n console.warn(\n `[pithy] ${loopConflictMessage(node.originalTagName ?? node.tagName ?? '', name)}`\n );\n }\n if (child.nodeType === Node.TEXT_NODE)\n dropped ??= JSON.stringify(child.textContent?.trim());\n else if (node?.type === 'slot') dropped ??= '<slot>';\n else if (node) dropped ??= `<${node.originalTagName ?? node.tagName}>`;\n else if (child.nodeType === Node.ELEMENT_NODE)\n dropped ??= `<${(child as Element).localName}>`;\n child.remove();\n }\n if (dropped && import.meta.env?.DEV && !warnedSwitches.has(switchNode)) {\n warnedSwitches.add(switchNode);\n console.warn(\n `[bindSwitchCases] @switch renders only its @case/@default children; ${dropped} is dropped, as in a build`\n );\n }\n}\n\n/**\n * Handles rendering and reactivity for an @switch/@case/@default block.\n */\nfunction handleSwitchBlock(\n parentElement: Element,\n caseElements: Element[],\n switchNode: PithyNode,\n caseNodes: PithyNode[],\n ctx: Record<string, unknown>,\n disposers: (() => void)[]\n) {\n // Generate a unique ID for this switch block for debugging\n const switchId = Math.random().toString(36).substring(2, 8);\n\n // Create a placeholder comment to mark where our switch content should go\n const placeholder = document.createComment(`switch-block-${switchId}`);\n\n // Insert the placeholder at the beginning of the parent element\n parentElement.insertBefore(placeholder, parentElement.firstChild);\n\n // Remove all case elements from the DOM immediately\n for (const el of caseElements) {\n el.remove();\n }\n\n let current: Branch | null = null;\n\n // Cache for compiled expressions to avoid recompiling on each change\n const compiledExpressions = new Map<string, () => unknown>();\n\n // Helper function to compile and cache expressions\n function getCompiledExpression(expr: string, kind: string): () => unknown {\n if (!expr || expr.trim() === '') {\n return () => undefined;\n }\n\n // Check if we already compiled this expression\n const cacheKey = `${kind}:${expr}`;\n if (compiledExpressions.has(cacheKey)) {\n return compiledExpressions.get(cacheKey)!;\n }\n\n try {\n const fn = compileExpression(expr, ctx, undefined);\n compiledExpressions.set(cacheKey, fn);\n return fn;\n } catch (err) {\n console.error(`[Switch-${switchId}] Error compiling ${kind}:`, err);\n const fallbackFn = () => undefined;\n compiledExpressions.set(cacheKey, fallbackFn);\n return fallbackFn;\n }\n }\n\n // Helper function to safely evaluate expressions\n function safeEvaluate(expr: string, kind: '@switch' | '@case'): unknown {\n const fn = getCompiledExpression(expr, kind);\n try {\n return fn();\n } catch (err) {\n console.error(switchEvalMessage(kind, expr), err);\n return undefined;\n }\n }\n\n function cleanupCurrentBranch() {\n if (current) clearBranch(current);\n current = null;\n }\n\n // Shared logic for finding the matching case\n function findMatchingCase(): number {\n // Evaluate the switch expression\n const switchValue = safeEvaluate(switchNode.directives!.switch!, '@switch');\n\n // Find the matching case\n let matchIndex = -1;\n let defaultIndex = -1;\n\n for (let i = 0; i < caseNodes.length; i++) {\n const node = caseNodes[i];\n\n if (node.directives?.case !== undefined) {\n // This is a @case node\n const caseValue = safeEvaluate(node.directives.case, '@case');\n\n // Check if the case value matches the switch value\n if (caseValue === switchValue) {\n matchIndex = i;\n break;\n }\n } else if (isDefaultCase(node)) {\n // This is a @default node, remember its index but continue checking other cases\n if (defaultIndex === -1) defaultIndex = i;\n }\n }\n\n // If no case matched but we have a default, use that\n if (matchIndex === -1 && defaultIndex !== -1) {\n matchIndex = defaultIndex;\n }\n\n return matchIndex;\n }\n\n function renderMatchedCase(matchIndex: number): Branch | null {\n if (matchIndex < 0 || !placeholder.parentNode) return null;\n return renderBranch(caseNodes[matchIndex], ctx, placeholder);\n }\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n const matchIndex = findMatchingCase();\n const branch = renderMatchedCase(matchIndex);\n // Ensure nested directive disposers created during SSR are added\n // to the parent disposers array for proper cleanup on destroy()\n if (branch) disposers.push(...branch.disposers);\n } else {\n // Client mode: reactive effect for dynamic updates\n // Track the previous match index to avoid unnecessary DOM operations\n let previousMatchIndex = -1;\n\n // Set up the reactive effect and capture the stop function\n const stopEffect = effect(() => {\n const matchIndex = findMatchingCase();\n\n // Skip re-insertion if match hasn't changed\n if (matchIndex === previousMatchIndex) {\n return;\n }\n\n // Clean up the current branch before showing a new one\n cleanupCurrentBranch();\n // Update the previous match index\n previousMatchIndex = matchIndex;\n current = renderMatchedCase(matchIndex);\n\n // Don't return cleanup here - we handle cleanup explicitly:\n // 1. When match changes: cleanupCurrentBranch() is called above\n // 2. When effect stops: cleanupCurrentBranch is in disposers array\n });\n\n disposers.push(\n blockDisposer(stopEffect, cleanupCurrentBranch, placeholder)\n );\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bindComponentsTags.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AA2DF,qGAAqG;AACrG,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AAmKD;;;;;;GAMG;AACH,4NAA4N;AAC5N,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,CAiaN"}
1
+ {"version":3,"file":"bindComponentsTags.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AA+DF,qGAAqG;AACrG,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AAqGD;;;;;;GAMG;AACH,4NAA4N;AAC5N,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,CAkbN"}
@@ -10,7 +10,7 @@ import { isTemplateAttr } from './declaredDirective.js';
10
10
  import { boundaryForElement, currentBoundary, replaceHidden, runWithBoundary, slotContentHidden, withSlotBoundary, } from './bindErrorBoundary.js';
11
11
  import { bindAfterComponents } from './bindAfterComponents.js';
12
12
  import { collectSlotMap, inProjectedContent } from '../contentProjection.js';
13
- import { componentChildDirectiveMessage, componentChildDirectives, nativeTags, } from '@pithyjs/compiler';
13
+ import { boundSlotMessage, componentChildDirectiveMessage, componentChildDirectives, nativeTags, } from '@pithyjs/compiler';
14
14
  import { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs.js';
15
15
  import { createRoot, untrack } from '@pithyjs/signals';
16
16
  import { watchStaleRowProp } from './staleRowProps.js';
@@ -19,9 +19,10 @@ import { invalidRenderError, invalidRenderMessage, propEvalMessage, } from '../e
19
19
  import { componentDisposer } from '../disposeOrder.js';
20
20
  import { pithyGlobals } from '../../types/globals.js';
21
21
  import { isSSRMode } from '../ssrMode.js';
22
- import { clearSSRRenderCrash, forgetCrash, hasCrashed, reportComponentFailure, resolveBeforeFallback, } from '../ssrCrashes.js';
22
+ import { clearSSRRenderCrash, forgetCrash, hasCrashed, failedInBranch, logFailure, reportComponentFailure, resolveBeforeFallback, } from '../ssrCrashes.js';
23
23
  import { isRenderableComponentEl } from '../componentResult.js';
24
- import { parsePropNames } from './propNames.js';
24
+ import { readPropNames } from './propNames.js';
25
+ import { warnBoundProps, warnUnexpectedProps } from './propWarnings.js';
25
26
  /**
26
27
  * Find the closest element-scoped context we attach in createLoopItem().
27
28
  * This is what exposes item(), gIdx(), count(), etc.
@@ -87,69 +88,20 @@ function evalInCtx(expr, ctx) {
87
88
  const fn = new Function(...keys, `return (${expr});`);
88
89
  return fn(...vals);
89
90
  }
90
- const propNameCache = new WeakMap();
91
- function readPropNames(componentFn) {
92
- let cached = propNameCache.get(componentFn);
93
- if (!cached) {
94
- try {
95
- cached = parsePropNames(componentFn.toString());
96
- }
97
- catch {
98
- cached = { names: [], fromParam: false, exhaustive: false };
99
- }
100
- propNameCache.set(componentFn, cached);
101
- }
102
- return cached;
103
- }
104
91
  function extractExpectedPropNames(componentFn) {
105
92
  return readPropNames(componentFn).names;
106
93
  }
107
- const warnedBoundProps = new Set();
108
- const GLOBAL_ATTRS = new Set([
109
- 'id',
110
- 'class',
111
- 'style',
112
- 'title',
113
- 'role',
114
- 'tabindex',
115
- 'hidden',
116
- ]);
117
- function warnBoundProps(componentFn, el, componentName) {
118
- const expected = extractExpectedPropNames(componentFn);
119
- for (const attr of Array.from(el.attributes)) {
120
- if (!attr.name.startsWith('data-bind-'))
121
- continue;
122
- const bound = attr.name.slice('data-bind-'.length);
123
- if (bound === 'slot' && !warnedBoundProps.has(`${componentName} slot`)) {
124
- warnedBoundProps.add(`${componentName} slot`);
125
- console.warn(`[PithyJS] <${componentName}> [slot] cannot choose a slot: the key is read as a literal, so this lands in the default slot. Write slot="name".`);
126
- }
127
- if (GLOBAL_ATTRS.has(bound))
128
- continue;
129
- const prop = expected.find(p => p.toLowerCase() === bound);
130
- const key = `${componentName} ${bound}`;
131
- if (!prop || warnedBoundProps.has(key))
132
- continue;
133
- warnedBoundProps.add(key);
134
- console.warn(`[PithyJS] <${componentName}> [${bound}] sets an attribute on the rendered root, not the \`${prop}\` prop. Write ${prop}="…" without brackets to set the prop; for a live value pass a signal or () => … if the prop accepts one.`);
135
- }
136
- }
137
- /** Dev warnings for unexpected props (only if destructuring is present). */
138
- function validateComponentProps(componentFn, props, componentName) {
139
- const { names: allNames, exhaustive } = readPropNames(componentFn);
140
- if (!exhaustive || allNames.length === 0)
141
- return;
142
- const passed = Object.keys(props);
143
- const expectedSet = new Set(allNames);
144
- const unexpected = passed.filter(p => !expectedSet.has(p));
145
- if (unexpected.length) {
146
- console.warn(`[PithyJS] 🔍 Component <${componentName}> received unexpected props: ${unexpected.join(', ')}\nExpected props: ${allNames.join(', ')}\nPassed props: ${passed.join(', ')}`);
94
+ const warnedBoundSlots = new Set();
95
+ function warnBoundAttrs(componentFn, el, componentName) {
96
+ const bound = [];
97
+ for (const attr of Array.from(el.attributes))
98
+ if (attr.name.startsWith('data-bind-'))
99
+ bound.push(attr.name.slice('data-bind-'.length));
100
+ if (bound.includes('slot') && !warnedBoundSlots.has(componentName)) {
101
+ warnedBoundSlots.add(componentName);
102
+ console.warn(`[PithyJS] ${boundSlotMessage(componentName)}`);
147
103
  }
148
- // NOTE: We intentionally do NOT warn about "missing" props here.
149
- // In template-driven usage, props are assembled at runtime by
150
- // bindComponentTags(), so TypeScript cannot catch missing required
151
- // props in this path. Components should self-validate critical
152
- // props where appropriate (e.g. Toggle warns on empty label).
104
+ warnBoundProps(extractExpectedPropNames(componentFn), bound, componentName);
153
105
  }
154
106
  /** DOM a component already rendered: its native tags may share a component's name. */
155
107
  function inComponentDom(el) {
@@ -269,8 +221,8 @@ export function bindComponentTags(root, rootCtx, disposers) {
269
221
  // Hidden like a sibling an activated boundary detached: never rendered.
270
222
  if (withSlotBoundary(undefined, projectedHost, () => slotContentHidden(el)))
271
223
  continue;
272
- // Its crash belongs to a boundary already; a build never retries.
273
- if (hasCrashed(el))
224
+ // It failed already, and a build never retries (BUG-161).
225
+ if (hasCrashed(el) || failedInBranch(el))
274
226
  continue;
275
227
  const componentFn = candidate;
276
228
  resolveBeforeFallback(el);
@@ -317,12 +269,12 @@ export function bindComponentTags(root, rootCtx, disposers) {
317
269
  // Native elements are already filtered out earlier (line 197 for fallback, line 171 for parser).
318
270
  if (import.meta.env?.DEV) {
319
271
  const displayTag = pithyNode?.originalTagName || tag;
320
- validateComponentProps(componentFn, props, displayTag);
321
- warnBoundProps(componentFn, el, displayTag);
272
+ warnUnexpectedProps(readPropNames(componentFn), props, displayTag);
273
+ warnBoundAttrs(componentFn, el, displayTag);
322
274
  }
323
275
  // Collect content projection SlotMap from component children
324
276
  const pithyChildren = pithyNode?.children || [];
325
- const slotMap = collectSlotMap(pithyChildren, localCtx, el);
277
+ const slotMap = collectSlotMap(pithyChildren, localCtx, el, componentFn);
326
278
  // Create enhanced context with SlotMap for content projection
327
279
  const componentContext = {
328
280
  ...localCtx,
@@ -369,7 +321,7 @@ export function bindComponentTags(root, rootCtx, disposers) {
369
321
  g.__pithyComponentContext = originalContext;
370
322
  g.__pithyRenderingComponent = wasRendering;
371
323
  }
372
- });
324
+ }, el);
373
325
  }
374
326
  catch (err) {
375
327
  // Route sync render errors to the nearest boundary with escalation
@@ -379,14 +331,25 @@ export function bindComponentTags(root, rootCtx, disposers) {
379
331
  // already-active boundary with no free ancestor drops it (React's
380
332
  // first-error-wins). A component inside that boundary's `@fallback` is
381
333
  // the everyday case, and the fallback is what the user actually sees.
382
- const accepted = reportComponentFailure(el, tag, error, boundary);
383
- if (import.meta.env?.DEV) {
384
- // Say which of the two actually happened. "Captured" on a rejected
385
- // error reports the opposite of the truth, and this branch exists
386
- // precisely because the two are not the same.
387
- console.log(accepted
388
- ? `[ErrorBoundary] Captured sync render error in <${tag}>:`
389
- : `[ErrorBoundary] Boundary already active — error from <${tag}> was NOT captured:`, error.message);
334
+ const message = `❌ Component <${tag}> crashed during render:`;
335
+ const accepted = reportComponentFailure(el, tag, error, boundary, {
336
+ message,
337
+ onCaptured: () => {
338
+ if (import.meta.env?.DEV)
339
+ console.log(`[ErrorBoundary] Captured sync render error in <${tag}>:`, error.message);
340
+ },
341
+ });
342
+ if (!hasCrashed(el)) {
343
+ if (import.meta.env?.DEV) {
344
+ // Say which of the two actually happened. "Captured" on a rejected
345
+ // error reports the opposite of the truth, and this branch exists
346
+ // precisely because the two are not the same.
347
+ console.log(accepted
348
+ ? `[ErrorBoundary] Captured sync render error in <${tag}>:`
349
+ : `[ErrorBoundary] No boundary took the error from <${tag}>:`, error.message);
350
+ }
351
+ if (!accepted)
352
+ logFailure(el, () => console.error(message, error));
390
353
  }
391
354
  continue;
392
355
  }
@@ -410,7 +373,7 @@ export function bindComponentTags(root, rootCtx, disposers) {
410
373
  },
411
374
  });
412
375
  if (!attributed)
413
- console.error(message, err);
376
+ logFailure(el, () => console.error(message, err));
414
377
  continue;
415
378
  }
416
379
  if (!out ||
@@ -418,7 +381,7 @@ export function bindComponentTags(root, rootCtx, disposers) {
418
381
  !('el' in out) ||
419
382
  !isRenderableComponentEl(out.el, el)) {
420
383
  const displayTag = pithyNode?.originalTagName || tag;
421
- console.warn(invalidRenderMessage(displayTag));
384
+ logFailure(el, () => console.warn(invalidRenderMessage(displayTag)));
422
385
  // Not a throw, but the same outcome as one: the raw <${tag}> is left in
423
386
  // the document and the subtree never renders. Under SSR that is content
424
387
  // silently missing from the emitted HTML, so it is recorded exactly like
@@ -1 +1 @@
1
- {"version":3,"file":"bindComponentsTags.js","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,eAAe,EACf,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1E,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,EACxB,UAAU,GAEX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAChE,OAAO,EACL,kBAAkB,EAClB,oBAA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QAAQ,CAAC,sBAAsB,EAAE,CAAC;gBACnD,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;gBAC/B,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YACrD,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.components\",\n \"title\": \"Component Tag Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { compileExpression } from '../compileExpression';\nimport { isTemplateAttr } from './declaredDirective';\nimport {\n boundaryForElement,\n currentBoundary,\n replaceHidden,\n runWithBoundary,\n slotContentHidden,\n withSlotBoundary,\n} from './bindErrorBoundary';\nimport { bindAfterComponents } from './bindAfterComponents';\nimport { collectSlotMap, inProjectedContent } from '../contentProjection';\nimport {\n componentChildDirectiveMessage,\n componentChildDirectives,\n nativeTags,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs';\nimport { createRoot, untrack } from '@pithyjs/signals';\nimport { watchStaleRowProp } from './staleRowProps';\nimport { markForwardTarget, nodeExpando } from '../nodeExpando';\nimport {\n invalidRenderError,\n invalidRenderMessage,\n propEvalMessage,\n} from '../evalDiagnostics';\nimport { componentDisposer } from '../disposeOrder';\nimport { pithyGlobals } from '../../types/globals';\nimport { isSSRMode } from '../ssrMode';\nimport {\n clearSSRRenderCrash,\n forgetCrash,\n hasCrashed,\n reportComponentFailure,\n resolveBeforeFallback,\n} from '../ssrCrashes';\nimport { isRenderableComponentEl } from '../componentResult';\nimport { parsePropNames, type PropNames } from './propNames';\n\ninterface ComponentResult {\n /** Any DOM node — see the `Component` type for why this is not narrower. */\n el: Node;\n destroy?: () => void;\n}\ntype ComponentFn = (props: Record<string, unknown>) => ComponentResult;\n\n/**\n * Find the closest element-scoped context we attach in createLoopItem().\n * This is what exposes item(), gIdx(), count(), etc.\n */\n// Warn once per component/tag pair — the same idiom re-renders constantly\n// (e.g. a panel importing Button while using a native <button>), and\n// repeating the warning drowns out real ones.\nconst warnedComponentTags = new Set<string>();\nconst warnedChildDirectives = new WeakSet<PithyNode>();\n\n/** Test-only: forget which tags were warned about, so each render warns as a fresh process would. */\nexport function __resetComponentTagWarnings(): void {\n warnedComponentTags.clear();\n}\n\nfunction nearestCtx(\n el: Element,\n rootCtx: Record<string, unknown>\n): Record<string, unknown> {\n let n: Element | null = el;\n while (n) {\n const local = nodeExpando(n).__pithyCtx;\n if (local) return local;\n n = n.parentElement;\n }\n return rootCtx;\n}\n\n/**\n * Detect whether a node is inside a subtree that represents a NOT-YET-EXPANDED nested loop.\n * Those hosts are tagged in createLoopManager.createLoopItem() via `__pithySkipText`,\n * and real templates may also still carry @for / data-for before expansion.\n * We must *defer* binding for anything under such a host, otherwise expressions like item()\n * will throw ReferenceError (because inner loop ctx isn’t created yet).\n */\nfunction isInsidePendingLoopZone(node: Element): boolean {\n let p: Element | null = node;\n while (p) {\n if (nodeExpando(p).__pithySkipText) return true;\n if (\n p.hasAttribute &&\n (p.hasAttribute('@for') || p.hasAttribute('data-for'))\n ) {\n return true;\n }\n p = p.parentElement;\n }\n return false;\n}\n\n/** Evaluate `expr` in `ctx`. Try engine compiler first, then args-style fallback. */\nfunction evalInCtx(expr: string, ctx: Record<string, unknown>): unknown {\n // 1) Preferred: compileExpression uses `with(ctx) { return (...) }`\n try {\n const f = compileExpression(expr, ctx);\n try {\n return f();\n } catch {\n /* fall through to fallback */\n }\n } catch {\n /* fall through to fallback */\n }\n\n // 2) Fallback: args-style evaluator (robust even if compileExpression throws)\n const keys = Object.keys(ctx);\n const vals = keys.map(k => ctx[k]);\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const fn = new Function(...keys, `return (${expr});`) as (\n ...args: unknown[]\n ) => unknown;\n return fn(...vals);\n}\n\nconst propNameCache = new WeakMap<ComponentFn, PropNames>();\n\nfunction readPropNames(componentFn: ComponentFn): PropNames {\n let cached = propNameCache.get(componentFn);\n if (!cached) {\n try {\n cached = parsePropNames(componentFn.toString());\n } catch {\n cached = { names: [], fromParam: false, exhaustive: false };\n }\n propNameCache.set(componentFn, cached);\n }\n return cached;\n}\n\nfunction extractExpectedPropNames(componentFn: ComponentFn): string[] {\n return readPropNames(componentFn).names;\n}\n\nconst warnedBoundProps = new Set<string>();\nconst GLOBAL_ATTRS = new Set([\n 'id',\n 'class',\n 'style',\n 'title',\n 'role',\n 'tabindex',\n 'hidden',\n]);\n\nfunction warnBoundProps(\n componentFn: ComponentFn,\n el: Element,\n componentName: string\n): void {\n const expected = extractExpectedPropNames(componentFn);\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-bind-')) continue;\n const bound = attr.name.slice('data-bind-'.length);\n if (bound === 'slot' && !warnedBoundProps.has(`${componentName} slot`)) {\n warnedBoundProps.add(`${componentName} slot`);\n console.warn(\n `[PithyJS] <${componentName}> [slot] cannot choose a slot: the key is read as a literal, so this lands in the default slot. Write slot=\"name\".`\n );\n }\n if (GLOBAL_ATTRS.has(bound)) continue;\n const prop = expected.find(p => p.toLowerCase() === bound);\n const key = `${componentName} ${bound}`;\n if (!prop || warnedBoundProps.has(key)) continue;\n warnedBoundProps.add(key);\n console.warn(\n `[PithyJS] <${componentName}> [${bound}] sets an attribute on the rendered root, not the \\`${prop}\\` prop. Write ${prop}=\"…\" without brackets to set the prop; for a live value pass a signal or () => … if the prop accepts one.`\n );\n }\n}\n\n/** Dev warnings for unexpected props (only if destructuring is present). */\nfunction validateComponentProps(\n componentFn: ComponentFn,\n props: Record<string, unknown>,\n componentName: string\n): void {\n const { names: allNames, exhaustive } = readPropNames(componentFn);\n if (!exhaustive || allNames.length === 0) return;\n\n const passed = Object.keys(props);\n const expectedSet = new Set(allNames);\n\n const unexpected = passed.filter(p => !expectedSet.has(p));\n if (unexpected.length) {\n console.warn(\n `[PithyJS] 🔍 Component <${componentName}> received unexpected props: ${unexpected.join(\n ', '\n )}\\nExpected props: ${allNames.join(', ')}\\nPassed props: ${passed.join(', ')}`\n );\n }\n\n // NOTE: We intentionally do NOT warn about \"missing\" props here.\n // In template-driven usage, props are assembled at runtime by\n // bindComponentTags(), so TypeScript cannot catch missing required\n // props in this path. Components should self-validate critical\n // props where appropriate (e.g. Toggle warns on empty label).\n}\n\n/** DOM a component already rendered: its native tags may share a component's name. */\nfunction inComponentDom(el: Element): boolean {\n for (let n: Element | null = el; n; n = n.parentElement)\n if (nodeExpando(n).__pithyComponentDom) return true;\n return false;\n}\n\n/** Map lowercased DOM attr name to expected prop name (case-insensitive). */\nfunction normalizePropName(\n authoredName: string,\n expectedProps: string[]\n): string {\n if (expectedProps.includes(authoredName)) return authoredName;\n const lower = authoredName.toLowerCase();\n const matches = expectedProps.filter(p => p.toLowerCase() === lower);\n return matches.length === 1 ? matches[0] : authoredName;\n}\n\n/**\n * Replace custom component tags (<Counter/>, <NestedComponent/>) with rendered output.\n * - Skips anything under a pending nested loop host (bind after loop expansion)\n * - Evaluates prop expressions in nearest loop ctx\n * - Case-insensitive prop name normalization\n * - No raw-string fallback (prevents things like calling count() on a string)\n */\n/** @codexApi {\"parent\":\"pithy.runtime.components\",\"name\":\"bindComponentTags\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindComponentTags(\n root: Element | DocumentFragment,\n rootCtx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // case-insensitive tag lookup from context\n const tagMap = new Map<string, unknown>(\n Object.keys(rootCtx).map(k => [k.toLowerCase(), rootCtx[k]])\n );\n\n const scope =\n root instanceof Element ? (root as Element) : (root as DocumentFragment);\n const elements = Array.from(scope.querySelectorAll('*'));\n\n for (const el of elements) {\n // Skip elements removed from the tree by a parent component's render, or\n // hidden by an `@error-boundary` that has since activated.\n if (!scope.contains(el)) {\n // An element that has left the tree contributes nothing to the output, so\n // a crash recorded for it on an earlier detached pass is stale.\n forgetCrash(el);\n continue;\n }\n\n // Defer components inside not-yet-expanded loops\n if (isInsidePendingLoopZone(el)) continue;\n\n // A build's placeholder carries no AST: its children are DOM, which only\n // the AOT binder reads.\n const aotMount = nodeExpando(el).__pithyAotMount;\n if (aotMount) {\n // Marked as below, so the text pass skips what the component rendered.\n for (const node of aotMount(disposers))\n nodeExpando(node).__pithyComponentDom = true;\n continue;\n }\n\n const tag = el.tagName.toLowerCase();\n\n // Check if the parser marked this element as a component\n // This is the authoritative source - it checks originalTagName starts with uppercase\n // AND the tag name exists in importedIdentifiers\n const pithyNode = nodeExpando(el).__pithyNode;\n if (pithyNode) {\n // Parser processed this element - use its isComponent flag\n if (!pithyNode.isComponent) {\n // DEV: Warn if there's a component that matches case-insensitively\n // This helps developers catch typos like <button> when they meant <Button>\n // Skip warning if we're inside a component's render (the component might\n // legitimately use native elements like <button> in its implementation)\n const isInsideComponentRender =\n !!pithyGlobals().__pithyRenderingComponent;\n if (\n import.meta.env?.DEV &&\n !isInsideComponentRender &&\n !inComponentDom(el)\n ) {\n const matchingComponent = tagMap.get(tag);\n if (matchingComponent && typeof matchingComponent === 'function') {\n // Find the actual component name from context\n const componentName = Object.keys(rootCtx).find(\n k => k.toLowerCase() === tag && rootCtx[k] === matchingComponent\n );\n const warnKey = `${componentName}:${pithyNode.originalTagName}`;\n if (\n componentName &&\n componentName !== pithyNode.originalTagName &&\n !warnedComponentTags.has(warnKey)\n ) {\n warnedComponentTags.add(warnKey);\n console.warn(\n `[PithyJS] ⚠️ Component '${componentName}' is imported but used as '<${pithyNode.originalTagName}>'. ` +\n `Components must use PascalCase. Use '<${componentName}>' instead.`\n );\n }\n }\n }\n continue;\n }\n } else {\n // Fallback for elements not processed by our parser:\n // Skip native HTML elements to prevent <button> matching Button component\n if (nativeTags.has(tag)) continue;\n // Rendered already, e.g. a build's slot content.\n if (inComponentDom(el)) continue;\n }\n\n if (\n import.meta.env?.DEV &&\n pithyNode &&\n !warnedChildDirectives.has(pithyNode)\n ) {\n warnedChildDirectives.add(pithyNode);\n for (const name of componentChildDirectives(pithyNode))\n console.warn(\n `[pithy] ${componentChildDirectiveMessage(pithyNode.originalTagName ?? tag, name)}`\n );\n }\n\n let candidate = tagMap.get(tag);\n\n if (!candidate) continue;\n\n // Support default exports\n if (\n candidate &&\n typeof candidate === 'object' &&\n 'default' in candidate &&\n typeof candidate.default === 'function'\n ) {\n candidate = candidate.default;\n }\n if (typeof candidate !== 'function') continue;\n // Content a runtime-compiled receiver projected: bound detached, inside the\n // output of the component being rendered.\n const projectedHost =\n !el.closest('[data-error]') && inProjectedContent(el)\n ? pithyGlobals().__pithyComponentContext?.__slotHost\n : undefined;\n // Hidden like a sibling an activated boundary detached: never rendered.\n if (withSlotBoundary(undefined, projectedHost, () => slotContentHidden(el)))\n continue;\n\n // Its crash belongs to a boundary already; a build never retries.\n if (hasCrashed(el)) continue;\n\n const componentFn = candidate as ComponentFn;\n resolveBeforeFallback(el);\n const localCtx = nearestCtx(el, rootCtx); // crucial for item(), gIdx(), etc.\n\n // Extract expected props for validation (DEV) and prop name normalization (always)\n // This ensures case-insensitive matching works even when originalAttrs is unavailable\n const { names, fromParam } = readPropNames(componentFn);\n const expectedProps = fromParam ? names : [];\n\n // Preserve originally-authored attribute names/casing from the parsed template\n // (pithyNode already extracted above for isComponent check)\n const originalAttrs: Record<string, string> | undefined =\n pithyNode?.originalAttrs;\n\n const props: Record<string, unknown> = {};\n\n const staleWatchers: (() => void)[] = [];\n\n // Evaluate attributes as expressions in localCtx\n for (const attr of Array.from(el.attributes)) {\n const name = attr.name;\n const raw = attr.value;\n\n // Skip internal/behavioral attributes\n if (name.startsWith('data-')) continue;\n if (name === 'class' || name === 'style' || name === 'slot') continue;\n if (!isTemplateAttr(attr)) continue;\n\n // Prefer originally-authored name (preserve casing), else DOM name\n const authored = originalAttrs?.[name] ?? name;\n const propName = normalizePropName(authored, expectedProps);\n\n try {\n const value = untrack(() => evalInCtx(raw, localCtx));\n props[propName] = value; // only set when evaluation succeeds\n if (import.meta.env?.DEV) {\n staleWatchers.push(() =>\n watchStaleRowProp(\n localCtx,\n pithyNode ?? el,\n pithyNode?.originalTagName || tag,\n propName,\n raw,\n value,\n () => evalInCtx(raw, localCtx),\n disposers\n )\n );\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(propEvalMessage(propName, raw), err);\n }\n // IMPORTANT: do NOT set a raw string fallback here.\n // Leaving it undefined lets the child use defaults and avoids count()-on-string.\n }\n }\n\n // Validate props for all components in DEV mode.\n // Native elements are already filtered out earlier (line 197 for fallback, line 171 for parser).\n if (import.meta.env?.DEV) {\n const displayTag = pithyNode?.originalTagName || tag;\n validateComponentProps(componentFn, props, displayTag);\n warnBoundProps(componentFn, el, displayTag);\n }\n\n // Collect content projection SlotMap from component children\n const pithyChildren: PithyNode[] = pithyNode?.children || [];\n const slotMap = collectSlotMap(pithyChildren, localCtx, el);\n\n // Create enhanced context with SlotMap for content projection\n const componentContext = {\n ...localCtx,\n __slotMap: slotMap,\n __childAstNodes: pithyChildren,\n __childFactory: undefined,\n __slotHost: el,\n };\n\n // Find nearest error boundary for this component\n const boundaryEl = el.closest('[data-error]') as Element | null;\n // Projected content is bound detached, during its receiver's render.\n const boundary =\n boundaryForElement(boundaryEl) ??\n (!boundaryEl && inProjectedContent(el) ? currentBoundary() : null);\n\n // Invoke component under boundary context; expect { el, destroy }\n let out: ComponentResult | undefined;\n let disposeSetup: (() => void) | undefined;\n try {\n out = runWithBoundary(boundary, () => {\n // Store the enhanced context globally for the component's html() calls to access.\n // This per-component context contains __slotMap for content projection.\n //\n // In SSR, there are TWO context sources that html() merges:\n // 1. AsyncLocalStorage context (__getComponentContext) - request-level isolation\n // 2. This global context (__pithyComponentContext) - per-component __slotMap\n //\n // Both are needed: AsyncLocalStorage provides request isolation, while this\n // global provides the __slotMap that changes for each component render.\n const g = pithyGlobals();\n const originalContext = g.__pithyComponentContext;\n const wasRendering = g.__pithyRenderingComponent;\n g.__pithyComponentContext = componentContext;\n // Mark that we're rendering a component to suppress casing warnings for\n // native elements used in component implementations (e.g., <button> in Button)\n g.__pithyRenderingComponent = true;\n\n try {\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return componentFn(props);\n });\n return result;\n } finally {\n // Restore original context\n g.__pithyComponentContext = originalContext;\n g.__pithyRenderingComponent = wasRendering;\n }\n });\n } catch (err) {\n // Route sync render errors to the nearest boundary with escalation\n if (boundary) {\n const error = err instanceof Error ? err : new Error(String(err));\n // A boundary being in scope does not mean it accepted the error: an\n // already-active boundary with no free ancestor drops it (React's\n // first-error-wins). A component inside that boundary's `@fallback` is\n // the everyday case, and the fallback is what the user actually sees.\n const accepted = reportComponentFailure(el, tag, error, boundary);\n if (import.meta.env?.DEV) {\n // Say which of the two actually happened. \"Captured\" on a rejected\n // error reports the opposite of the truth, and this branch exists\n // precisely because the two are not the same.\n console.log(\n accepted\n ? `[ErrorBoundary] Captured sync render error in <${tag}>:`\n : `[ErrorBoundary] Boundary already active — error from <${tag}> was NOT captured:`,\n error.message\n );\n }\n continue;\n }\n\n // No boundary reachable through the DOM. A branch, slot or component\n // built detached knows the one it will sit under (`deferCrash`).\n // Otherwise degrade in both modes.\n //\n // A static/server render additionally records the crash. Nobody reads a\n // console during `pithy-ssg`, so this used to leave the raw <${tag}> in\n // the emitted HTML while the route still counted as rendered and the CLI\n // exited 0 (BUG-018). Anything still recorded when the render finishes\n // makes the SSR renderer throw, and the per-route catch in `vite-ssg.ts`\n // fails that route.\n const error = err instanceof Error ? err : new Error(String(err));\n const message = `❌ Component <${tag}> crashed during render:`;\n const attributed = reportComponentFailure(el, tag, error, null, {\n message,\n onCaptured: () => {\n if (import.meta.env?.DEV)\n console.log(\n `[ErrorBoundary] Captured sync render error in <${tag}>:`,\n error.message\n );\n },\n });\n if (!attributed) console.error(message, err);\n continue;\n }\n\n if (\n !out ||\n typeof out !== 'object' ||\n !('el' in out) ||\n !isRenderableComponentEl(out.el, el)\n ) {\n const displayTag = pithyNode?.originalTagName || tag;\n console.warn(invalidRenderMessage(displayTag));\n // Not a throw, but the same outcome as one: the raw <${tag}> is left in\n // the document and the subtree never renders. Under SSR that is content\n // silently missing from the emitted HTML, so it is recorded exactly like\n // a crash (BUG-018). Recorded rather than merely left in place, because\n // this attempt may also be retracting an earlier attempt's record.\n // Same funnel as a throw: a boundary above this component gets the\n // chance to claim it and render its fallback, and only an unclaimed\n // failure is recorded. Bypassing this meant a component under\n // `@error-boundary` that returned garbage failed the route with the\n // boundary signal still null.\n reportComponentFailure(\n el,\n displayTag,\n invalidRenderError(displayTag),\n boundary\n );\n disposeSetup?.();\n continue;\n }\n\n const { el: renderedEl, destroy } = out;\n\n // Capture class and data-* attributes for forwarding to rendered root:\n // directive bindings (data-on-*, data-bind-*, data-class-toggle-*,\n // data-classes, data-style-*) plus any author-written data-* attribute.\n const forwardedClass = el.getAttribute('class');\n const forwardedAttrs = collectForwardedAttrs(el);\n\n const isFragment = renderedEl.nodeType === Node.DOCUMENT_FRAGMENT_NODE;\n let forwardTarget: HTMLElement | null = null;\n const hasForwardables = !!(forwardedClass || forwardedAttrs.length > 0);\n if (hasForwardables) {\n if (isFragment) {\n forwardTarget = (renderedEl as DocumentFragment)\n .firstElementChild as HTMLElement | null;\n if (import.meta.env?.DEV && !forwardTarget) {\n const displayTag = pithyNode?.originalTagName || tag;\n console.warn(\n `[PithyJS] <${displayTag}> has class or data-* attributes but returns a fragment with no element children — forwarding skipped.`\n );\n }\n } else if (renderedEl.nodeType === Node.ELEMENT_NODE) {\n forwardTarget = renderedEl as HTMLElement;\n }\n }\n\n const renderedNodes = isFragment\n ? Array.from(renderedEl.childNodes)\n : [renderedEl];\n const slotOwner = nodeExpando(el).__pithySlotOwner;\n for (const node of renderedNodes) {\n const x = nodeExpando(node);\n x.__pithyComponentDom = true;\n if (slotOwner) x.__pithySlotOwner ??= slotOwner;\n }\n\n let replaced = true;\n let hidden = false;\n try {\n // A boundary that caught a crash in this render may have hidden `el`.\n hidden = replaceHidden(el, renderedNodes);\n if (!hidden) el.replaceWith(...renderedNodes);\n } catch (err) {\n // A failed replacement leaves the raw <${tag}> exactly where a crash\n // would have, so it is the same content loss and is recorded the same way.\n replaced = false;\n const error = err instanceof Error ? err : new Error(String(err));\n reportComponentFailure(el, tag, error, boundary);\n console.error(`❌ Failed to replace <${tag}> with rendered DOM:`, err);\n }\n\n // Retracted only here, and in the boundary catch above — never eagerly at\n // the top of an attempt, where any early `continue` added later would\n // silently drop a real record. This is the point at which the component is\n // known to have produced a usable node AND to have reached the document, so\n // an earlier detached attempt's crash is genuinely no longer the outcome.\n if (isSSRMode() && replaced) clearSSRRenderCrash(el);\n\n for (const watch of staleWatchers) watch();\n\n // Forward class from component tag onto the rendered root element\n if (forwardedClass && forwardTarget) {\n for (const cls of forwardedClass.split(/\\s+/)) {\n if (cls) forwardTarget.classList.add(cls);\n }\n }\n\n // Before any binding pass below, which can throw.\n const teardown = componentDisposer(\n destroy,\n disposeSetup,\n renderedNodes[0] ?? (replaced ? null : el)\n );\n if (teardown) disposers.push(teardown);\n\n // Forward captured attributes so subsequent binders can attach the bindings\n if (forwardedAttrs.length > 0 && forwardTarget) {\n applyForwardedAttrs(forwardTarget, forwardedAttrs, tag);\n markForwardTarget(\n forwardTarget,\n localCtx,\n new Set(forwardedAttrs.map(([name]) => name))\n );\n const styleProps = Object.keys(pithyNode?.directives?.styleMap ?? {});\n if (styleProps.length)\n nodeExpando(forwardTarget).__styleProps = styleProps;\n const classToggles = Object.keys(pithyNode?.directives?.classMap ?? {});\n if (classToggles.length)\n nodeExpando(forwardTarget).__classToggles = classToggles;\n // Hidden, it is out of reach of this fragment's later passes. An active\n // nested boundary `hideContent` kept in place is still within reach.\n if (hidden && !forwardTarget.parentNode) {\n const detached = document.createDocumentFragment();\n detached.append(forwardTarget);\n bindAfterComponents(detached, localCtx, disposers);\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"bindComponentsTags.js","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAA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IAAI,aAAa,EAAE,CAAC;YAC/C,mBAAmB,CAAC,aAAa,EAAE,cAAc,EAAE,GAAG,CAAC,CAAC;YACxD,iBAAiB,CACf,aAAa,EACb,QAAQ,EACR,IAAI,GAAG,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAC9C,CAAC;YACF,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,IAAI,EAAE,CAAC,CAAC;YACtE,IAAI,UAAU,CAAC,MAAM;gBACnB,WAAW,CAAC,aAAa,CAAC,CAAC,YAAY,GAAG,UAAU,CAAC;YACvD,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,IAAI,EAAE,CAAC,CAAC;YACxE,IAAI,YAAY,CAAC,MAAM;gBACrB,WAAW,CAAC,aAAa,CAAC,CAAC,cAAc,GAAG,YAAY,CAAC;YAC3D,wEAAwE;YACxE,qEAAqE;YACrE,IAAI,MAAM,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,CAAC;gBACxC,MAAM,QAAQ,GAAG,QAAQ,CAAC,sBAAsB,EAAE,CAAC;gBACnD,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;gBAC/B,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YACrD,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.components\",\n \"title\": \"Component Tag Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { compileExpression } from '../compileExpression';\nimport { isTemplateAttr } from './declaredDirective';\nimport {\n boundaryForElement,\n currentBoundary,\n replaceHidden,\n runWithBoundary,\n slotContentHidden,\n withSlotBoundary,\n} from './bindErrorBoundary';\nimport { bindAfterComponents } from './bindAfterComponents';\nimport { collectSlotMap, inProjectedContent } from '../contentProjection';\nimport {\n boundSlotMessage,\n componentChildDirectiveMessage,\n componentChildDirectives,\n nativeTags,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs';\nimport { createRoot, untrack } from '@pithyjs/signals';\nimport { watchStaleRowProp } from './staleRowProps';\nimport { markForwardTarget, nodeExpando } from '../nodeExpando';\nimport {\n invalidRenderError,\n invalidRenderMessage,\n propEvalMessage,\n} from '../evalDiagnostics';\nimport { componentDisposer } from '../disposeOrder';\nimport { pithyGlobals } from '../../types/globals';\nimport { isSSRMode } from '../ssrMode';\nimport {\n clearSSRRenderCrash,\n forgetCrash,\n hasCrashed,\n failedInBranch,\n logFailure,\n reportComponentFailure,\n resolveBeforeFallback,\n} from '../ssrCrashes';\nimport { isRenderableComponentEl } from '../componentResult';\nimport { readPropNames } from './propNames';\nimport { warnBoundProps, warnUnexpectedProps } from './propWarnings';\n\ninterface ComponentResult {\n /** Any DOM node — see the `Component` type for why this is not narrower. */\n el: Node;\n destroy?: () => void;\n}\ntype ComponentFn = (props: Record<string, unknown>) => ComponentResult;\n\n/**\n * Find the closest element-scoped context we attach in createLoopItem().\n * This is what exposes item(), gIdx(), count(), etc.\n */\n// Warn once per component/tag pair — the same idiom re-renders constantly\n// (e.g. a panel importing Button while using a native <button>), and\n// repeating the warning drowns out real ones.\nconst warnedComponentTags = new Set<string>();\nconst warnedChildDirectives = new WeakSet<PithyNode>();\n\n/** Test-only: forget which tags were warned about, so each render warns as a fresh process would. */\nexport function __resetComponentTagWarnings(): void {\n warnedComponentTags.clear();\n}\n\nfunction nearestCtx(\n el: Element,\n rootCtx: Record<string, unknown>\n): Record<string, unknown> {\n let n: Element | null = el;\n while (n) {\n const local = nodeExpando(n).__pithyCtx;\n if (local) return local;\n n = n.parentElement;\n }\n return rootCtx;\n}\n\n/**\n * Detect whether a node is inside a subtree that represents a NOT-YET-EXPANDED nested loop.\n * Those hosts are tagged in createLoopManager.createLoopItem() via `__pithySkipText`,\n * and real templates may also still carry @for / data-for before expansion.\n * We must *defer* binding for anything under such a host, otherwise expressions like item()\n * will throw ReferenceError (because inner loop ctx isn’t created yet).\n */\nfunction isInsidePendingLoopZone(node: Element): boolean {\n let p: Element | null = node;\n while (p) {\n if (nodeExpando(p).__pithySkipText) return true;\n if (\n p.hasAttribute &&\n (p.hasAttribute('@for') || p.hasAttribute('data-for'))\n ) {\n return true;\n }\n p = p.parentElement;\n }\n return false;\n}\n\n/** Evaluate `expr` in `ctx`. Try engine compiler first, then args-style fallback. */\nfunction evalInCtx(expr: string, ctx: Record<string, unknown>): unknown {\n // 1) Preferred: compileExpression uses `with(ctx) { return (...) }`\n try {\n const f = compileExpression(expr, ctx);\n try {\n return f();\n } catch {\n /* fall through to fallback */\n }\n } catch {\n /* fall through to fallback */\n }\n\n // 2) Fallback: args-style evaluator (robust even if compileExpression throws)\n const keys = Object.keys(ctx);\n const vals = keys.map(k => ctx[k]);\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const fn = new Function(...keys, `return (${expr});`) as (\n ...args: unknown[]\n ) => unknown;\n return fn(...vals);\n}\n\nfunction extractExpectedPropNames(componentFn: ComponentFn): string[] {\n return readPropNames(componentFn).names;\n}\n\nconst warnedBoundSlots = new Set<string>();\n\nfunction warnBoundAttrs(\n componentFn: ComponentFn,\n el: Element,\n componentName: string\n): void {\n const bound: string[] = [];\n for (const attr of Array.from(el.attributes))\n if (attr.name.startsWith('data-bind-'))\n bound.push(attr.name.slice('data-bind-'.length));\n if (bound.includes('slot') && !warnedBoundSlots.has(componentName)) {\n warnedBoundSlots.add(componentName);\n console.warn(`[PithyJS] ${boundSlotMessage(componentName)}`);\n }\n warnBoundProps(extractExpectedPropNames(componentFn), bound, componentName);\n}\n\n/** DOM a component already rendered: its native tags may share a component's name. */\nfunction inComponentDom(el: Element): boolean {\n for (let n: Element | null = el; n; n = n.parentElement)\n if (nodeExpando(n).__pithyComponentDom) return true;\n return false;\n}\n\n/** Map lowercased DOM attr name to expected prop name (case-insensitive). */\nfunction normalizePropName(\n authoredName: string,\n expectedProps: string[]\n): string {\n if (expectedProps.includes(authoredName)) return authoredName;\n const lower = authoredName.toLowerCase();\n const matches = expectedProps.filter(p => p.toLowerCase() === lower);\n return matches.length === 1 ? matches[0] : authoredName;\n}\n\n/**\n * Replace custom component tags (<Counter/>, <NestedComponent/>) with rendered output.\n * - Skips anything under a pending nested loop host (bind after loop expansion)\n * - Evaluates prop expressions in nearest loop ctx\n * - Case-insensitive prop name normalization\n * - No raw-string fallback (prevents things like calling count() on a string)\n */\n/** @codexApi {\"parent\":\"pithy.runtime.components\",\"name\":\"bindComponentTags\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindComponentTags(\n root: Element | DocumentFragment,\n rootCtx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // case-insensitive tag lookup from context\n const tagMap = new Map<string, unknown>(\n Object.keys(rootCtx).map(k => [k.toLowerCase(), rootCtx[k]])\n );\n\n const scope =\n root instanceof Element ? (root as Element) : (root as DocumentFragment);\n const elements = Array.from(scope.querySelectorAll('*'));\n\n for (const el of elements) {\n // Skip elements removed from the tree by a parent component's render, or\n // hidden by an `@error-boundary` that has since activated.\n if (!scope.contains(el)) {\n // An element that has left the tree contributes nothing to the output, so\n // a crash recorded for it on an earlier detached pass is stale.\n forgetCrash(el);\n continue;\n }\n\n // Defer components inside not-yet-expanded loops\n if (isInsidePendingLoopZone(el)) continue;\n\n // A build's placeholder carries no AST: its children are DOM, which only\n // the AOT binder reads.\n const aotMount = nodeExpando(el).__pithyAotMount;\n if (aotMount) {\n // Marked as below, so the text pass skips what the component rendered.\n for (const node of aotMount(disposers))\n nodeExpando(node).__pithyComponentDom = true;\n continue;\n }\n\n const tag = el.tagName.toLowerCase();\n\n // Check if the parser marked this element as a component\n // This is the authoritative source - it checks originalTagName starts with uppercase\n // AND the tag name exists in importedIdentifiers\n const pithyNode = nodeExpando(el).__pithyNode;\n if (pithyNode) {\n // Parser processed this element - use its isComponent flag\n if (!pithyNode.isComponent) {\n // DEV: Warn if there's a component that matches case-insensitively\n // This helps developers catch typos like <button> when they meant <Button>\n // Skip warning if we're inside a component's render (the component might\n // legitimately use native elements like <button> in its implementation)\n const isInsideComponentRender =\n !!pithyGlobals().__pithyRenderingComponent;\n if (\n import.meta.env?.DEV &&\n !isInsideComponentRender &&\n !inComponentDom(el)\n ) {\n const matchingComponent = tagMap.get(tag);\n if (matchingComponent && typeof matchingComponent === 'function') {\n // Find the actual component name from context\n const componentName = Object.keys(rootCtx).find(\n k => k.toLowerCase() === tag && rootCtx[k] === matchingComponent\n );\n const warnKey = `${componentName}:${pithyNode.originalTagName}`;\n if (\n componentName &&\n componentName !== pithyNode.originalTagName &&\n !warnedComponentTags.has(warnKey)\n ) {\n warnedComponentTags.add(warnKey);\n console.warn(\n `[PithyJS] ⚠️ Component '${componentName}' is imported but used as '<${pithyNode.originalTagName}>'. ` +\n `Components must use PascalCase. Use '<${componentName}>' instead.`\n );\n }\n }\n }\n continue;\n }\n } else {\n // Fallback for elements not processed by our parser:\n // Skip native HTML elements to prevent <button> matching Button component\n if (nativeTags.has(tag)) continue;\n // Rendered already, e.g. a build's slot content.\n if (inComponentDom(el)) continue;\n }\n\n if (\n import.meta.env?.DEV &&\n pithyNode &&\n !warnedChildDirectives.has(pithyNode)\n ) {\n warnedChildDirectives.add(pithyNode);\n for (const name of componentChildDirectives(pithyNode))\n console.warn(\n `[pithy] ${componentChildDirectiveMessage(pithyNode.originalTagName ?? tag, name)}`\n );\n }\n\n let candidate = tagMap.get(tag);\n\n if (!candidate) continue;\n\n // Support default exports\n if (\n candidate &&\n typeof candidate === 'object' &&\n 'default' in candidate &&\n typeof candidate.default === 'function'\n ) {\n candidate = candidate.default;\n }\n if (typeof candidate !== 'function') continue;\n // Content a runtime-compiled receiver projected: bound detached, inside the\n // output of the component being rendered.\n const projectedHost =\n !el.closest('[data-error]') && inProjectedContent(el)\n ? pithyGlobals().__pithyComponentContext?.__slotHost\n : undefined;\n // Hidden like a sibling an activated boundary detached: never rendered.\n if (withSlotBoundary(undefined, projectedHost, () => slotContentHidden(el)))\n continue;\n\n // It failed already, and a build never retries (BUG-161).\n if (hasCrashed(el) || failedInBranch(el)) continue;\n\n const componentFn = candidate as ComponentFn;\n resolveBeforeFallback(el);\n const localCtx = nearestCtx(el, rootCtx); // crucial for item(), gIdx(), etc.\n\n // Extract expected props for validation (DEV) and prop name normalization (always)\n // This ensures case-insensitive matching works even when originalAttrs is unavailable\n const { names, fromParam } = readPropNames(componentFn);\n const expectedProps = fromParam ? names : [];\n\n // Preserve originally-authored attribute names/casing from the parsed template\n // (pithyNode already extracted above for isComponent check)\n const originalAttrs: Record<string, string> | undefined =\n pithyNode?.originalAttrs;\n\n const props: Record<string, unknown> = {};\n\n const staleWatchers: (() => void)[] = [];\n\n // Evaluate attributes as expressions in localCtx\n for (const attr of Array.from(el.attributes)) {\n const name = attr.name;\n const raw = attr.value;\n\n // Skip internal/behavioral attributes\n if (name.startsWith('data-')) continue;\n if (name === 'class' || name === 'style' || name === 'slot') continue;\n if (!isTemplateAttr(attr)) continue;\n\n // Prefer originally-authored name (preserve casing), else DOM name\n const authored = originalAttrs?.[name] ?? name;\n const propName = normalizePropName(authored, expectedProps);\n\n try {\n const value = untrack(() => evalInCtx(raw, localCtx));\n props[propName] = value; // only set when evaluation succeeds\n if (import.meta.env?.DEV) {\n staleWatchers.push(() =>\n watchStaleRowProp(\n localCtx,\n pithyNode ?? el,\n pithyNode?.originalTagName || tag,\n propName,\n raw,\n value,\n () => evalInCtx(raw, localCtx),\n disposers\n )\n );\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(propEvalMessage(propName, raw), err);\n }\n // IMPORTANT: do NOT set a raw string fallback here.\n // Leaving it undefined lets the child use defaults and avoids count()-on-string.\n }\n }\n\n // Validate props for all components in DEV mode.\n // Native elements are already filtered out earlier (line 197 for fallback, line 171 for parser).\n if (import.meta.env?.DEV) {\n const displayTag = pithyNode?.originalTagName || tag;\n warnUnexpectedProps(readPropNames(componentFn), props, displayTag);\n warnBoundAttrs(componentFn, el, displayTag);\n }\n\n // Collect content projection SlotMap from component children\n const pithyChildren: PithyNode[] = pithyNode?.children || [];\n const slotMap = collectSlotMap(pithyChildren, localCtx, el, componentFn);\n\n // Create enhanced context with SlotMap for content projection\n const componentContext = {\n ...localCtx,\n __slotMap: slotMap,\n __childAstNodes: pithyChildren,\n __childFactory: undefined,\n __slotHost: el,\n };\n\n // Find nearest error boundary for this component\n const boundaryEl = el.closest('[data-error]') as Element | null;\n // Projected content is bound detached, during its receiver's render.\n const boundary =\n boundaryForElement(boundaryEl) ??\n (!boundaryEl && inProjectedContent(el) ? currentBoundary() : null);\n\n // Invoke component under boundary context; expect { el, destroy }\n let out: ComponentResult | undefined;\n let disposeSetup: (() => void) | undefined;\n try {\n out = runWithBoundary(\n boundary,\n () => {\n // Store the enhanced context globally for the component's html() calls to access.\n // This per-component context contains __slotMap for content projection.\n //\n // In SSR, there are TWO context sources that html() merges:\n // 1. AsyncLocalStorage context (__getComponentContext) - request-level isolation\n // 2. This global context (__pithyComponentContext) - per-component __slotMap\n //\n // Both are needed: AsyncLocalStorage provides request isolation, while this\n // global provides the __slotMap that changes for each component render.\n const g = pithyGlobals();\n const originalContext = g.__pithyComponentContext;\n const wasRendering = g.__pithyRenderingComponent;\n g.__pithyComponentContext = componentContext;\n // Mark that we're rendering a component to suppress casing warnings for\n // native elements used in component implementations (e.g., <button> in Button)\n g.__pithyRenderingComponent = true;\n\n try {\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return componentFn(props);\n });\n return result;\n } finally {\n // Restore original context\n g.__pithyComponentContext = originalContext;\n g.__pithyRenderingComponent = wasRendering;\n }\n },\n el\n );\n } catch (err) {\n // Route sync render errors to the nearest boundary with escalation\n if (boundary) {\n const error = err instanceof Error ? err : new Error(String(err));\n // A boundary being in scope does not mean it accepted the error: an\n // already-active boundary with no free ancestor drops it (React's\n // first-error-wins). A component inside that boundary's `@fallback` is\n // the everyday case, and the fallback is what the user actually sees.\n const message = `❌ Component <${tag}> crashed during render:`;\n const accepted = reportComponentFailure(el, tag, error, boundary, {\n message,\n onCaptured: () => {\n if (import.meta.env?.DEV)\n console.log(\n `[ErrorBoundary] Captured sync render error in <${tag}>:`,\n error.message\n );\n },\n });\n if (!hasCrashed(el)) {\n if (import.meta.env?.DEV) {\n // Say which of the two actually happened. \"Captured\" on a rejected\n // error reports the opposite of the truth, and this branch exists\n // precisely because the two are not the same.\n console.log(\n accepted\n ? `[ErrorBoundary] Captured sync render error in <${tag}>:`\n : `[ErrorBoundary] No boundary took the error from <${tag}>:`,\n error.message\n );\n }\n if (!accepted) logFailure(el, () => console.error(message, error));\n }\n continue;\n }\n\n // No boundary reachable through the DOM. A branch, slot or component\n // built detached knows the one it will sit under (`deferCrash`).\n // Otherwise degrade in both modes.\n //\n // A static/server render additionally records the crash. Nobody reads a\n // console during `pithy-ssg`, so this used to leave the raw <${tag}> in\n // the emitted HTML while the route still counted as rendered and the CLI\n // exited 0 (BUG-018). Anything still recorded when the render finishes\n // makes the SSR renderer throw, and the per-route catch in `vite-ssg.ts`\n // fails that route.\n const error = err instanceof Error ? err : new Error(String(err));\n const message = `❌ Component <${tag}> crashed during render:`;\n const attributed = reportComponentFailure(el, tag, error, null, {\n message,\n onCaptured: () => {\n if (import.meta.env?.DEV)\n console.log(\n `[ErrorBoundary] Captured sync render error in <${tag}>:`,\n error.message\n );\n },\n });\n if (!attributed) logFailure(el, () => console.error(message, err));\n continue;\n }\n\n if (\n !out ||\n typeof out !== 'object' ||\n !('el' in out) ||\n !isRenderableComponentEl(out.el, el)\n ) {\n const displayTag = pithyNode?.originalTagName || tag;\n logFailure(el, () => console.warn(invalidRenderMessage(displayTag)));\n // Not a throw, but the same outcome as one: the raw <${tag}> is left in\n // the document and the subtree never renders. Under SSR that is content\n // silently missing from the emitted HTML, so it is recorded exactly like\n // a crash (BUG-018). Recorded rather than merely left in place, because\n // this attempt may also be retracting an earlier attempt's record.\n // Same funnel as a throw: a boundary above this component gets the\n // chance to claim it and render its fallback, and only an unclaimed\n // failure is recorded. Bypassing this meant a component under\n // `@error-boundary` that returned garbage failed the route with the\n // boundary signal still null.\n reportComponentFailure(\n el,\n displayTag,\n invalidRenderError(displayTag),\n boundary\n );\n disposeSetup?.();\n continue;\n }\n\n const { el: renderedEl, destroy } = out;\n\n // Capture class and data-* attributes for forwarding to rendered root:\n // directive bindings (data-on-*, data-bind-*, data-class-toggle-*,\n // data-classes, data-style-*) plus any author-written data-* attribute.\n const forwardedClass = el.getAttribute('class');\n const forwardedAttrs = collectForwardedAttrs(el);\n\n const isFragment = renderedEl.nodeType === Node.DOCUMENT_FRAGMENT_NODE;\n let forwardTarget: HTMLElement | null = null;\n const hasForwardables = !!(forwardedClass || forwardedAttrs.length > 0);\n if (hasForwardables) {\n if (isFragment) {\n forwardTarget = (renderedEl as DocumentFragment)\n .firstElementChild as HTMLElement | null;\n if (import.meta.env?.DEV && !forwardTarget) {\n const displayTag = pithyNode?.originalTagName || tag;\n console.warn(\n `[PithyJS] <${displayTag}> has class or data-* attributes but returns a fragment with no element children — forwarding skipped.`\n );\n }\n } else if (renderedEl.nodeType === Node.ELEMENT_NODE) {\n forwardTarget = renderedEl as HTMLElement;\n }\n }\n\n const renderedNodes = isFragment\n ? Array.from(renderedEl.childNodes)\n : [renderedEl];\n const slotOwner = nodeExpando(el).__pithySlotOwner;\n for (const node of renderedNodes) {\n const x = nodeExpando(node);\n x.__pithyComponentDom = true;\n if (slotOwner) x.__pithySlotOwner ??= slotOwner;\n }\n\n let replaced = true;\n let hidden = false;\n try {\n // A boundary that caught a crash in this render may have hidden `el`.\n hidden = replaceHidden(el, renderedNodes);\n if (!hidden) el.replaceWith(...renderedNodes);\n } catch (err) {\n // A failed replacement leaves the raw <${tag}> exactly where a crash\n // would have, so it is the same content loss and is recorded the same way.\n replaced = false;\n const error = err instanceof Error ? err : new Error(String(err));\n reportComponentFailure(el, tag, error, boundary);\n console.error(`❌ Failed to replace <${tag}> with rendered DOM:`, err);\n }\n\n // Retracted only here, and in the boundary catch above — never eagerly at\n // the top of an attempt, where any early `continue` added later would\n // silently drop a real record. This is the point at which the component is\n // known to have produced a usable node AND to have reached the document, so\n // an earlier detached attempt's crash is genuinely no longer the outcome.\n if (isSSRMode() && replaced) clearSSRRenderCrash(el);\n\n for (const watch of staleWatchers) watch();\n\n // Forward class from component tag onto the rendered root element\n if (forwardedClass && forwardTarget) {\n for (const cls of forwardedClass.split(/\\s+/)) {\n if (cls) forwardTarget.classList.add(cls);\n }\n }\n\n // Before any binding pass below, which can throw.\n const teardown = componentDisposer(\n destroy,\n disposeSetup,\n renderedNodes[0] ?? (replaced ? null : el)\n );\n if (teardown) disposers.push(teardown);\n\n // Forward captured attributes so subsequent binders can attach the bindings\n if (forwardedAttrs.length > 0 && forwardTarget) {\n applyForwardedAttrs(forwardTarget, forwardedAttrs, tag);\n markForwardTarget(\n forwardTarget,\n localCtx,\n new Set(forwardedAttrs.map(([name]) => name))\n );\n const styleProps = Object.keys(pithyNode?.directives?.styleMap ?? {});\n if (styleProps.length)\n nodeExpando(forwardTarget).__styleProps = styleProps;\n const classToggles = Object.keys(pithyNode?.directives?.classMap ?? {});\n if (classToggles.length)\n nodeExpando(forwardTarget).__classToggles = classToggles;\n // Hidden, it is out of reach of this fragment's later passes. An active\n // nested boundary `hideContent` kept in place is still within reach.\n if (hidden && !forwardTarget.parentNode) {\n const detached = document.createDocumentFragment();\n detached.append(forwardTarget);\n bindAfterComponents(detached, localCtx, disposers);\n }\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bindDefaultTwoWay.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindDefaultTwoWay.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAsBF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,qOAAqO;AACrO,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,CAwDN"}
1
+ {"version":3,"file":"bindDefaultTwoWay.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindDefaultTwoWay.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAuBF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,qOAAqO;AACrO,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,CAqDN"}
@@ -5,6 +5,7 @@
5
5
  "category": "runtime"
6
6
  }
7
7
  */
8
+ import { svgBindMessage } from '@pithyjs/compiler';
8
9
  import { isDeclaredDirective } from './declaredDirective.js';
9
10
  import { effect, isSignal } from '@pithyjs/signals';
10
11
  // Type guard to check if an element is an HTMLElement
@@ -45,7 +46,7 @@ export function bindDefaultTwoWay(fragment, context, disposers) {
45
46
  fragment.querySelectorAll('[data-bind]').forEach(element => {
46
47
  // Type guard to ensure we have an HTMLElement
47
48
  if (!isHTMLElement(element)) {
48
- console.warn(`[PithyJS] Element with data-bind is not an HTMLElement:`, element);
49
+ console.warn(`[PithyJS] ${svgBindMessage(element.localName)}`, element);
49
50
  return;
50
51
  }
51
52
  const el = element; // Now TypeScript knows this is HTMLElement