@barefootjs/jsx 0.39.9 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/adapters/attr-plan.d.ts +1 -20
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/dsl-template-adapter.d.ts +77 -1
  4. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  5. package/dist/adapters/loop-plan.d.ts +41 -1
  6. package/dist/adapters/loop-plan.d.ts.map +1 -1
  7. package/dist/augment-inherited-props.d.ts.map +1 -1
  8. package/dist/css-layer-prefixer.d.ts.map +1 -1
  9. package/dist/debug.d.ts.map +1 -1
  10. package/dist/index.d.ts +4 -4
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1965 -1862
  13. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  14. package/dist/ir-to-client-js/utils.d.ts +1 -1
  15. package/dist/jsx-to-ir.d.ts.map +1 -1
  16. package/dist/module-exports.d.ts.map +1 -1
  17. package/dist/scope/binding-scope.d.ts +2 -0
  18. package/dist/scope/binding-scope.d.ts.map +1 -1
  19. package/dist/template-parts.d.ts +1 -1
  20. package/dist/template-parts.d.ts.map +1 -1
  21. package/dist/types.d.ts +5 -1
  22. package/dist/types.d.ts.map +1 -1
  23. package/package.json +2 -2
  24. package/src/__tests__/attr-plan.test.ts +1 -14
  25. package/src/__tests__/client-template-escape-soundness.test.ts +17 -4
  26. package/src/__tests__/client-template-static-delimiters.test.ts +57 -0
  27. package/src/__tests__/dsl-template-adapter.test.ts +70 -0
  28. package/src/__tests__/extract-function-params.test.ts +37 -0
  29. package/src/__tests__/issue-2960-multi-root-cond-same-tag.test.ts +18 -0
  30. package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +11 -0
  31. package/src/__tests__/loop-plan.test.ts +66 -1
  32. package/src/__tests__/template-parts-literal-boundary.test.ts +22 -0
  33. package/src/adapters/attr-plan.ts +2 -54
  34. package/src/adapters/dsl-template-adapter.ts +144 -2
  35. package/src/adapters/loop-plan.ts +67 -2
  36. package/src/augment-inherited-props.ts +5 -9
  37. package/src/css-layer-prefixer.ts +4 -5
  38. package/src/debug.ts +1 -0
  39. package/src/index.ts +11 -3
  40. package/src/ir-to-client-js/compute-inlinability.ts +1 -1
  41. package/src/ir-to-client-js/html-template.ts +52 -45
  42. package/src/ir-to-client-js/utils.ts +1 -1
  43. package/src/jsx-to-ir.ts +34 -20
  44. package/src/loop-destructure.ts +4 -1
  45. package/src/module-exports.ts +13 -21
  46. package/src/rich-type-refusal.ts +3 -1
  47. package/src/scope/binding-scope.ts +5 -0
  48. package/src/template-parts.ts +4 -2
  49. package/src/template-position-walk.ts +3 -1
  50. package/src/types.ts +2 -1
@@ -20,6 +20,14 @@ import { markupSlotIdsOf } from './markup-slots.ts'
20
20
  import { isEventHandlerName } from '../event-handler-name.ts'
21
21
  import { writesAnyBinding } from '../props-binding.ts'
22
22
 
23
+ /** Static HTML is embedded in a JS template literal; dynamic expressions use interp(). */
24
+ function escapeStaticTemplateHtml(text: string): string {
25
+ return escapeHtml(text)
26
+ .replace(/\\/g, '\\\\')
27
+ .replace(/`/g, '\\`')
28
+ .replace(/\$\{/g, '\\${')
29
+ }
30
+
23
31
  /**
24
32
  * Split a template literal body into static segments and `${...}` interpolations,
25
33
  * correctly handling nested braces (e.g. object literals inside interpolations).
@@ -359,7 +367,7 @@ function renderTemplateAttrPart(
359
367
  case 'boolean-attr':
360
368
  return attrName
361
369
  case 'literal':
362
- return `${attrName}="${escapeHtml(v.value)}"`
370
+ return `${attrName}="${escapeStaticTemplateHtml(v.value)}"`
363
371
  case 'expression': {
364
372
  const valExpr = wrap(v.expr)
365
373
  return templateAttrExpr(attrName, valExpr, v.presenceOrUndefined)
@@ -793,7 +801,7 @@ export function irToHtmlTemplate(node: IRNode, restSpreadNames?: ReadonlySet<str
793
801
  case 'text':
794
802
  // IRText carries the entity-DECODED value; this string is parsed
795
803
  // as HTML (template.innerHTML), so re-escape for the HTML parser.
796
- return escapeHtml(node.value)
804
+ return escapeStaticTemplateHtml(node.value)
797
805
 
798
806
  case 'expression': {
799
807
  if (node.expr === 'null' || node.expr === 'undefined') return ''
@@ -928,7 +936,9 @@ export function irToHtmlTemplate(node: IRNode, restSpreadNames?: ReadonlySet<str
928
936
  if (childrenEntry) propsEntries.push(childrenEntry)
929
937
  const propsExpr = propsEntries.length > 0 ? `{${propsEntries.join(', ')}}` : '{}'
930
938
  const keyProp = node.props.find(p => p.name === 'key')
931
- const keyArg = keyProp ? `, ${attrValueToString(keyProp.value) ?? 'undefined'}` : ''
939
+ const keyArg = keyProp
940
+ ? `, ${transformKeyValue(keyProp.value, (expr, templateExpr) => wrapExpr(templateExpr ?? expr))}`
941
+ : ''
932
942
  // Pass slotId as suffix so $c() can find the child component by slot
933
943
  // after branch swap. A loop-item-root component owns a separate scope
934
944
  // per iteration (identified by `data-key`) rather than deriving from
@@ -1072,7 +1082,7 @@ export function buildLoopSkeletonTemplate(node: IRNode, safe: LoopSkeletonSafeSl
1072
1082
  const v = a.value
1073
1083
  switch (v.kind) {
1074
1084
  case 'literal':
1075
- attrParts.push(`${toHtmlAttrName(a.name)}="${escapeHtml(v.value)}"`)
1085
+ attrParts.push(`${toHtmlAttrName(a.name)}="${escapeStaticTemplateHtml(v.value)}"`)
1076
1086
  break
1077
1087
  case 'boolean-attr':
1078
1088
  attrParts.push(toHtmlAttrName(a.name))
@@ -1128,7 +1138,7 @@ export function buildLoopSkeletonTemplate(node: IRNode, safe: LoopSkeletonSafeSl
1128
1138
  case 'text':
1129
1139
  // IRText carries the entity-DECODED value; this string is parsed
1130
1140
  // as HTML (template.innerHTML), so re-escape for the HTML parser.
1131
- return escapeHtml(node.value)
1141
+ return escapeStaticTemplateHtml(node.value)
1132
1142
 
1133
1143
  case 'expression':
1134
1144
  if (node.expr === 'null' || node.expr === 'undefined') return ''
@@ -1402,7 +1412,7 @@ export function irToPlaceholderTemplate(node: IRNode, restSpreadNames?: Readonly
1402
1412
  case 'text':
1403
1413
  // IRText carries the entity-DECODED value; this string is parsed
1404
1414
  // as HTML (template.innerHTML), so re-escape for the HTML parser.
1405
- return escapeHtml(node.value)
1415
+ return escapeStaticTemplateHtml(node.value)
1406
1416
 
1407
1417
  case 'expression': {
1408
1418
  if (node.expr === 'null' || node.expr === 'undefined') return ''
@@ -1627,6 +1637,33 @@ export function addCondAttrToTemplate(html: string, condId: string): string {
1627
1637
  return `<!--bf-cond-start:${condId}-->${html}<!--bf-cond-end:${condId}-->`
1628
1638
  }
1629
1639
 
1640
+ function* templateHtmlTags(html: string): Generator<{ raw: string; end: number }> {
1641
+ let cursor = 0
1642
+ let noCommentEnd = false
1643
+ while (cursor < html.length) {
1644
+ const start = html.indexOf('<', cursor)
1645
+ if (start < 0) break
1646
+ cursor = start + 1
1647
+ if (html.startsWith('<!--', start) && !noCommentEnd) {
1648
+ const commentEnd = html.indexOf('-->', start + 4)
1649
+ if (commentEnd >= 0) {
1650
+ cursor = commentEnd + 3
1651
+ continue
1652
+ }
1653
+ // A failed search covers the entire remaining suffix, not just this opener.
1654
+ noCommentEnd = true
1655
+ }
1656
+ const nameStart = html[start + 1] === '/' ? start + 2 : start + 1
1657
+ if (nameStart >= html.length || /[\s/>]/.test(html[nameStart])) continue
1658
+ const end = html.indexOf('>', nameStart + 1)
1659
+ if (end < 0) break
1660
+ cursor = end + 1
1661
+ const raw = html.slice(start, cursor)
1662
+ if (raw.startsWith('<!--')) continue
1663
+ yield { raw, end: cursor }
1664
+ }
1665
+ }
1666
+
1630
1667
  /**
1631
1668
  * Check if HTML string has a single root element (not multiple siblings).
1632
1669
  *
@@ -1654,44 +1691,14 @@ function isSingleRootElement(html: string): boolean {
1654
1691
  // BOTH the `bf-c` stamp and the comment-wrap fallback for those roots.
1655
1692
  const match = trimmed.match(/^<(\w+)[\s>]/)
1656
1693
  if (!match) return false
1657
- // Self-closing tags like <br/>, <input/> with nothing else.
1658
- if (/^<\w+[^>]*\/>$/.test(trimmed)) return true
1659
-
1660
- // Walk top-level tags tracking nesting depth — see the docstring above
1661
- // for why (#2960). The comment alternative must come first so it wins at a `<!--`
1662
- // position — without it, a BarefootJS marker comment like
1663
- // `<!--bf:s1-->`/`<!--/-->` (a reactive text slot nested inside a
1664
- // genuine single root) matches the generic tag alternative too (its
1665
- // body has no `\s`, `/` or `>` before the closing `-->`) and gets
1666
- // miscounted as an opening tag, throwing off the depth count for
1667
- // perfectly ordinary single-root branches.
1668
- const tagPattern = /<!--[\s\S]*?-->|<\/?[^\s/>]+[^>]*>/g
1669
1694
  let depth = 0
1670
- let tagMatch: RegExpExecArray | null
1671
- while ((tagMatch = tagPattern.exec(trimmed))) {
1672
- const raw = tagMatch[0]
1673
- if (raw.startsWith('<!--')) continue // HTML comment, not a tag: depth unchanged
1695
+ for (const { raw, end } of templateHtmlTags(trimmed)) {
1674
1696
  if (raw.endsWith('/>')) {
1675
- // Self-closing/void tag (e.g. `<input .../>`). The whole-string
1676
- // check above only catches a self-closing tag with NOTHING else in
1677
- // the string — a self-closing root FOLLOWED by more content (e.g.
1678
- // `<input .../><label>...</label>`, a genuine two-root branch) still
1679
- // reaches here with the guard above already satisfied (it only
1680
- // looks at the tag name and the very next character, not whether
1681
- // the tag turns out to self-close). At depth 0 this tag completes a
1682
- // whole top-level unit by itself, so treat it exactly like any
1683
- // other tag's closing point: single root only if nothing follows.
1684
- // Nested inside another element (depth > 0) it's just an ordinary
1685
- // child and doesn't affect depth.
1686
- if (depth === 0) return tagPattern.lastIndex === trimmed.length
1697
+ if (depth === 0) return end === trimmed.length
1687
1698
  continue
1688
1699
  }
1689
1700
  depth += raw.startsWith('</') ? -1 : 1
1690
- if (depth === 0) {
1691
- // Back to depth 0: the root element's own closing tag. Single root
1692
- // only if nothing else follows it.
1693
- return tagPattern.lastIndex === trimmed.length
1694
- }
1701
+ if (depth === 0) return end === trimmed.length
1695
1702
  }
1696
1703
  return false
1697
1704
  }
@@ -1934,7 +1941,7 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
1934
1941
  return templateAttrExpr(keyName, transformExpr(tmplStr))
1935
1942
  }
1936
1943
  case 'literal':
1937
- return `${keyName}="${escapeHtml(v.value)}"`
1944
+ return `${keyName}="${escapeStaticTemplateHtml(v.value)}"`
1938
1945
  default:
1939
1946
  return ''
1940
1947
  }
@@ -1944,7 +1951,7 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
1944
1951
  case 'boolean-attr':
1945
1952
  return attrName
1946
1953
  case 'literal':
1947
- return `${attrName}="${escapeHtml(v.value)}"`
1954
+ return `${attrName}="${escapeStaticTemplateHtml(v.value)}"`
1948
1955
  case 'expression':
1949
1956
  return templateAttrExpr(attrName, transformExpr(v.expr, v.templateExpr), v.presenceOrUndefined)
1950
1957
  case 'template': {
@@ -1977,7 +1984,7 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
1977
1984
  case 'text':
1978
1985
  // IRText carries the entity-DECODED value; this string is parsed
1979
1986
  // as HTML (template.innerHTML), so re-escape for the HTML parser.
1980
- return escapeHtml(node.value)
1987
+ return escapeStaticTemplateHtml(node.value)
1981
1988
 
1982
1989
  case 'expression': {
1983
1990
  if (node.expr === 'null' || node.expr === 'undefined') return ''
@@ -2566,7 +2573,7 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2566
2573
  case 'boolean-attr':
2567
2574
  return keyName
2568
2575
  case 'literal':
2569
- return `${keyName}="${escapeHtml(v.value)}"`
2576
+ return `${keyName}="${escapeStaticTemplateHtml(v.value)}"`
2570
2577
  case 'expression':
2571
2578
  return templateAttrExpr(keyName, transformExpr(v.expr, v.templateExpr), v.presenceOrUndefined)
2572
2579
  case 'template': {
@@ -2583,7 +2590,7 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2583
2590
  case 'boolean-attr':
2584
2591
  return attrName
2585
2592
  case 'literal':
2586
- return `${attrName}="${escapeHtml(v.value)}"`
2593
+ return `${attrName}="${escapeStaticTemplateHtml(v.value)}"`
2587
2594
  case 'expression':
2588
2595
  return templateAttrExpr(attrName, transformExpr(v.expr, v.templateExpr), v.presenceOrUndefined)
2589
2596
  case 'template': {
@@ -2616,7 +2623,7 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2616
2623
  case 'text':
2617
2624
  // IRText carries the entity-DECODED value; this string is parsed
2618
2625
  // as HTML (template.innerHTML), so re-escape for the HTML parser.
2619
- return escapeHtml(node.value)
2626
+ return escapeStaticTemplateHtml(node.value)
2620
2627
 
2621
2628
  case 'expression':
2622
2629
  if (node.expr === 'null' || node.expr === 'undefined') return ''
@@ -213,7 +213,7 @@ export { templatePartsToJsExpr }
213
213
  * `boolean-shorthand`, `jsx-children`) — callers must branch on `value.kind`
214
214
  * before reaching them.
215
215
  *
216
- * When `opts.useTemplate` is set, prefers `templateExpr` / `templateValue` /
216
+ * When `opts.useTemplate` is set, prefers `templateExpr` /
217
217
  * `templateCondition` / `templateKey` (the prop-rewritten variant) over the
218
218
  * raw source form, for use in SSR template-literal interpolation.
219
219
  */
package/src/jsx-to-ir.ts CHANGED
@@ -1197,10 +1197,18 @@ function attachParsedAttrValues(
1197
1197
  node: IRNode,
1198
1198
  parse: (trimmed: string) => ParsedExpr,
1199
1199
  parseValue: (trimmed: string) => ParsedExpr,
1200
+ resolve: (parsed: ParsedExpr) => ParsedExpr,
1200
1201
  ): void {
1201
- const attach = (value: { kind: string; expr?: string; parsed?: ParsedExpr }, spreads: boolean): void => {
1202
- const trimmed = value.kind === 'expression' || (spreads && value.kind === 'spread') ? value.expr?.trim() : undefined
1203
- if (trimmed) value.parsed = value.kind === 'spread' ? parse(trimmed) : parseValue(trimmed)
1202
+ const attach = (value: AttrValue, spreads: boolean): void => {
1203
+ if (value.kind === 'template' || value.kind === 'expression') {
1204
+ for (const part of value.parts ?? []) {
1205
+ if (part.type === 'expression') part.parsed = resolve(part.parsed)
1206
+ }
1207
+ }
1208
+ if (value.kind === 'expression' || (spreads && value.kind === 'spread')) {
1209
+ const trimmed = value.expr.trim()
1210
+ if (trimmed) value.parsed = value.kind === 'spread' ? parse(trimmed) : parseValue(trimmed)
1211
+ }
1204
1212
  }
1205
1213
  if (node.type === 'element') {
1206
1214
  for (const attr of node.attrs) attach(attr.value, true)
@@ -1240,7 +1248,8 @@ function attachParsedExpressions(node: IRNode, analyzer: AnalyzerContext, scope:
1240
1248
  const trimmed = node.condition.trim()
1241
1249
  if (trimmed) node.parsedCondition = parse(trimmed)
1242
1250
  }
1243
- attachParsedAttrValues(node, parse, parseValue)
1251
+ attachParsedAttrValues(node, parse, parseValue,
1252
+ parsed => resolveCallbackMethodFunctionReferences(parsed, analyzer, bound))
1244
1253
  switch (node.type) {
1245
1254
  case 'element':
1246
1255
  case 'component':
@@ -2665,7 +2674,11 @@ function cleanJsxWhitespace(raw: string): string {
2665
2674
  const isLastLine = i === lines.length - 1
2666
2675
  let line = lines[i].replace(/\t/g, ' ')
2667
2676
  if (!isFirstLine) line = line.replace(/^ +/, '')
2668
- if (!isLastLine) line = line.replace(/ +$/, '')
2677
+ if (!isLastLine) {
2678
+ let end = line.length
2679
+ while (end > 0 && line[end - 1] === ' ') end--
2680
+ line = line.slice(0, end)
2681
+ }
2669
2682
  if (line !== '') kept.push(line)
2670
2683
  }
2671
2684
  return kept.join(' ')
@@ -6769,7 +6782,8 @@ function attrValueText(value: AttrValue): string {
6769
6782
  if (value.kind !== 'template') return ''
6770
6783
  const out: string[] = []
6771
6784
  for (const p of value.parts) {
6772
- if (p.type === 'ternary') out.push(p.condition, p.whenTrue, p.whenFalse)
6785
+ if (p.type === 'expression') out.push(p.expr)
6786
+ else if (p.type === 'ternary') out.push(p.condition, p.whenTrue, p.whenFalse)
6773
6787
  else if (p.type === 'lookup') out.push(p.key)
6774
6788
  }
6775
6789
  return out.join(' ')
@@ -8178,10 +8192,10 @@ function parseTemplateLiteral(
8178
8192
  if (ternary) {
8179
8193
  parts.push(ternary)
8180
8194
  } else {
8181
- // Fallback: keep as string expression
8195
+ // Preserve the expression as a distinct part.
8182
8196
  const val = ctx.getJS(span.expression)
8183
8197
  const tVal = rewriteBarePropRefs(val, span.expression, ctx)
8184
- parts.push({ type: 'string', value: `\${${val}}`, templateValue: tVal ? `\${${tVal}}` : undefined })
8198
+ parts.push({ type: 'expression', expr: val, templateExpr: tVal, parsed: parseValueExpr(val) })
8185
8199
  }
8186
8200
  } else {
8187
8201
  // Try to resolve `${IDENT}` against local consts (string literal
@@ -8192,10 +8206,10 @@ function parseTemplateLiteral(
8192
8206
  if (resolved) {
8193
8207
  parts.push(...resolved)
8194
8208
  } else {
8195
- // Non-ternary expression: keep as ${expr}
8209
+ // Preserve unresolved expressions for the target renderer.
8196
8210
  const val = ctx.getJS(span.expression)
8197
8211
  const tVal = rewriteBarePropRefs(val, span.expression, ctx)
8198
- parts.push({ type: 'string', value: `\${${val}}`, templateValue: tVal ? `\${${tVal}}` : undefined })
8212
+ parts.push({ type: 'expression', expr: val, templateExpr: tVal, parsed: parseValueExpr(val) })
8199
8213
  }
8200
8214
  }
8201
8215
 
@@ -8484,7 +8498,7 @@ function tryResolveIdentifierAsTemplateLiteral(
8484
8498
  // substitution or a Record lookup) to bother emitting structured
8485
8499
  // IR — otherwise the existing identifier-text path is more
8486
8500
  // efficient. Spans that don't resolve fall through to a bare
8487
- // `${expr}` string part (matching `parseTemplateLiteral`'s default).
8501
+ // expression part (matching `parseTemplateLiteral`'s default).
8488
8502
  let resolvedAny = false
8489
8503
  const parts: IRTemplatePart[] = []
8490
8504
  if (ast.head.text) parts.push({ type: 'string', value: ast.head.text })
@@ -8495,15 +8509,14 @@ function tryResolveIdentifierAsTemplateLiteral(
8495
8509
  resolvedAny = true
8496
8510
  parts.push(...resolved)
8497
8511
  } else {
8498
- // Unresolved span (e.g. a function param like `className`): keep
8499
- // as a bare ${expr} placeholder so adapters can substitute the
8500
- // matching prop/param at render time.
8512
+ // Unresolved spans retain their parsed expression for adapter emission.
8501
8513
  const text = astText(span.expression)
8502
8514
  const templateText = rewriteBarePropRefs(text, span.expression, ctx)
8503
8515
  parts.push({
8504
- type: 'string',
8505
- value: `\${${text}}`,
8506
- templateValue: templateText ? `\${${templateText}}` : undefined,
8516
+ type: 'expression',
8517
+ expr: text,
8518
+ templateExpr: templateText,
8519
+ parsed: parseValueExpr(text),
8507
8520
  })
8508
8521
  }
8509
8522
  if (span.literal.text) parts.push({ type: 'string', value: span.literal.text })
@@ -9072,7 +9085,7 @@ function processComponentProps(
9072
9085
  // shorthand (`<X disabled />` → `disabled={true}`).
9073
9086
  if (value.kind === 'template') {
9074
9087
  // Collapse using the raw part values, but also carry the
9075
- // template-variant projection (parts' `templateValue` /
9088
+ // template-variant projection (parts' `templateExpr` /
9076
9089
  // `templateCondition` / `templateKey`, i.e. destructured-prop refs
9077
9090
  // rewritten to `_p.X`) as `templateExpr`. Without it, the
9078
9091
  // `templateExpr` derivation below walks the ORIGINAL initializer AST
@@ -9891,10 +9904,11 @@ function attrValueReactivityProbe(value: AttrValue): string | null {
9891
9904
  return value.expr
9892
9905
  case 'template':
9893
9906
  return value.parts.map((p: IRTemplatePart) => {
9894
- if (p.type === 'string') return p.value
9907
+ if (p.type === 'string') return ''
9908
+ if (p.type === 'expression') return p.expr
9895
9909
  if (p.type === 'ternary') return p.condition
9896
9910
  return p.key
9897
- }).join('')
9911
+ }).join(' ')
9898
9912
  case 'literal':
9899
9913
  case 'boolean-attr':
9900
9914
  case 'boolean-shorthand':
@@ -140,7 +140,10 @@ function restNamesMisused(loop: IRLoop, names: string[]): boolean {
140
140
  }
141
141
  }
142
142
  const part = (p: IRTemplatePart): void => {
143
- if (p.type === 'ternary') {
143
+ if (p.type === 'expression') {
144
+ check(p.expr)
145
+ check(p.templateExpr)
146
+ } else if (p.type === 'ternary') {
144
147
  check(p.condition)
145
148
  check(p.templateCondition)
146
149
  check(p.whenTrue)
@@ -304,27 +304,19 @@ function isAssignmentOperator(kind: ts.SyntaxKind): boolean {
304
304
  * Strips type annotations and default values.
305
305
  */
306
306
  export function extractFunctionParams(value: string): string {
307
- // Match arrow function parameters: (a, b) => ... or async (a, b) => ...
308
- const arrowMatch = value.match(/^(?:async\s*)?\(([^)]*)\)\s*(?::\s*[^=]+)?\s*=>/)
309
- if (arrowMatch) {
310
- return arrowMatch[1]
311
- .split(',')
312
- .map((p) => p.trim().split(':')[0].split('=')[0].trim())
313
- .filter(Boolean)
314
- .join(', ')
315
- }
316
- // Single param arrow function: a => ...
317
- const singleMatch = value.match(/^(?:async\s*)?(\w+)\s*=>/)
318
- if (singleMatch) {
319
- return singleMatch[1]
320
- }
321
- // Function expression: function(a, b) { ... }
322
- const funcMatch = value.match(/^(?:async\s*)?function\s*\w*\s*\(([^)]*)\)/)
323
- if (funcMatch) {
324
- return funcMatch[1]
325
- .split(',')
326
- .map((p) => p.trim().split(':')[0].split('=')[0].trim())
327
- .filter(Boolean)
307
+ for (const kind of [ts.ScriptKind.TSX, ts.ScriptKind.TS]) {
308
+ const source = ts.createSourceFile('function.tsx', `(${value}\n)`, ts.ScriptTarget.Latest, true, kind)
309
+ const diagnostics = 'parseDiagnostics' in source ? source.parseDiagnostics : undefined
310
+ if (Array.isArray(diagnostics) && diagnostics.length > 0) continue
311
+ const statement = source.statements[0]
312
+ if (!statement || !ts.isExpressionStatement(statement)) return ''
313
+
314
+ let expression = statement.expression
315
+ while (ts.isParenthesizedExpression(expression)) expression = expression.expression
316
+ if (!ts.isArrowFunction(expression) && !ts.isFunctionExpression(expression)) return ''
317
+
318
+ return expression.parameters
319
+ .map(parameter => `${parameter.dotDotDotToken ? '...' : ''}${parameter.name.getText(source)}`)
328
320
  .join(', ')
329
321
  }
330
322
  return ''
@@ -373,7 +373,9 @@ function walkTemplateParts(
373
373
  seen: Set<string>,
374
374
  ): void {
375
375
  for (const part of parts) {
376
- if (part.type === 'ternary') {
376
+ if (part.type === 'expression') {
377
+ checkExpr(part.parsed, loc, meta, bindings, matchers, errors, seen)
378
+ } else if (part.type === 'ternary') {
377
379
  const trimmed = part.condition.trim()
378
380
  if (trimmed) checkExpr(parseExpression(trimmed), loc, meta, bindings, matchers, errors, seen)
379
381
  } else if (part.type === 'lookup') {
@@ -213,6 +213,11 @@ export class BindingScope {
213
213
  return hit ? hit.binding.stringValue === true : outer(name)
214
214
  }
215
215
 
216
+ /** The names the innermost frame binds, in binding order. */
217
+ innermostNames(): readonly string[] {
218
+ return this.frames[0] ? [...this.frames[0].bindings.keys()] : []
219
+ }
220
+
216
221
  /** Names this frame shadows in an enclosing callback/row frame. */
217
222
  shadowedNames(): readonly string[] {
218
223
  if (!this.frames[0]) return []
@@ -14,7 +14,7 @@ import type { IRTemplatePart } from './types.ts'
14
14
 
15
15
  export interface TemplatePartsToJsOptions {
16
16
  /**
17
- * Prefer each part's prop-rewritten projection (`templateValue` /
17
+ * Prefer each part's prop-rewritten projection (`templateExpr` /
18
18
  * `templateCondition` / `templateKey`, i.e. destructured props rewritten
19
19
  * to `_p.X`) when present. Used by the client-JS / module-registration
20
20
  * template emitters, which run outside the component's destructured scope.
@@ -68,7 +68,9 @@ export function templatePartsToJsExpr(
68
68
  let result = '`'
69
69
  for (const part of parts) {
70
70
  if (part.type === 'string') {
71
- result += (opts?.useTemplate && part.templateValue) ? part.templateValue : part.value
71
+ result += part.value.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${').replace(/\r/g, '\\r')
72
+ } else if (part.type === 'expression') {
73
+ result += `\${${opts?.useTemplate ? part.templateExpr ?? part.expr : part.expr}}`
72
74
  } else if (part.type === 'ternary') {
73
75
  const cond = (opts?.useTemplate && part.templateCondition) ? part.templateCondition : part.condition
74
76
  result += `\${${cond} ? '${part.whenTrue}' : '${part.whenFalse}'}`
@@ -105,7 +105,9 @@ function walkTemplateParts(
105
105
  visit({ expr: parseExpression(trimmed), loc, role: 'template-part', attrName })
106
106
  }
107
107
  for (const part of parts) {
108
- if (part.type === 'ternary') {
108
+ if (part.type === 'expression') {
109
+ visit({ expr: part.parsed, loc, role: 'template-part', attrName })
110
+ } else if (part.type === 'ternary') {
109
111
  visitText(part.condition)
110
112
  visitText(part.whenTrue)
111
113
  visitText(part.whenFalse)
package/src/types.ts CHANGED
@@ -1338,7 +1338,8 @@ export interface IRIfStatement {
1338
1338
  // =============================================================================
1339
1339
 
1340
1340
  export type IRTemplatePart =
1341
- | { type: 'string'; value: string; templateValue?: string }
1341
+ | { type: 'string'; value: string }
1342
+ | { type: 'expression'; expr: JsSourceText; templateExpr?: JsSourceText; parsed: ParsedExpr }
1342
1343
  | { type: 'ternary'; condition: string; templateCondition?: string; whenTrue: string; whenFalse: string }
1343
1344
  /**
1344
1345
  * `${MAP[KEY]}` indexed lookup against a `Record<T, string>` literal