@barefootjs/jsx 0.39.5 → 0.39.6

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 (57) hide show
  1. package/dist/adapters/array-method.d.ts +93 -0
  2. package/dist/adapters/array-method.d.ts.map +1 -0
  3. package/dist/adapters/attr-plan.d.ts +135 -0
  4. package/dist/adapters/attr-plan.d.ts.map +1 -0
  5. package/dist/adapters/boolean-result.d.ts +84 -9
  6. package/dist/adapters/boolean-result.d.ts.map +1 -1
  7. package/dist/adapters/callback-method.d.ts +126 -0
  8. package/dist/adapters/callback-method.d.ts.map +1 -0
  9. package/dist/adapters/component-props.d.ts +99 -0
  10. package/dist/adapters/component-props.d.ts.map +1 -0
  11. package/dist/adapters/component-tree.d.ts +25 -0
  12. package/dist/adapters/component-tree.d.ts.map +1 -0
  13. package/dist/adapters/literal-value.d.ts +22 -0
  14. package/dist/adapters/literal-value.d.ts.map +1 -0
  15. package/dist/adapters/loop-plan.d.ts +53 -0
  16. package/dist/adapters/loop-plan.d.ts.map +1 -0
  17. package/dist/adapters/prop-classes.d.ts +37 -0
  18. package/dist/adapters/prop-classes.d.ts.map +1 -0
  19. package/dist/expression-parser.d.ts +38 -0
  20. package/dist/expression-parser.d.ts.map +1 -1
  21. package/dist/index.d.ts +17 -3
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1765 -914
  24. package/dist/jsx-to-ir.d.ts +465 -1
  25. package/dist/jsx-to-ir.d.ts.map +1 -1
  26. package/dist/nullable-signal-attr.d.ts +19 -0
  27. package/dist/nullable-signal-attr.d.ts.map +1 -1
  28. package/package.json +2 -2
  29. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
  30. package/src/__tests__/action-accessor.test.ts +6 -24
  31. package/src/__tests__/array-method-catalogue.test.ts +99 -0
  32. package/src/__tests__/attr-plan.test.ts +121 -0
  33. package/src/__tests__/binding-scope-ratchet.test.ts +12 -12
  34. package/src/__tests__/boolean-result-expr.test.ts +106 -0
  35. package/src/__tests__/boolean-result.test.ts +34 -1
  36. package/src/__tests__/callback-method.test.ts +189 -0
  37. package/src/__tests__/component-props.test.ts +148 -0
  38. package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
  39. package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
  40. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
  41. package/src/__tests__/loop-plan.test.ts +104 -0
  42. package/src/__tests__/map-call-decisions.test.ts +521 -0
  43. package/src/__tests__/nullable-signal-attr.test.ts +45 -0
  44. package/src/adapters/array-method.ts +193 -0
  45. package/src/adapters/attr-plan.ts +200 -0
  46. package/src/adapters/boolean-result.ts +208 -12
  47. package/src/adapters/callback-method.ts +301 -0
  48. package/src/adapters/component-props.ts +144 -0
  49. package/src/adapters/component-tree.ts +118 -0
  50. package/src/adapters/literal-value.ts +36 -0
  51. package/src/adapters/loop-plan.ts +88 -0
  52. package/src/adapters/prop-classes.ts +73 -0
  53. package/src/expression-parser.ts +537 -374
  54. package/src/index.ts +53 -2
  55. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
  56. package/src/jsx-to-ir.ts +1328 -991
  57. package/src/nullable-signal-attr.ts +78 -0
package/dist/index.js CHANGED
@@ -501,6 +501,23 @@ var CALLBACK_METHODS = new Set([
501
501
  "reduceRight",
502
502
  "flatMap"
503
503
  ]);
504
+ function evaluatorBoundParamCount(method, scope) {
505
+ if (method === "sort" || method === "toSorted" || method === "reduce" || method === "reduceRight")
506
+ return 2;
507
+ return scope === "evaluator" && (method === "map" || method === "filter") ? 2 : 1;
508
+ }
509
+ function unboundCallbackParamRead(method, arrow, scope = "template") {
510
+ const extra = arrow.params.slice(evaluatorBoundParamCount(method, scope));
511
+ if (extra.length === 0)
512
+ return null;
513
+ const free = freeIdentifiers(arrow.body);
514
+ if (free === null)
515
+ return extra[0];
516
+ return extra.find((name) => free.has(name)) ?? null;
517
+ }
518
+ function unboundCallbackParamReason(method, name) {
519
+ return `'.${method}()' callback reads '${name}', its index or array parameter, which a template evaluator does not bind. Pre-compute the value, or add /* @client */ for client-only (no SSR).`;
520
+ }
504
521
  function asCallbackMethodCall(expr) {
505
522
  if (expr.kind !== "call")
506
523
  return null;
@@ -545,134 +562,20 @@ function convertNode(node, raw) {
545
562
  if (ts2.isCallExpression(node)) {
546
563
  const callee = convertNode(node.expression, raw);
547
564
  const args = node.arguments.map((arg) => convertNode(arg, raw));
548
- if (callee.kind === "member" && !callee.computed && callee.property === "filter" && args.length === 1 && args[0].kind === "identifier" && args[0].name === "Boolean") {
565
+ if (callee.kind === "member" && callee.optional) {
549
566
  return {
550
- kind: "call",
551
- callee,
552
- args: [{ kind: "arrow", params: ["_"], body: { kind: "identifier", name: "_" } }]
567
+ kind: "conditional",
568
+ test: {
569
+ kind: "logical",
570
+ op: "||",
571
+ left: { kind: "binary", op: "===", left: callee.object, right: { kind: "literal", value: null, literalType: "null" } },
572
+ right: { kind: "binary", op: "===", left: callee.object, right: { kind: "identifier", name: "undefined" } }
573
+ },
574
+ consequent: { kind: "identifier", name: "undefined" },
575
+ alternate: convertCallExpression(node, raw, { ...callee, optional: false }, args)
553
576
  };
554
577
  }
555
- if (callee.kind === "member" && !callee.computed) {
556
- if (callee.property === "join") {
557
- return { kind: "array-method", method: "join", object: callee.object, args };
558
- }
559
- if (callee.property === "includes" && args.length === 1) {
560
- return { kind: "array-method", method: "includes", object: callee.object, args };
561
- }
562
- if ((callee.property === "indexOf" || callee.property === "lastIndexOf") && args.length === 1) {
563
- return { kind: "array-method", method: callee.property, object: callee.object, args };
564
- }
565
- if (callee.property === "at") {
566
- return { kind: "array-method", method: "at", object: callee.object, args };
567
- }
568
- if (callee.property === "concat" && args.length <= 1) {
569
- return { kind: "array-method", method: "concat", object: callee.object, args };
570
- }
571
- if (callee.property === "slice") {
572
- return { kind: "array-method", method: "slice", object: callee.object, args };
573
- }
574
- if (callee.property === "reverse" || callee.property === "toReversed") {
575
- return { kind: "array-method", method: callee.property, object: callee.object, args };
576
- }
577
- if (callee.property === "flat") {
578
- const depthNode = node.arguments[0];
579
- let flatDepth;
580
- let depthExpr;
581
- if (depthNode === undefined) {
582
- flatDepth = 1;
583
- } else if (ts2.isIdentifier(depthNode) && depthNode.text === "Infinity") {
584
- flatDepth = "infinity";
585
- } else {
586
- let n;
587
- if (ts2.isNumericLiteral(depthNode)) {
588
- n = Number(depthNode.text);
589
- } else if (ts2.isPrefixUnaryExpression(depthNode) && depthNode.operator === ts2.SyntaxKind.MinusToken && ts2.isNumericLiteral(depthNode.operand)) {
590
- n = -Number(depthNode.operand.text);
591
- }
592
- if (n === undefined || Number.isNaN(n)) {
593
- const parsedDepth = convertNode(depthNode, raw);
594
- if (checkSupport(parsedDepth, "rendered", []).supported) {
595
- depthExpr = parsedDepth;
596
- flatDepth = 1;
597
- } else {
598
- return {
599
- kind: "unsupported",
600
- raw,
601
- reason: `\`.flat(depth)\` needs a literal integer, \`Infinity\`, or a supported dynamic depth expression — this depth can't be resolved. Use a literal depth, a supported expression (prop/signal/arithmetic), or pre-compute the value before the template.`
602
- };
603
- }
604
- } else {
605
- const truncated = Math.trunc(n);
606
- flatDepth = truncated < 0 ? 0 : truncated;
607
- }
608
- }
609
- return depthExpr !== undefined ? { kind: "array-method", method: "flat", object: callee.object, args: [], flatDepth, depthExpr } : { kind: "array-method", method: "flat", object: callee.object, args: [], flatDepth };
610
- }
611
- if (callee.property === "toLowerCase") {
612
- return { kind: "array-method", method: "toLowerCase", object: callee.object, args };
613
- }
614
- if (callee.property === "toUpperCase") {
615
- return { kind: "array-method", method: "toUpperCase", object: callee.object, args };
616
- }
617
- if (callee.property === "trim") {
618
- return { kind: "array-method", method: "trim", object: callee.object, args };
619
- }
620
- if (callee.property === "trimStart" || callee.property === "trimEnd") {
621
- return { kind: "array-method", method: callee.property, object: callee.object, args };
622
- }
623
- if (callee.property === "toFixed") {
624
- return { kind: "array-method", method: "toFixed", object: callee.object, args };
625
- }
626
- if (callee.property === "split") {
627
- return { kind: "array-method", method: "split", object: callee.object, args };
628
- }
629
- if (LOWERED_ARRAY_METHODS.has(callee.property)) {
630
- const argName = callee.property === "concat" ? "other" : "x";
631
- const detail = callee.property === "concat" ? "the variadic `.concat(a, b, …)` form" : `\`.${callee.property}(…)\` with ${args.length} argument(s)`;
632
- return {
633
- kind: "unsupported",
634
- raw,
635
- reason: `${detail} is not yet lowered to the Go/Mojo template adapters. Use the single-argument \`.${callee.property}(${argName})\` form, or pre-compute the value before the template.`
636
- };
637
- }
638
- if (callee.property === "startsWith" || callee.property === "endsWith") {
639
- if (args.length === 0) {
640
- return {
641
- kind: "unsupported",
642
- raw,
643
- reason: `\`.${callee.property}()\` with no search string is not lowered — JS coerces the missing argument to the string "undefined", a degenerate result. Pass an explicit search string, or pre-compute the value before the template.`
644
- };
645
- }
646
- return { kind: "array-method", method: callee.property, object: callee.object, args };
647
- }
648
- if (callee.property === "replace" || callee.property === "replaceAll") {
649
- const method = callee.property;
650
- if (args.length < 2) {
651
- return {
652
- kind: "unsupported",
653
- raw,
654
- reason: `\`.${method}(${args.length === 0 ? "" : "pattern"})\` needs both a pattern and a replacement — JS coerces the missing argument to the string "undefined", a degenerate result. Pass both arguments, or pre-compute the value before the template.`
655
- };
656
- }
657
- const patternNode = node.arguments[0];
658
- if (patternNode && ts2.isRegularExpressionLiteral(patternNode)) {
659
- return { kind: "array-method", method, object: callee.object, args };
660
- }
661
- const badArg = args[0].kind === "unsupported" || args[0].kind === "object-literal" ? args[0] : args[1].kind === "unsupported" || args[1].kind === "object-literal" ? args[1] : undefined;
662
- if (badArg) {
663
- const reason = badArg.kind === "unsupported" ? badArg.reason : "Unsupported syntax: ObjectLiteralExpression";
664
- return { kind: "unsupported", raw, reason };
665
- }
666
- return { kind: "array-method", method, object: callee.object, args };
667
- }
668
- if (callee.property === "repeat") {
669
- return { kind: "array-method", method: "repeat", object: callee.object, args };
670
- }
671
- if (callee.property === "padStart" || callee.property === "padEnd") {
672
- return { kind: "array-method", method: callee.property, object: callee.object, args };
673
- }
674
- }
675
- return { kind: "call", callee, args };
578
+ return convertCallExpression(node, raw, callee, args);
676
579
  }
677
580
  if (ts2.isArrayLiteralExpression(node)) {
678
581
  const elements = node.elements.map((el) => convertNode(el, raw));
@@ -1375,7 +1278,35 @@ function isSupported(expr, opts) {
1375
1278
  function isSupportedValue(expr, opts) {
1376
1279
  return checkSupport(expr, "value", opts?.loweringMatchers ?? []);
1377
1280
  }
1378
- function checkSupport(expr, pos, matchers) {
1281
+ function checkCallbackMethodSupport(cb, pos, matchers, scope) {
1282
+ const objSupport = checkSupport(cb.object, pos, matchers, scope);
1283
+ if (!objSupport.supported)
1284
+ return objSupport;
1285
+ const unbound = unboundCallbackParamRead(cb.method, cb.arrow, scope);
1286
+ if (unbound !== null) {
1287
+ return {
1288
+ supported: false,
1289
+ level: "L5_UNSUPPORTED",
1290
+ selfContained: true,
1291
+ reason: unboundCallbackParamReason(cb.method, unbound)
1292
+ };
1293
+ }
1294
+ const bodySupport = checkSupport(cb.arrow.body, pos, matchers, "evaluator");
1295
+ if (!bodySupport.supported) {
1296
+ return {
1297
+ supported: false,
1298
+ level: "L5_UNSUPPORTED",
1299
+ reason: `Higher-order method '.${cb.method}()' with complex callback. ${bodySupport.reason || "Simplify the callback."}`
1300
+ };
1301
+ }
1302
+ for (const rest of cb.args) {
1303
+ const restSupport = checkSupport(rest, pos, matchers, scope);
1304
+ if (!restSupport.supported)
1305
+ return restSupport;
1306
+ }
1307
+ return { supported: true, level: "L5" };
1308
+ }
1309
+ function checkSupport(expr, pos, matchers, scope = "template") {
1379
1310
  switch (expr.kind) {
1380
1311
  case "unsupported":
1381
1312
  return { supported: false, reason: expr.reason };
@@ -1384,7 +1315,7 @@ function checkSupport(expr, pos, matchers) {
1384
1315
  return { supported: false, reason: "Unsupported syntax: ObjectLiteralExpression" };
1385
1316
  }
1386
1317
  for (const prop of expr.properties) {
1387
- const propSupport = checkSupport(prop.kind === "spread" ? prop.expr : prop.value, pos, matchers);
1318
+ const propSupport = checkSupport(prop.kind === "spread" ? prop.expr : prop.value, pos, matchers, scope);
1388
1319
  if (!propSupport.supported)
1389
1320
  return propSupport;
1390
1321
  }
@@ -1399,7 +1330,7 @@ function checkSupport(expr, pos, matchers) {
1399
1330
  return { supported: false, reason: "Standalone arrow functions / regex literals are not supported" };
1400
1331
  case "array-literal": {
1401
1332
  for (const el of expr.elements) {
1402
- const elSupport = checkSupport(el, pos, matchers);
1333
+ const elSupport = checkSupport(el, pos, matchers, scope);
1403
1334
  if (!elSupport.supported)
1404
1335
  return elSupport;
1405
1336
  }
@@ -1412,16 +1343,16 @@ function checkSupport(expr, pos, matchers) {
1412
1343
  reason: `String.prototype.${expr.method} supports only a string pattern + string replacement (the regex form is deferred); use a string pattern or wrap the expression in /* @client */`
1413
1344
  };
1414
1345
  }
1415
- const objSupport = checkSupport(expr.object, pos, matchers);
1346
+ const objSupport = checkSupport(expr.object, pos, matchers, scope);
1416
1347
  if (!objSupport.supported)
1417
1348
  return objSupport;
1418
1349
  for (const arg of expr.args) {
1419
- const argSupport = checkSupport(arg, pos, matchers);
1350
+ const argSupport = checkSupport(arg, pos, matchers, scope);
1420
1351
  if (!argSupport.supported)
1421
1352
  return argSupport;
1422
1353
  }
1423
1354
  if (expr.method === "flat" && expr.depthExpr) {
1424
- const depthSupport = checkSupport(expr.depthExpr, pos, matchers);
1355
+ const depthSupport = checkSupport(expr.depthExpr, pos, matchers, scope);
1425
1356
  if (!depthSupport.supported)
1426
1357
  return depthSupport;
1427
1358
  }
@@ -1433,33 +1364,16 @@ function checkSupport(expr, pos, matchers) {
1433
1364
  if (!node)
1434
1365
  continue;
1435
1366
  for (const child of loweringNodeChildren(node)) {
1436
- const childSupport = checkSupport(child, pos, matchers);
1367
+ const childSupport = checkSupport(child, pos, matchers, scope);
1437
1368
  if (!childSupport.supported)
1438
1369
  return childSupport;
1439
1370
  }
1440
1371
  return { supported: true, level: "L2" };
1441
1372
  }
1442
1373
  const cb = asCallbackMethodCall(expr);
1443
- if (cb) {
1444
- const objSupport = checkSupport(cb.object, pos, matchers);
1445
- if (!objSupport.supported)
1446
- return objSupport;
1447
- const bodySupport = checkSupport(cb.arrow.body, pos, matchers);
1448
- if (!bodySupport.supported) {
1449
- return {
1450
- supported: false,
1451
- level: "L5_UNSUPPORTED",
1452
- reason: `Higher-order method '.${cb.method}()' with complex callback. ${bodySupport.reason || "Simplify the callback."}`
1453
- };
1454
- }
1455
- for (const rest of cb.args) {
1456
- const restSupport = checkSupport(rest, pos, matchers);
1457
- if (!restSupport.supported)
1458
- return restSupport;
1459
- }
1460
- return { supported: true, level: "L5" };
1461
- }
1462
- const calleeSupport = checkSupport(expr.callee, pos, matchers);
1374
+ if (cb)
1375
+ return checkCallbackMethodSupport(cb, pos, matchers, scope);
1376
+ const calleeSupport = checkSupport(expr.callee, pos, matchers, scope);
1463
1377
  if (!calleeSupport.supported) {
1464
1378
  return calleeSupport;
1465
1379
  }
@@ -1478,7 +1392,7 @@ function checkSupport(expr, pos, matchers) {
1478
1392
  return { supported: true, level: "L1" };
1479
1393
  }
1480
1394
  for (const arg of expr.args) {
1481
- const argSupport = checkSupport(arg, pos, matchers);
1395
+ const argSupport = checkSupport(arg, pos, matchers, scope);
1482
1396
  if (!argSupport.supported) {
1483
1397
  return argSupport;
1484
1398
  }
@@ -1486,7 +1400,7 @@ function checkSupport(expr, pos, matchers) {
1486
1400
  return { supported: true, level: "L2" };
1487
1401
  }
1488
1402
  case "member": {
1489
- const objSupport = checkSupport(expr.object, pos, matchers);
1403
+ const objSupport = checkSupport(expr.object, pos, matchers, scope);
1490
1404
  if (!objSupport.supported) {
1491
1405
  return objSupport;
1492
1406
  }
@@ -1496,19 +1410,19 @@ function checkSupport(expr, pos, matchers) {
1496
1410
  return { supported: true, level: "L2" };
1497
1411
  }
1498
1412
  case "index-access": {
1499
- const objSupport = checkSupport(expr.object, pos, matchers);
1413
+ const objSupport = checkSupport(expr.object, pos, matchers, scope);
1500
1414
  if (!objSupport.supported)
1501
1415
  return objSupport;
1502
- const indexSupport = checkSupport(expr.index, pos, matchers);
1416
+ const indexSupport = checkSupport(expr.index, pos, matchers, scope);
1503
1417
  if (!indexSupport.supported)
1504
1418
  return indexSupport;
1505
1419
  return { supported: true, level: "L2" };
1506
1420
  }
1507
1421
  case "binary": {
1508
- const leftSupport = checkSupport(expr.left, pos, matchers);
1422
+ const leftSupport = checkSupport(expr.left, pos, matchers, scope);
1509
1423
  if (!leftSupport.supported)
1510
1424
  return leftSupport;
1511
- const rightSupport = checkSupport(expr.right, pos, matchers);
1425
+ const rightSupport = checkSupport(expr.right, pos, matchers, scope);
1512
1426
  if (!rightSupport.supported)
1513
1427
  return rightSupport;
1514
1428
  if (["===", "==", "!==", "!=", ">", "<", ">=", "<="].includes(expr.op)) {
@@ -1520,7 +1434,7 @@ function checkSupport(expr, pos, matchers) {
1520
1434
  return { supported: false, reason: `Unknown operator: ${expr.op}` };
1521
1435
  }
1522
1436
  case "unary": {
1523
- const argSupport = checkSupport(expr.argument, pos, matchers);
1437
+ const argSupport = checkSupport(expr.argument, pos, matchers, scope);
1524
1438
  if (!argSupport.supported)
1525
1439
  return argSupport;
1526
1440
  if (expr.op === "!") {
@@ -1532,25 +1446,25 @@ function checkSupport(expr, pos, matchers) {
1532
1446
  return { supported: false, reason: `Unsupported unary operator: ${expr.op}` };
1533
1447
  }
1534
1448
  case "logical": {
1535
- const leftSupport = checkSupport(expr.left, pos, matchers);
1449
+ const leftSupport = checkSupport(expr.left, pos, matchers, scope);
1536
1450
  if (!leftSupport.supported)
1537
1451
  return leftSupport;
1538
1452
  if (expr.op === "??" && expr.right.kind === "object-literal" && expr.right.properties.length === 0) {
1539
1453
  return { supported: true, level: "L4" };
1540
1454
  }
1541
- const rightSupport = checkSupport(expr.right, pos, matchers);
1455
+ const rightSupport = checkSupport(expr.right, pos, matchers, scope);
1542
1456
  if (!rightSupport.supported)
1543
1457
  return rightSupport;
1544
1458
  return { supported: true, level: "L4" };
1545
1459
  }
1546
1460
  case "conditional": {
1547
- const testSupport = checkSupport(expr.test, pos, matchers);
1461
+ const testSupport = checkSupport(expr.test, pos, matchers, scope);
1548
1462
  if (!testSupport.supported)
1549
1463
  return testSupport;
1550
- const consSupport = checkSupport(expr.consequent, pos, matchers);
1464
+ const consSupport = checkSupport(expr.consequent, pos, matchers, scope);
1551
1465
  if (!consSupport.supported)
1552
1466
  return consSupport;
1553
- const altSupport = checkSupport(expr.alternate, pos, matchers);
1467
+ const altSupport = checkSupport(expr.alternate, pos, matchers, scope);
1554
1468
  if (!altSupport.supported)
1555
1469
  return altSupport;
1556
1470
  return { supported: true, level: "L4" };
@@ -1558,7 +1472,7 @@ function checkSupport(expr, pos, matchers) {
1558
1472
  case "template-literal": {
1559
1473
  for (const part of expr.parts) {
1560
1474
  if (part.type === "expression") {
1561
- const partSupport = checkSupport(part.expr, pos, matchers);
1475
+ const partSupport = checkSupport(part.expr, pos, matchers, scope);
1562
1476
  if (!partSupport.supported)
1563
1477
  return partSupport;
1564
1478
  }
@@ -2271,6 +2185,58 @@ function evalBuiltinCalleeName(callee) {
2271
2185
  }
2272
2186
  return null;
2273
2187
  }
2188
+ function hasOpaqueCall(expr) {
2189
+ let found = false;
2190
+ const visit = (node) => {
2191
+ if (found || node === null || typeof node !== "object")
2192
+ return;
2193
+ if (Array.isArray(node)) {
2194
+ node.forEach(visit);
2195
+ return;
2196
+ }
2197
+ const e = node;
2198
+ if (e.kind === "call") {
2199
+ const cb = asCallbackMethodCall(e);
2200
+ if (cb) {
2201
+ visit(cb.object);
2202
+ visit(cb.arrow.body);
2203
+ cb.args.forEach(visit);
2204
+ return;
2205
+ }
2206
+ const getter = e.callee.kind === "identifier" && e.args.length === 0;
2207
+ if (!getter && evalBuiltinCalleeName(e.callee) === null) {
2208
+ found = true;
2209
+ return;
2210
+ }
2211
+ e.args.forEach(visit);
2212
+ return;
2213
+ }
2214
+ for (const value of Object.values(e))
2215
+ visit(value);
2216
+ };
2217
+ visit(expr);
2218
+ return found;
2219
+ }
2220
+ function readsNestedCallbackIndex(expr) {
2221
+ let found = false;
2222
+ const visit = (node) => {
2223
+ if (found || node === null || typeof node !== "object")
2224
+ return;
2225
+ if (Array.isArray(node)) {
2226
+ node.forEach(visit);
2227
+ return;
2228
+ }
2229
+ const cb = node.kind === "call" ? asCallbackMethodCall(node) : null;
2230
+ if (cb && unboundCallbackParamRead(cb.method, cb.arrow) !== null) {
2231
+ found = true;
2232
+ return;
2233
+ }
2234
+ for (const value of Object.values(node))
2235
+ visit(value);
2236
+ };
2237
+ visit(expr);
2238
+ return found;
2239
+ }
2274
2240
  function toEvalNode(e) {
2275
2241
  switch (e.kind) {
2276
2242
  case "literal":
@@ -2417,6 +2383,136 @@ function identifierPath(callee) {
2417
2383
  }
2418
2384
  return null;
2419
2385
  }
2386
+ function convertCallExpression(node, raw, callee, args) {
2387
+ if (callee.kind === "member" && !callee.computed && callee.property === "filter" && args.length === 1 && args[0].kind === "identifier" && args[0].name === "Boolean") {
2388
+ return {
2389
+ kind: "call",
2390
+ callee,
2391
+ args: [{ kind: "arrow", params: ["_"], body: { kind: "identifier", name: "_" } }]
2392
+ };
2393
+ }
2394
+ if (callee.kind === "member" && !callee.computed) {
2395
+ if (callee.property === "join") {
2396
+ return { kind: "array-method", method: "join", object: callee.object, args };
2397
+ }
2398
+ if (callee.property === "includes" && args.length === 1) {
2399
+ return { kind: "array-method", method: "includes", object: callee.object, args };
2400
+ }
2401
+ if ((callee.property === "indexOf" || callee.property === "lastIndexOf") && args.length === 1) {
2402
+ return { kind: "array-method", method: callee.property, object: callee.object, args };
2403
+ }
2404
+ if (callee.property === "at") {
2405
+ return { kind: "array-method", method: "at", object: callee.object, args };
2406
+ }
2407
+ if (callee.property === "concat" && args.length <= 1) {
2408
+ return { kind: "array-method", method: "concat", object: callee.object, args };
2409
+ }
2410
+ if (callee.property === "slice") {
2411
+ return { kind: "array-method", method: "slice", object: callee.object, args };
2412
+ }
2413
+ if (callee.property === "reverse" || callee.property === "toReversed") {
2414
+ return { kind: "array-method", method: callee.property, object: callee.object, args };
2415
+ }
2416
+ if (callee.property === "flat") {
2417
+ const depthNode = node.arguments[0];
2418
+ let flatDepth;
2419
+ let depthExpr;
2420
+ if (depthNode === undefined) {
2421
+ flatDepth = 1;
2422
+ } else if (ts2.isIdentifier(depthNode) && depthNode.text === "Infinity") {
2423
+ flatDepth = "infinity";
2424
+ } else {
2425
+ let n;
2426
+ if (ts2.isNumericLiteral(depthNode)) {
2427
+ n = Number(depthNode.text);
2428
+ } else if (ts2.isPrefixUnaryExpression(depthNode) && depthNode.operator === ts2.SyntaxKind.MinusToken && ts2.isNumericLiteral(depthNode.operand)) {
2429
+ n = -Number(depthNode.operand.text);
2430
+ }
2431
+ if (n === undefined || Number.isNaN(n)) {
2432
+ const parsedDepth = convertNode(depthNode, raw);
2433
+ if (checkSupport(parsedDepth, "rendered", []).supported) {
2434
+ depthExpr = parsedDepth;
2435
+ flatDepth = 1;
2436
+ } else {
2437
+ return {
2438
+ kind: "unsupported",
2439
+ raw,
2440
+ reason: `\`.flat(depth)\` needs a literal integer, \`Infinity\`, or a supported dynamic depth expression — this depth can't be resolved. Use a literal depth, a supported expression (prop/signal/arithmetic), or pre-compute the value before the template.`
2441
+ };
2442
+ }
2443
+ } else {
2444
+ const truncated = Math.trunc(n);
2445
+ flatDepth = truncated < 0 ? 0 : truncated;
2446
+ }
2447
+ }
2448
+ return depthExpr !== undefined ? { kind: "array-method", method: "flat", object: callee.object, args: [], flatDepth, depthExpr } : { kind: "array-method", method: "flat", object: callee.object, args: [], flatDepth };
2449
+ }
2450
+ if (callee.property === "toLowerCase") {
2451
+ return { kind: "array-method", method: "toLowerCase", object: callee.object, args };
2452
+ }
2453
+ if (callee.property === "toUpperCase") {
2454
+ return { kind: "array-method", method: "toUpperCase", object: callee.object, args };
2455
+ }
2456
+ if (callee.property === "trim") {
2457
+ return { kind: "array-method", method: "trim", object: callee.object, args };
2458
+ }
2459
+ if (callee.property === "trimStart" || callee.property === "trimEnd") {
2460
+ return { kind: "array-method", method: callee.property, object: callee.object, args };
2461
+ }
2462
+ if (callee.property === "toFixed") {
2463
+ return { kind: "array-method", method: "toFixed", object: callee.object, args };
2464
+ }
2465
+ if (callee.property === "split") {
2466
+ return { kind: "array-method", method: "split", object: callee.object, args };
2467
+ }
2468
+ if (LOWERED_ARRAY_METHODS.has(callee.property)) {
2469
+ const argName = callee.property === "concat" ? "other" : "x";
2470
+ const detail = callee.property === "concat" ? "the variadic `.concat(a, b, …)` form" : `\`.${callee.property}(…)\` with ${args.length} argument(s)`;
2471
+ return {
2472
+ kind: "unsupported",
2473
+ raw,
2474
+ reason: `${detail} is not yet lowered to the Go/Mojo template adapters. Use the single-argument \`.${callee.property}(${argName})\` form, or pre-compute the value before the template.`
2475
+ };
2476
+ }
2477
+ if (callee.property === "startsWith" || callee.property === "endsWith") {
2478
+ if (args.length === 0) {
2479
+ return {
2480
+ kind: "unsupported",
2481
+ raw,
2482
+ reason: `\`.${callee.property}()\` with no search string is not lowered — JS coerces the missing argument to the string "undefined", a degenerate result. Pass an explicit search string, or pre-compute the value before the template.`
2483
+ };
2484
+ }
2485
+ return { kind: "array-method", method: callee.property, object: callee.object, args };
2486
+ }
2487
+ if (callee.property === "replace" || callee.property === "replaceAll") {
2488
+ const method = callee.property;
2489
+ if (args.length < 2) {
2490
+ return {
2491
+ kind: "unsupported",
2492
+ raw,
2493
+ reason: `\`.${method}(${args.length === 0 ? "" : "pattern"})\` needs both a pattern and a replacement — JS coerces the missing argument to the string "undefined", a degenerate result. Pass both arguments, or pre-compute the value before the template.`
2494
+ };
2495
+ }
2496
+ const patternNode = node.arguments[0];
2497
+ if (patternNode && ts2.isRegularExpressionLiteral(patternNode)) {
2498
+ return { kind: "array-method", method, object: callee.object, args };
2499
+ }
2500
+ const badArg = args[0].kind === "unsupported" || args[0].kind === "object-literal" ? args[0] : args[1].kind === "unsupported" || args[1].kind === "object-literal" ? args[1] : undefined;
2501
+ if (badArg) {
2502
+ const reason = badArg.kind === "unsupported" ? badArg.reason : "Unsupported syntax: ObjectLiteralExpression";
2503
+ return { kind: "unsupported", raw, reason };
2504
+ }
2505
+ return { kind: "array-method", method, object: callee.object, args };
2506
+ }
2507
+ if (callee.property === "repeat") {
2508
+ return { kind: "array-method", method: "repeat", object: callee.object, args };
2509
+ }
2510
+ if (callee.property === "padStart" || callee.property === "padEnd") {
2511
+ return { kind: "array-method", method: callee.property, object: callee.object, args };
2512
+ }
2513
+ }
2514
+ return { kind: "call", callee, args };
2515
+ }
2420
2516
 
2421
2517
  // src/prop-rewrite.ts
2422
2518
  import ts11 from "typescript";
@@ -14249,6 +14345,9 @@ function extractFilterPredicate(callback, ctx) {
14249
14345
  if (!support2.supported) {
14250
14346
  return { result: null, unsupportedReason: support2.reason };
14251
14347
  }
14348
+ const unbound2 = unboundFilterParamReason(callback, predicate2, ctx);
14349
+ if (unbound2)
14350
+ return { result: null, unsupportedReason: unbound2 };
14252
14351
  return { result: { param, predicate: predicate2, raw: raw2 } };
14253
14352
  }
14254
14353
  const raw = ctx.getJS(callback.body);
@@ -14257,8 +14356,16 @@ function extractFilterPredicate(callback, ctx) {
14257
14356
  if (!support.supported) {
14258
14357
  return { result: null, unsupportedReason: support.reason };
14259
14358
  }
14359
+ const unbound = unboundFilterParamReason(callback, predicate, ctx);
14360
+ if (unbound)
14361
+ return { result: null, unsupportedReason: unbound };
14260
14362
  return { result: { param, predicate, raw } };
14261
14363
  }
14364
+ function unboundFilterParamReason(callback, predicate, ctx) {
14365
+ const params = callback.parameters.map((p) => p.name.getText(ctx.sourceFile));
14366
+ const unbound = unboundCallbackParamRead("filter", { kind: "arrow", params, body: predicate });
14367
+ return unbound === null ? undefined : unboundCallbackParamReason("filter", unbound);
14368
+ }
14262
14369
  function extractLoopParamBindings(pattern) {
14263
14370
  if (ts19.isIdentifier(pattern))
14264
14371
  return null;
@@ -14756,469 +14863,544 @@ function extractItemConditionalKey(cond) {
14756
14863
  }
14757
14864
  return a ?? b;
14758
14865
  }
14759
- function transformMapCall(node, ctx, isClientOnly = false, method = "map") {
14760
- const isNested = ctx.scope.valueBoundNames().size > 0;
14761
- const diagCountAtEntry = ctx.analyzer.errors.length;
14762
- const depth = ctx.loopDepth;
14763
- const propAccess = node.expression;
14764
- const mapSource = propAccess.expression;
14765
- let array = "";
14766
- let templateArray;
14767
- let arrayExpr = mapSource;
14768
- let filterPredicate;
14769
- let sortComparator;
14770
- let chainOrder;
14771
- let preamble;
14772
- let iterationShape;
14773
- let objectIteration;
14774
- const setArray = (node2) => {
14775
- array = ctx.getJS(node2);
14776
- templateArray = rewriteBarePropRefs2(array, node2, ctx);
14777
- arrayExpr = node2;
14778
- };
14779
- let chainSource = mapSource;
14866
+ var CLIENT_ONLY_EXPRESSION_SUGGESTION = "Add /* @client */ to evaluate this expression on the client only";
14867
+ var CLIENT_ONLY_LOOP_SUGGESTION = "Add /* @client */ to render this loop on the client only";
14868
+ function stripIteratorWrapper(mapSource) {
14780
14869
  const iteratorInfo = isIteratorShapeCall(mapSource);
14781
14870
  if (iteratorInfo) {
14782
- chainSource = iteratorInfo.array;
14783
- if (iteratorInfo.shape === "entries") {
14784
- iterationShape = "entries";
14785
- } else if (iteratorInfo.shape === "keys") {
14786
- iterationShape = "keys";
14787
- }
14788
- } else {
14789
- const objectIteratorInfo = isObjectIteratorCall(mapSource);
14790
- if (objectIteratorInfo) {
14791
- chainSource = objectIteratorInfo.object;
14792
- objectIteration = objectIteratorInfo.shape;
14871
+ const iterationShape = iteratorInfo.shape === "entries" ? "entries" : iteratorInfo.shape === "keys" ? "keys" : undefined;
14872
+ return { chainSource: iteratorInfo.array, iterationShape, objectIteration: undefined };
14873
+ }
14874
+ const objectIteratorInfo = isObjectIteratorCall(mapSource);
14875
+ if (objectIteratorInfo) {
14876
+ return {
14877
+ chainSource: objectIteratorInfo.object,
14878
+ iterationShape: undefined,
14879
+ objectIteration: objectIteratorInfo.shape
14880
+ };
14881
+ }
14882
+ return { chainSource: mapSource, iterationShape: undefined, objectIteration: undefined };
14883
+ }
14884
+ function refuseOffSubsetCallback(kind, callback, unsupportedReason, ctx, isClientOnly) {
14885
+ if (isClientOnly || !unsupportedReason)
14886
+ return;
14887
+ if (ctx.analyzer.acceptsCallbackBody?.(kind) ?? false)
14888
+ return;
14889
+ ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(callback, ctx.sourceFile, ctx.filePath), {
14890
+ message: `Expression cannot be compiled to marked template: ${unsupportedReason}`,
14891
+ suggestion: {
14892
+ message: CLIENT_ONLY_EXPRESSION_SUGGESTION
14793
14893
  }
14894
+ }));
14895
+ }
14896
+ function resolveSortOuterChain(sortInfo, mapSource, plan, setArray, ctx, isClientOnly) {
14897
+ const innerFilter = isFilterCall(sortInfo.array);
14898
+ const sortExtraction = extractSortComparator(sortInfo.callback, sortInfo.method, ctx);
14899
+ if (isClientOnly || !sortExtraction.result) {
14900
+ refuseOffSubsetCallback("sort", sortInfo.callback, sortExtraction.unsupportedReason, ctx, isClientOnly);
14901
+ setArray(mapSource);
14902
+ return;
14903
+ }
14904
+ plan.sortComparator = sortExtraction.result;
14905
+ if (!innerFilter) {
14906
+ setArray(sortInfo.array);
14907
+ return;
14908
+ }
14909
+ plan.chainOrder = "filter-sort";
14910
+ const filterExtraction = extractFilterPredicate(innerFilter.callback, ctx);
14911
+ if (isClientOnly || !filterExtraction.result) {
14912
+ refuseOffSubsetCallback("filter", innerFilter.callback, filterExtraction.unsupportedReason, ctx, isClientOnly);
14913
+ setArray(mapSource);
14914
+ plan.sortComparator = undefined;
14915
+ plan.chainOrder = undefined;
14916
+ return;
14917
+ }
14918
+ setArray(innerFilter.array);
14919
+ plan.filterPredicate = filterExtraction.result;
14920
+ }
14921
+ function resolveFilterOuterChain(filterInfo, mapSource, plan, setArray, ctx, isClientOnly) {
14922
+ const innerSort = isSortCall(filterInfo.array);
14923
+ const filterExtraction = extractFilterPredicate(filterInfo.callback, ctx);
14924
+ if (isClientOnly || !filterExtraction.result) {
14925
+ refuseOffSubsetCallback("filter", filterInfo.callback, filterExtraction.unsupportedReason, ctx, isClientOnly);
14926
+ setArray(mapSource);
14927
+ return;
14928
+ }
14929
+ plan.filterPredicate = filterExtraction.result;
14930
+ if (!innerSort) {
14931
+ setArray(filterInfo.array);
14932
+ return;
14933
+ }
14934
+ plan.chainOrder = "sort-filter";
14935
+ const sortExtraction = extractSortComparator(innerSort.callback, innerSort.method, ctx);
14936
+ if (isClientOnly || !sortExtraction.result) {
14937
+ refuseOffSubsetCallback("sort", innerSort.callback, sortExtraction.unsupportedReason, ctx, isClientOnly);
14938
+ setArray(filterInfo.array);
14939
+ return;
14794
14940
  }
14795
- const filterInfo = isFilterCall(chainSource);
14796
- const sortInfo = isSortCall(chainSource);
14941
+ plan.sortComparator = sortExtraction.result;
14942
+ setArray(innerSort.array);
14943
+ }
14944
+ function resolveLoopSource(node, ctx, isClientOnly) {
14945
+ const propAccess = node.expression;
14946
+ const mapSource = propAccess.expression;
14947
+ const iteration = stripIteratorWrapper(mapSource);
14948
+ const plan = {
14949
+ array: "",
14950
+ templateArray: undefined,
14951
+ arrayExpr: mapSource,
14952
+ filterPredicate: undefined,
14953
+ sortComparator: undefined,
14954
+ chainOrder: undefined,
14955
+ iterationShape: iteration.iterationShape,
14956
+ objectIteration: iteration.objectIteration
14957
+ };
14958
+ const setArray = (expr) => {
14959
+ plan.array = ctx.getJS(expr);
14960
+ plan.templateArray = rewriteBarePropRefs2(plan.array, expr, ctx);
14961
+ plan.arrayExpr = expr;
14962
+ };
14963
+ const filterInfo = isFilterCall(iteration.chainSource);
14964
+ const sortInfo = isSortCall(iteration.chainSource);
14797
14965
  if (sortInfo) {
14798
- const innerFilter = isFilterCall(sortInfo.array);
14799
- const sortExtraction = extractSortComparator(sortInfo.callback, sortInfo.method, ctx);
14800
- if (isClientOnly || !sortExtraction.result) {
14801
- if (!isClientOnly && sortExtraction.unsupportedReason && !(ctx.analyzer.acceptsCallbackBody?.("sort") ?? false)) {
14802
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(sortInfo.callback, ctx.sourceFile, ctx.filePath), {
14803
- message: `Expression cannot be compiled to marked template: ${sortExtraction.unsupportedReason}`,
14804
- suggestion: {
14805
- message: "Add /* @client */ to evaluate this expression on the client only"
14806
- }
14807
- }));
14808
- }
14809
- setArray(mapSource);
14810
- } else {
14811
- sortComparator = sortExtraction.result;
14812
- if (innerFilter) {
14813
- chainOrder = "filter-sort";
14814
- const filterExtraction = extractFilterPredicate(innerFilter.callback, ctx);
14815
- if (isClientOnly || !filterExtraction.result) {
14816
- if (!isClientOnly && filterExtraction.unsupportedReason && !(ctx.analyzer.acceptsCallbackBody?.("filter") ?? false)) {
14817
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(innerFilter.callback, ctx.sourceFile, ctx.filePath), {
14818
- message: `Expression cannot be compiled to marked template: ${filterExtraction.unsupportedReason}`,
14819
- suggestion: {
14820
- message: "Add /* @client */ to evaluate this expression on the client only"
14821
- }
14822
- }));
14823
- }
14824
- setArray(mapSource);
14825
- sortComparator = undefined;
14826
- chainOrder = undefined;
14827
- } else {
14828
- setArray(innerFilter.array);
14829
- filterPredicate = filterExtraction.result;
14830
- }
14831
- } else {
14832
- setArray(sortInfo.array);
14833
- }
14834
- }
14966
+ resolveSortOuterChain(sortInfo, mapSource, plan, setArray, ctx, isClientOnly);
14835
14967
  } else if (filterInfo) {
14836
- const innerSort = isSortCall(filterInfo.array);
14837
- const filterExtraction = extractFilterPredicate(filterInfo.callback, ctx);
14838
- if (isClientOnly || !filterExtraction.result) {
14839
- if (!isClientOnly && filterExtraction.unsupportedReason && !(ctx.analyzer.acceptsCallbackBody?.("filter") ?? false)) {
14840
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(filterInfo.callback, ctx.sourceFile, ctx.filePath), {
14841
- message: `Expression cannot be compiled to marked template: ${filterExtraction.unsupportedReason}`,
14842
- suggestion: {
14843
- message: "Add /* @client */ to evaluate this expression on the client only"
14844
- }
14845
- }));
14846
- }
14847
- setArray(mapSource);
14968
+ resolveFilterOuterChain(filterInfo, mapSource, plan, setArray, ctx, isClientOnly);
14969
+ } else {
14970
+ setArray(iteration.chainSource);
14971
+ }
14972
+ return plan;
14973
+ }
14974
+ function entriesTupleBindings(pattern) {
14975
+ const elements = pattern.elements.filter((el) => !ts19.isOmittedExpression(el));
14976
+ if (elements.length !== 2)
14977
+ return null;
14978
+ const [first, second] = elements;
14979
+ if (!ts19.isBindingElement(first) || !ts19.isIdentifier(first.name))
14980
+ return null;
14981
+ if (!ts19.isBindingElement(second) || !ts19.isIdentifier(second.name))
14982
+ return null;
14983
+ return { index: first.name.text, param: second.name.text, itemTypeNode: second.name };
14984
+ }
14985
+ function loopParamBindingsOrRefuse(firstParam, ctx) {
14986
+ const bindingResult = extractLoopParamBindings(firstParam.name);
14987
+ if (bindingResult && !Array.isArray(bindingResult)) {
14988
+ ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_DESTRUCTURE_REST, getSourceLocation(firstParam, ctx.sourceFile, ctx.filePath)));
14989
+ return;
14990
+ }
14991
+ return Array.isArray(bindingResult) ? bindingResult : undefined;
14992
+ }
14993
+ function resolveLoopRowParams(callback, source, ctx) {
14994
+ const row = {
14995
+ param: "item",
14996
+ paramType: undefined,
14997
+ index: null,
14998
+ indexType: undefined,
14999
+ paramBindings: undefined,
15000
+ itemTypeNode: undefined
15001
+ };
15002
+ const isEntriesShape = source.iterationShape === "entries" || source.objectIteration === "entries";
15003
+ if (callback.parameters.length > 0) {
15004
+ const firstParam = callback.parameters[0];
15005
+ row.itemTypeNode = firstParam;
15006
+ row.param = firstParam.name.getText(ctx.sourceFile);
15007
+ if (firstParam.type) {
15008
+ row.paramType = firstParam.type.getText(ctx.sourceFile);
15009
+ }
15010
+ const tuple = isEntriesShape && ts19.isArrayBindingPattern(firstParam.name) ? entriesTupleBindings(firstParam.name) : null;
15011
+ if (tuple) {
15012
+ row.index = tuple.index;
15013
+ row.param = tuple.param;
15014
+ row.itemTypeNode = tuple.itemTypeNode;
14848
15015
  } else {
14849
- filterPredicate = filterExtraction.result;
14850
- if (innerSort) {
14851
- chainOrder = "sort-filter";
14852
- const sortExtraction = extractSortComparator(innerSort.callback, innerSort.method, ctx);
14853
- if (isClientOnly || !sortExtraction.result) {
14854
- if (!isClientOnly && sortExtraction.unsupportedReason && !(ctx.analyzer.acceptsCallbackBody?.("sort") ?? false)) {
14855
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(innerSort.callback, ctx.sourceFile, ctx.filePath), {
14856
- message: `Expression cannot be compiled to marked template: ${sortExtraction.unsupportedReason}`,
14857
- suggestion: {
14858
- message: "Add /* @client */ to evaluate this expression on the client only"
14859
- }
14860
- }));
14861
- }
14862
- setArray(filterInfo.array);
14863
- } else {
14864
- sortComparator = sortExtraction.result;
14865
- setArray(innerSort.array);
14866
- }
14867
- } else {
14868
- setArray(filterInfo.array);
14869
- }
15016
+ row.paramBindings = loopParamBindingsOrRefuse(firstParam, ctx);
14870
15017
  }
14871
- } else {
14872
- setArray(chainSource);
14873
15018
  }
14874
- const callback = node.arguments[0];
14875
- let param = "item";
14876
- let paramType;
14877
- let index = null;
14878
- let indexType;
14879
- let children = [];
14880
- let paramBindings;
14881
- let flatMapCallback;
14882
- let itemTypeNode;
14883
- if (ts19.isArrowFunction(callback)) {
14884
- if (callback.parameters.length > 0) {
14885
- const firstParam = callback.parameters[0];
14886
- itemTypeNode = firstParam;
14887
- param = firstParam.name.getText(ctx.sourceFile);
14888
- if (firstParam.type) {
14889
- paramType = firstParam.type.getText(ctx.sourceFile);
14890
- }
14891
- const isEntriesShape = iterationShape === "entries" || objectIteration === "entries";
14892
- if (isEntriesShape && ts19.isArrayBindingPattern(firstParam.name)) {
14893
- const elements = firstParam.name.elements.filter((el) => !ts19.isOmittedExpression(el));
14894
- if (elements.length === 2 && ts19.isBindingElement(elements[0]) && ts19.isIdentifier(elements[0].name) && ts19.isBindingElement(elements[1]) && ts19.isIdentifier(elements[1].name)) {
14895
- index = elements[0].name.text;
14896
- param = elements[1].name.text;
14897
- itemTypeNode = elements[1].name;
14898
- } else {
14899
- const bindingResult = extractLoopParamBindings(firstParam.name);
14900
- if (bindingResult && !Array.isArray(bindingResult)) {
14901
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_DESTRUCTURE_REST, getSourceLocation(firstParam, ctx.sourceFile, ctx.filePath)));
14902
- } else if (Array.isArray(bindingResult)) {
14903
- paramBindings = bindingResult;
14904
- }
14905
- }
14906
- } else {
14907
- const bindingResult = extractLoopParamBindings(firstParam.name);
14908
- if (bindingResult && !Array.isArray(bindingResult)) {
14909
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_DESTRUCTURE_REST, getSourceLocation(firstParam, ctx.sourceFile, ctx.filePath)));
14910
- } else if (Array.isArray(bindingResult)) {
14911
- paramBindings = bindingResult;
14912
- }
14913
- }
15019
+ if (callback.parameters.length > 1 && !isEntriesShape) {
15020
+ const secondParam = callback.parameters[1];
15021
+ row.index = secondParam.name.getText(ctx.sourceFile);
15022
+ if (secondParam.type) {
15023
+ row.indexType = secondParam.type.getText(ctx.sourceFile);
14914
15024
  }
14915
- if (callback.parameters.length > 1 && iterationShape !== "entries" && objectIteration !== "entries") {
14916
- const secondParam = callback.parameters[1];
14917
- index = secondParam.name.getText(ctx.sourceFile);
14918
- if (secondParam.type) {
14919
- indexType = secondParam.type.getText(ctx.sourceFile);
14920
- }
15025
+ }
15026
+ return row;
15027
+ }
15028
+ function transformRenderableLogicalBody(expr, ctx, isClientOnly) {
15029
+ if (!ts19.isBinaryExpression(expr))
15030
+ return [];
15031
+ const op = expr.operatorToken.kind;
15032
+ if (op !== ts19.SyntaxKind.AmpersandAmpersandToken && op !== ts19.SyntaxKind.BarBarToken && op !== ts19.SyntaxKind.QuestionQuestionToken) {
15033
+ return [];
15034
+ }
15035
+ if (!containsJsxInExpression(expr) && !callsJsxHelper(expr, ctx))
15036
+ return [];
15037
+ const transformed = transformJsxExpression(expr, ctx, isClientOnly);
15038
+ return transformed ? [transformed] : [];
15039
+ }
15040
+ function transformLoopExpressionBody(body, ctx, isClientOnly, method) {
15041
+ let inner = body;
15042
+ while (ts19.isParenthesizedExpression(inner)) {
15043
+ inner = inner.expression;
15044
+ }
15045
+ if (ts19.isJsxElement(inner) || ts19.isJsxSelfClosingElement(inner) || ts19.isJsxFragment(inner)) {
15046
+ const transformed = transformNode(inner, ctx);
15047
+ return transformed ? [transformed] : [];
15048
+ }
15049
+ if (ts19.isConditionalExpression(inner)) {
15050
+ return [transformConditional(inner, ctx)];
15051
+ }
15052
+ if (method === "flatMap" && ts19.isArrayLiteralExpression(inner)) {
15053
+ return transformArrayLiteralChildren(inner, ctx);
15054
+ }
15055
+ return transformRenderableLogicalBody(inner, ctx, isClientOnly);
15056
+ }
15057
+ function refuseUndeclarablePreamble(preamble, loc, message, ctx, isClientOnly) {
15058
+ if (preamble.declarations)
15059
+ return;
15060
+ if (isClientOnly)
15061
+ return;
15062
+ if (ctx.analyzer.acceptsCallbackBody?.("map") ?? false)
15063
+ return;
15064
+ ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, loc, {
15065
+ message,
15066
+ suggestion: {
15067
+ message: CLIENT_ONLY_EXPRESSION_SUGGESTION
14921
15068
  }
14922
- const savedScope = ctx.scope;
14923
- ctx.scope = ctx.scope.enterLoopRow({ param, index, paramBindings });
14924
- ctx.loopDepth++;
14925
- const tryTransformRenderableBody = (expr) => {
14926
- if (!ts19.isBinaryExpression(expr))
14927
- return;
14928
- const op = expr.operatorToken.kind;
14929
- if (op !== ts19.SyntaxKind.AmpersandAmpersandToken && op !== ts19.SyntaxKind.BarBarToken && op !== ts19.SyntaxKind.QuestionQuestionToken) {
14930
- return;
14931
- }
14932
- if (!containsJsxInExpression(expr) && !callsJsxHelper(expr, ctx))
14933
- return;
14934
- const transformed = transformJsxExpression(expr, ctx, isClientOnly);
14935
- if (transformed)
14936
- children = [transformed];
14937
- };
14938
- const body = callback.body;
14939
- if (ts19.isJsxElement(body) || ts19.isJsxSelfClosingElement(body) || ts19.isJsxFragment(body)) {
14940
- const transformed = transformNode(body, ctx);
14941
- if (transformed) {
14942
- children = [transformed];
14943
- }
14944
- } else if (ts19.isConditionalExpression(body)) {
14945
- children = [transformConditional(body, ctx)];
14946
- } else if (ts19.isParenthesizedExpression(body)) {
14947
- let inner = body.expression;
14948
- while (ts19.isParenthesizedExpression(inner)) {
14949
- inner = inner.expression;
14950
- }
14951
- if (ts19.isJsxElement(inner) || ts19.isJsxSelfClosingElement(inner) || ts19.isJsxFragment(inner)) {
14952
- const transformed = transformNode(inner, ctx);
14953
- if (transformed) {
14954
- children = [transformed];
14955
- }
14956
- } else if (ts19.isConditionalExpression(inner)) {
14957
- children = [transformConditional(inner, ctx)];
14958
- } else if (method === "flatMap" && ts19.isArrayLiteralExpression(inner)) {
14959
- children = transformArrayLiteralChildren(inner, ctx);
14960
- } else {
14961
- tryTransformRenderableBody(inner);
14962
- }
14963
- } else if (method === "flatMap" && ts19.isArrayLiteralExpression(body)) {
14964
- children = transformArrayLiteralChildren(body, ctx);
14965
- } else if (ts19.isBlock(body)) {
14966
- const multiReturn = method !== "flatMap" ? extractMultiReturnJsxBranches(body, true) : null;
14967
- if (multiReturn && multiReturn.branches.length > 0) {
14968
- const loc = getSourceLocation(body, ctx.sourceFile, ctx.filePath);
14969
- children = [foldMultiReturnBranches(multiReturn, ctx, loc, ctx.getJS)];
14970
- const pre = multiReturn.preamble ?? [];
14971
- if (pre.length > 0) {
14972
- preamble = preambleFromValueStatements(pre, ctx, body.statements);
14973
- if (!preamble.declarations && !isClientOnly && !(ctx.analyzer.acceptsCallbackBody?.("map") ?? false)) {
14974
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, loc, {
14975
- message: "A .map() callback body with a preamble before its branches cannot be " + "lowered to a template: the preamble is not a sequence of value " + "declarations, so this backend has no per-row local to carry into the " + "branches.",
14976
- suggestion: {
14977
- message: "Add /* @client */ to evaluate this expression on the client only"
14978
- }
14979
- }));
14980
- }
14981
- }
14982
- }
14983
- const returnStmt = children.length === 0 ? body.statements.find((s) => ts19.isReturnStatement(s) && s.expression != null) : undefined;
14984
- let rowScopeBeforePreamble = null;
14985
- if (returnStmt) {
14986
- const preambleNames = new Set;
14987
- for (const stmt of body.statements) {
14988
- if (stmt === returnStmt)
14989
- break;
14990
- collectPreambleDeclaredNames(stmt, preambleNames);
14991
- }
14992
- if (preambleNames.size > 0) {
14993
- rowScopeBeforePreamble = ctx.scope;
14994
- ctx.scope = savedScope.enterLoopRow({
14995
- param,
14996
- index,
14997
- paramBindings,
14998
- preamble: { declaredNames: [...preambleNames] }
14999
- });
15000
- }
15001
- }
15002
- if (returnStmt && returnStmt.expression) {
15003
- let returnExpr = returnStmt.expression;
15004
- while (ts19.isParenthesizedExpression(returnExpr)) {
15005
- returnExpr = returnExpr.expression;
15006
- }
15007
- if (ts19.isJsxElement(returnExpr) || ts19.isJsxSelfClosingElement(returnExpr) || ts19.isJsxFragment(returnExpr)) {
15008
- const transformed = transformNode(returnExpr, ctx);
15009
- if (transformed) {
15010
- children = [transformed];
15011
- }
15012
- }
15013
- let jsxPreambleStmt;
15014
- for (const stmt of body.statements) {
15015
- if (stmt === returnStmt)
15016
- break;
15017
- if (containsJsxInExpression(stmt)) {
15018
- jsxPreambleStmt = stmt;
15019
- break;
15020
- }
15021
- }
15022
- if (jsxPreambleStmt) {
15023
- const jsRuntime = isClientOnly || (ctx.analyzer.acceptsCallbackBody?.("map") ?? false);
15024
- if (children.length === 0) {
15025
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(jsxPreambleStmt, ctx.sourceFile, ctx.filePath), {
15026
- message: "A .map() callback that builds JSX in a statement before its " + "`return` must return a single JSX element that embeds the " + "built array — this return shape has no element root to host it.",
15027
- suggestion: {
15028
- message: "Wrap the result in one element root, e.g. `return <tr key={item.id}>{out}</tr>`."
15029
- }
15030
- }));
15031
- } else if (!jsRuntime) {
15032
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(jsxPreambleStmt, ctx.sourceFile, ctx.filePath), {
15033
- message: "A .map() callback that builds JSX in a statement before its " + "`return` (for example pushing elements into an array in a loop) " + "cannot be lowered to a template on this backend.",
15034
- suggestion: {
15035
- message: "Add /* @client */ to render this loop on the client only"
15036
- }
15037
- }));
15038
- } else {
15039
- const collected = buildPreambleSegments(body.statements, returnStmt, ctx);
15040
- if (collected.refusalNode) {
15041
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(collected.refusalNode, ctx.sourceFile, ctx.filePath), {
15042
- message: "A JSX element built in a .map() callback preamble cannot carry " + "event handlers, components, nested loops, or reactive expressions, " + "and cannot sit inside a template literal — the verbatim render " + "path builds it once, with no reactive wiring.",
15043
- suggestion: {
15044
- message: "Return the element directly (not through a preamble variable), " + "or add /* @client */ to render the loop on the client only."
15045
- }
15046
- }));
15047
- } else {
15048
- preamble = collected.preamble;
15049
- }
15050
- }
15051
- } else {
15052
- const valueStmts = [];
15053
- for (const stmt of body.statements) {
15054
- if (stmt === returnStmt)
15055
- break;
15056
- valueStmts.push(stmt);
15057
- }
15058
- if (valueStmts.length > 0) {
15059
- preamble = preambleFromValueStatements(valueStmts, ctx, body.statements);
15060
- if (!preamble.declarations && !isClientOnly && !(ctx.analyzer.acceptsCallbackBody?.("map") ?? false)) {
15061
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(body, ctx.sourceFile, ctx.filePath), {
15062
- message: "A .map() callback preamble that is not a sequence of value " + "declarations cannot be lowered to a template: this backend can " + "declare a per-row local, but cannot run arbitrary statements per row.",
15063
- suggestion: {
15064
- message: "Add /* @client */ to evaluate this expression on the client only"
15065
- }
15066
- }));
15067
- }
15068
- }
15069
- }
15070
- }
15071
- if (rowScopeBeforePreamble) {
15072
- ctx.scope = rowScopeBeforePreamble;
15069
+ }));
15070
+ }
15071
+ function lowerMultiReturnLoopBody(body, ctx, isClientOnly) {
15072
+ const multiReturn = extractMultiReturnJsxBranches(body, true);
15073
+ if (!multiReturn || multiReturn.branches.length === 0)
15074
+ return null;
15075
+ const loc = getSourceLocation(body, ctx.sourceFile, ctx.filePath);
15076
+ const children = [foldMultiReturnBranches(multiReturn, ctx, loc, ctx.getJS)];
15077
+ const pre = multiReturn.preamble ?? [];
15078
+ if (pre.length === 0)
15079
+ return { children, preamble: undefined };
15080
+ const preamble = preambleFromValueStatements(pre, ctx, body.statements);
15081
+ refuseUndeclarablePreamble(preamble, loc, "A .map() callback body with a preamble before its branches cannot be " + "lowered to a template: the preamble is not a sequence of value " + "declarations, so this backend has no per-row local to carry into the " + "branches.", ctx, isClientOnly);
15082
+ return { children, preamble };
15083
+ }
15084
+ function withPreambleRowScope(ctx, savedScope, row, body, returnStmt, run) {
15085
+ const preambleNames = new Set;
15086
+ for (const stmt of body.statements) {
15087
+ if (stmt === returnStmt)
15088
+ break;
15089
+ collectPreambleDeclaredNames(stmt, preambleNames);
15090
+ }
15091
+ if (preambleNames.size === 0)
15092
+ return run();
15093
+ const rowScopeBeforePreamble = ctx.scope;
15094
+ ctx.scope = savedScope.enterLoopRow({
15095
+ param: row.param,
15096
+ index: row.index,
15097
+ paramBindings: row.paramBindings,
15098
+ preamble: { declaredNames: [...preambleNames] }
15099
+ });
15100
+ try {
15101
+ return run();
15102
+ } finally {
15103
+ ctx.scope = rowScopeBeforePreamble;
15104
+ }
15105
+ }
15106
+ function findJsxBuildingPreambleStatement(body, returnStmt) {
15107
+ for (const stmt of body.statements) {
15108
+ if (stmt === returnStmt)
15109
+ break;
15110
+ if (containsJsxInExpression(stmt))
15111
+ return stmt;
15112
+ }
15113
+ return;
15114
+ }
15115
+ function lowerJsxBuildingPreamble(body, returnStmt, jsxPreambleStmt, children, ctx, isClientOnly) {
15116
+ const jsRuntime = isClientOnly || (ctx.analyzer.acceptsCallbackBody?.("map") ?? false);
15117
+ if (children.length === 0) {
15118
+ ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(jsxPreambleStmt, ctx.sourceFile, ctx.filePath), {
15119
+ message: "A .map() callback that builds JSX in a statement before its " + "`return` must return a single JSX element that embeds the " + "built array — this return shape has no element root to host it.",
15120
+ suggestion: {
15121
+ message: "Wrap the result in one element root, e.g. `return <tr key={item.id}>{out}</tr>`."
15073
15122
  }
15074
- if (method === "flatMap" && children.length === 0 && !flatMapProjectionCall(body)) {
15075
- flatMapCallback = buildFlatMapCallback(callback, body, ctx);
15123
+ }));
15124
+ return;
15125
+ }
15126
+ if (!jsRuntime) {
15127
+ ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(jsxPreambleStmt, ctx.sourceFile, ctx.filePath), {
15128
+ message: "A .map() callback that builds JSX in a statement before its " + "`return` (for example pushing elements into an array in a loop) " + "cannot be lowered to a template on this backend.",
15129
+ suggestion: {
15130
+ message: CLIENT_ONLY_LOOP_SUGGESTION
15076
15131
  }
15077
- } else {
15078
- tryTransformRenderableBody(body);
15079
- }
15080
- if (method === "flatMap" && children.length === 0 && !flatMapCallback) {
15081
- const projection = flatMapProjectionCall(body);
15082
- if (projection) {
15083
- const transformed = transformJsxExpression(projection, ctx, isClientOnly);
15084
- if (transformed && transformed.type === "loop") {
15085
- children = [transformed];
15086
- }
15132
+ }));
15133
+ return;
15134
+ }
15135
+ const collected = buildPreambleSegments(body.statements, returnStmt, ctx);
15136
+ if (collected.refusalNode) {
15137
+ ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(collected.refusalNode, ctx.sourceFile, ctx.filePath), {
15138
+ message: "A JSX element built in a .map() callback preamble cannot carry " + "event handlers, components, nested loops, or reactive expressions, " + "and cannot sit inside a template literal — the verbatim render " + "path builds it once, with no reactive wiring.",
15139
+ suggestion: {
15140
+ message: "Return the element directly (not through a preamble variable), " + "or add /* @client */ to render the loop on the client only."
15087
15141
  }
15142
+ }));
15143
+ return;
15144
+ }
15145
+ return collected.preamble;
15146
+ }
15147
+ function lowerValuePreamble(body, returnStmt, ctx, isClientOnly) {
15148
+ const valueStmts = [];
15149
+ for (const stmt of body.statements) {
15150
+ if (stmt === returnStmt)
15151
+ break;
15152
+ valueStmts.push(stmt);
15153
+ }
15154
+ if (valueStmts.length === 0)
15155
+ return;
15156
+ const preamble = preambleFromValueStatements(valueStmts, ctx, body.statements);
15157
+ refuseUndeclarablePreamble(preamble, getSourceLocation(body, ctx.sourceFile, ctx.filePath), "A .map() callback preamble that is not a sequence of value " + "declarations cannot be lowered to a template: this backend can " + "declare a per-row local, but cannot run arbitrary statements per row.", ctx, isClientOnly);
15158
+ return preamble;
15159
+ }
15160
+ function lowerSingleReturnLoopBody(body, returnStmt, ctx, isClientOnly) {
15161
+ let returnExpr = returnStmt.expression;
15162
+ while (ts19.isParenthesizedExpression(returnExpr)) {
15163
+ returnExpr = returnExpr.expression;
15164
+ }
15165
+ let children = [];
15166
+ if (ts19.isJsxElement(returnExpr) || ts19.isJsxSelfClosingElement(returnExpr) || ts19.isJsxFragment(returnExpr)) {
15167
+ const transformed = transformNode(returnExpr, ctx);
15168
+ if (transformed) {
15169
+ children = [transformed];
15088
15170
  }
15089
- if (method === "flatMap" && children.length === 0 && !flatMapCallback && !ts19.isBlock(body)) {
15090
- flatMapCallback = buildFlatMapCallback(callback, body, ctx);
15171
+ }
15172
+ const jsxPreambleStmt = findJsxBuildingPreambleStatement(body, returnStmt);
15173
+ const preamble = jsxPreambleStmt ? lowerJsxBuildingPreamble(body, returnStmt, jsxPreambleStmt, children, ctx, isClientOnly) : lowerValuePreamble(body, returnStmt, ctx, isClientOnly);
15174
+ return { children, preamble };
15175
+ }
15176
+ function transformLoopBlockBody(body, callback, row, savedScope, ctx, isClientOnly, method) {
15177
+ const out = { children: [], preamble: undefined, flatMapCallback: undefined };
15178
+ const multi = method !== "flatMap" ? lowerMultiReturnLoopBody(body, ctx, isClientOnly) : null;
15179
+ if (multi) {
15180
+ out.children = multi.children;
15181
+ out.preamble = multi.preamble;
15182
+ }
15183
+ const returnStmt = out.children.length === 0 ? body.statements.find((s) => ts19.isReturnStatement(s) && s.expression != null) : undefined;
15184
+ if (returnStmt) {
15185
+ const single = withPreambleRowScope(ctx, savedScope, row, body, returnStmt, () => lowerSingleReturnLoopBody(body, returnStmt, ctx, isClientOnly));
15186
+ out.children = single.children;
15187
+ out.preamble = single.preamble;
15188
+ }
15189
+ if (method === "flatMap" && out.children.length === 0 && !flatMapProjectionCall(body)) {
15190
+ out.flatMapCallback = buildFlatMapCallback(callback, body, ctx);
15191
+ }
15192
+ return out;
15193
+ }
15194
+ function applyFlatMapFallbacks(out, callback, ctx, isClientOnly, method) {
15195
+ if (method !== "flatMap")
15196
+ return;
15197
+ const body = callback.body;
15198
+ if (out.children.length === 0 && !out.flatMapCallback) {
15199
+ const projection = flatMapProjectionCall(body);
15200
+ if (projection) {
15201
+ const transformed = transformJsxExpression(projection, ctx, isClientOnly);
15202
+ if (transformed && transformed.type === "loop") {
15203
+ out.children = [transformed];
15204
+ }
15091
15205
  }
15092
- if (flatMapCallback)
15093
- preamble = undefined;
15094
- if (flatMapCallback && !isClientOnly && !(ctx.analyzer.acceptsCallbackBody?.("flatMap") ?? false)) {
15095
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(body, ctx.sourceFile, ctx.filePath), {
15096
- message: "A .flatMap() callback body with statements or a nested projection " + "cannot be lowered to a template on this backend.",
15097
- suggestion: {
15098
- message: "Add /* @client */ to render this loop on the client only"
15099
- }
15100
- }));
15206
+ }
15207
+ if (out.children.length === 0 && !out.flatMapCallback && !ts19.isBlock(body)) {
15208
+ out.flatMapCallback = buildFlatMapCallback(callback, body, ctx);
15209
+ }
15210
+ if (!out.flatMapCallback)
15211
+ return;
15212
+ out.preamble = undefined;
15213
+ if (isClientOnly || (ctx.analyzer.acceptsCallbackBody?.("flatMap") ?? false))
15214
+ return;
15215
+ ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(body, ctx.sourceFile, ctx.filePath), {
15216
+ message: "A .flatMap() callback body with statements or a nested projection " + "cannot be lowered to a template on this backend.",
15217
+ suggestion: {
15218
+ message: CLIENT_ONLY_LOOP_SUGGESTION
15101
15219
  }
15220
+ }));
15221
+ }
15222
+ function withLoopRowScope(ctx, row, fn) {
15223
+ const savedScope = ctx.scope;
15224
+ ctx.scope = ctx.scope.enterLoopRow({ param: row.param, index: row.index, paramBindings: row.paramBindings });
15225
+ ctx.loopDepth++;
15226
+ try {
15227
+ return fn(savedScope);
15228
+ } finally {
15102
15229
  ctx.scope = savedScope;
15103
15230
  ctx.loopDepth--;
15104
15231
  }
15105
- if (children.length === 0 && !flatMapCallback) {
15106
- const cb = node.arguments[0];
15107
- const cbBody = cb && (ts19.isArrowFunction(cb) || ts19.isFunctionExpression(cb)) ? cb.body : undefined;
15108
- if (cbBody && containsJsxInExpression(cbBody) && ctx.analyzer.errors.length === diagCountAtEntry) {
15109
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(cbBody, ctx.sourceFile, ctx.filePath), {
15110
- message: `A .${method}() callback that builds JSX in this shape cannot be ` + "compiled — the JSX would leak verbatim into the client bundle. " + "Recognized bodies: a JSX element/fragment, a ternary or " + "&& / || / ?? expression, an array literal (flatMap), or a block " + "body whose return the compiler can lower.",
15111
- suggestion: {
15112
- message: "Restructure the callback to return the JSX element directly " + "(or via a block body with a plain `return`)."
15113
- }
15114
- }));
15232
+ }
15233
+ function transformLoopCallbackBody(callback, row, savedScope, ctx, isClientOnly, method) {
15234
+ const body = callback.body;
15235
+ const out = ts19.isBlock(body) ? transformLoopBlockBody(body, callback, row, savedScope, ctx, isClientOnly, method) : { children: transformLoopExpressionBody(body, ctx, isClientOnly, method), preamble: undefined, flatMapCallback: undefined };
15236
+ applyFlatMapFallbacks(out, callback, ctx, isClientOnly, method);
15237
+ return out;
15238
+ }
15239
+ function refuseUnloweredJsxCallback(node, ctx, method, diagCountAtEntry) {
15240
+ const cb = node.arguments[0];
15241
+ const cbBody = cb && (ts19.isArrowFunction(cb) || ts19.isFunctionExpression(cb)) ? cb.body : undefined;
15242
+ if (!cbBody || !containsJsxInExpression(cbBody))
15243
+ return;
15244
+ if (ctx.analyzer.errors.length !== diagCountAtEntry)
15245
+ return;
15246
+ ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(cbBody, ctx.sourceFile, ctx.filePath), {
15247
+ message: `A .${method}() callback that builds JSX in this shape cannot be ` + "compiled — the JSX would leak verbatim into the client bundle. " + "Recognized bodies: a JSX element/fragment, a ternary or " + "&& / || / ?? expression, an array literal (flatMap), or a block " + "body whose return the compiler can lower.",
15248
+ suggestion: {
15249
+ message: "Restructure the callback to return the JSX element directly " + "(or via a block body with a plain `return`)."
15115
15250
  }
15116
- return null;
15117
- }
15118
- if (ts19.isArrowFunction(node.arguments[0]) && children.length > 0) {
15119
- checkLoopKey(node.arguments[0], ctx, isNested);
15251
+ }));
15252
+ }
15253
+ function resolveLoopKey(callback, children, ctx, isNested, depth) {
15254
+ if (children.length > 0) {
15255
+ checkLoopKey(callback, ctx, isNested);
15120
15256
  }
15121
15257
  const itemConditional = children.length > 0 ? loopBodyItemConditional(children) : null;
15122
15258
  const bodyIsItemConditional = itemConditional !== null;
15123
- const key = bodyIsItemConditional ? extractItemConditionalKey(itemConditional) : children.length > 0 ? extractLoopKey(children[0]) : null;
15259
+ const key = itemConditional ? extractItemConditionalKey(itemConditional) : children.length > 0 ? extractLoopKey(children[0]) : null;
15124
15260
  if (key !== null) {
15125
15261
  const resolvedKeyAttrName2 = keyAttrName2(depth);
15126
- if (bodyIsItemConditional) {
15262
+ if (itemConditional) {
15127
15263
  applyLoopKeyAttr(itemConditional, resolvedKeyAttrName2, key);
15128
15264
  } else if (children.length > 0) {
15129
15265
  applyLoopKeyAttr(children[0], resolvedKeyAttrName2, key);
15130
15266
  }
15131
15267
  }
15132
15268
  applyRowPortalKeyAttrs(children, key, depth, ctx);
15133
- const declaredNameSet = preamble && preamble.declaredNames.length > 0 ? new Set(preamble.declaredNames) : undefined;
15134
- if (key && declaredNameSet) {
15135
- const keyRefs = extractFreeIdentifiersFromText(key);
15136
- const usesLocal = [...keyRefs].some((r) => declaredNameSet.has(r));
15137
- if (usesLocal) {
15138
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(node, ctx.sourceFile, ctx.filePath), {
15139
- message: "A .map() loop key must be derivable from the loop item — it is " + "evaluated before the callback body runs, so it cannot reference a " + "value computed in the callback preamble.",
15140
- suggestion: {
15141
- message: "Derive the key directly from the loop item (e.g. key={item.id})."
15142
- }
15143
- }));
15269
+ return { key, bodyIsItemConditional };
15270
+ }
15271
+ function refusePreambleDerivedKey(node, key, preamble, ctx) {
15272
+ if (!key || !preamble || preamble.declaredNames.length === 0)
15273
+ return;
15274
+ const declaredNameSet = new Set(preamble.declaredNames);
15275
+ const keyRefs = extractFreeIdentifiersFromText(key);
15276
+ const usesLocal = [...keyRefs].some((r) => declaredNameSet.has(r));
15277
+ if (!usesLocal)
15278
+ return;
15279
+ ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(node, ctx.sourceFile, ctx.filePath), {
15280
+ message: "A .map() loop key must be derivable from the loop item — it is " + "evaluated before the callback body runs, so it cannot reference a " + "value computed in the callback preamble.",
15281
+ suggestion: {
15282
+ message: "Derive the key directly from the loop item (e.g. key={item.id})."
15283
+ }
15284
+ }));
15285
+ }
15286
+ function applyPreambleBuilderPasses(node, children, preamble, ctx) {
15287
+ if (!preamble || preamble.builderNames.length === 0)
15288
+ return preamble;
15289
+ flagArrayChildExpressions(children, new Set(preamble.builderNames));
15290
+ if (children.length !== 1 || children[0].type !== "component")
15291
+ return preamble;
15292
+ ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(node, ctx.sourceFile, ctx.filePath), {
15293
+ message: "A .map() callback that builds JSX in its preamble cannot return a " + "component: the built elements would reach the component as raw HTML " + "strings on the client but as JSX elements at SSR (a silent divergence).",
15294
+ suggestion: {
15295
+ message: "Return a plain element root that embeds the array, or move the " + "building logic inside the component."
15144
15296
  }
15297
+ }));
15298
+ return;
15299
+ }
15300
+ function loopChildComponentOf(children) {
15301
+ if (children.length !== 1 || children[0].type !== "component")
15302
+ return;
15303
+ const comp = children[0];
15304
+ return {
15305
+ name: comp.name,
15306
+ slotId: comp.slotId,
15307
+ props: comp.props.filter((p) => p.name !== "key").map((p) => ({
15308
+ name: p.name,
15309
+ value: p.value,
15310
+ isEventHandler: isEventHandlerName(p.name)
15311
+ })),
15312
+ children: comp.children
15313
+ };
15314
+ }
15315
+ function classifyLoopArray(source, method, ctx) {
15316
+ const callsReactive = exprCallsReactiveGetters(source.arrayExpr, ctx);
15317
+ const hasCalls = exprHasFunctionCalls(source.arrayExpr);
15318
+ const isDirectPropArray = method !== "flatMap" && isArrayExprDirectPropRef(source.arrayExpr, ctx);
15319
+ const isStaticArray = !isSignalOrMemoArray(source.array, ctx) && !isDirectPropArray && !hasCalls && !source.objectIteration;
15320
+ return { callsReactive, hasCalls, isDirectPropArray, isStaticArray };
15321
+ }
15322
+ function markPreambleReactivity(children, preamble, isStaticArray, ctx) {
15323
+ if (!preamble || isStaticArray)
15324
+ return;
15325
+ const declared = new Set(preamble.declaredNames);
15326
+ const preambleRegions = collectPreambleRegions(children, declared, ctx);
15327
+ markPreambleAttrSlots(children, declared, ctx);
15328
+ if (preamble.reactiveNames && preamble.reactiveNames.length > 0) {
15329
+ markPreambleConditionalReactivity(children, new Set(preamble.reactiveNames), ctx);
15145
15330
  }
15146
- if (preamble && preamble.builderNames.length > 0) {
15147
- flagArrayChildExpressions(children, new Set(preamble.builderNames));
15331
+ return preambleRegions;
15332
+ }
15333
+ function scalarLoopItemType(itemTypeNode, ctx) {
15334
+ const callbackType = itemTypeNode && ctx.analyzer.checker ? tsTypeToTypeInfo(ctx.analyzer.checker.getTypeAtLocation(itemTypeNode), ctx.analyzer.checker) : null;
15335
+ if (!callbackType)
15336
+ return null;
15337
+ if (callbackType.kind === "primitive")
15338
+ return callbackType;
15339
+ if (callbackType.kind === "union" && callbackType.unionTypes?.every((t) => t.kind === "primitive")) {
15340
+ return callbackType;
15148
15341
  }
15149
- if (preamble && preamble.builderNames.length > 0 && children.length === 1 && children[0].type === "component") {
15150
- ctx.analyzer.errors.push(createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(node, ctx.sourceFile, ctx.filePath), {
15151
- message: "A .map() callback that builds JSX in its preamble cannot return a " + "component: the built elements would reach the component as raw HTML " + "strings on the client but as JSX elements at SSR (a silent divergence).",
15152
- suggestion: {
15153
- message: "Return a plain element root that embeds the array, or move the " + "building logic inside the component."
15154
- }
15155
- }));
15156
- preamble = undefined;
15342
+ return null;
15343
+ }
15344
+ function transformMapCall(node, ctx, isClientOnly = false, method = "map") {
15345
+ const isNested = ctx.scope.valueBoundNames().size > 0;
15346
+ const diagCountAtEntry = ctx.analyzer.errors.length;
15347
+ const depth = ctx.loopDepth;
15348
+ const source = resolveLoopSource(node, ctx, isClientOnly);
15349
+ const callback = node.arguments[0];
15350
+ if (!ts19.isArrowFunction(callback)) {
15351
+ refuseUnloweredJsxCallback(node, ctx, method, diagCountAtEntry);
15352
+ return null;
15157
15353
  }
15158
- tagLoopItemRootComponents(children);
15159
- let childComponent;
15160
- if (children.length === 1 && children[0].type === "component") {
15161
- const comp = children[0];
15162
- childComponent = {
15163
- name: comp.name,
15164
- slotId: comp.slotId,
15165
- props: comp.props.filter((p) => p.name !== "key").map((p) => ({
15166
- name: p.name,
15167
- value: p.value,
15168
- isEventHandler: isEventHandlerName(p.name)
15169
- })),
15170
- children: comp.children
15171
- };
15354
+ const row = resolveLoopRowParams(callback, source, ctx);
15355
+ const body = withLoopRowScope(ctx, row, (savedScope) => transformLoopCallbackBody(callback, row, savedScope, ctx, isClientOnly, method));
15356
+ const { children, flatMapCallback } = body;
15357
+ if (children.length === 0 && !flatMapCallback) {
15358
+ refuseUnloweredJsxCallback(node, ctx, method, diagCountAtEntry);
15359
+ return null;
15172
15360
  }
15361
+ const { key, bodyIsItemConditional } = resolveLoopKey(callback, children, ctx, isNested, depth);
15362
+ refusePreambleDerivedKey(node, key, body.preamble, ctx);
15363
+ const preamble = applyPreambleBuilderPasses(node, children, body.preamble, ctx);
15364
+ tagLoopItemRootComponents(children);
15365
+ const childComponent = loopChildComponentOf(children);
15173
15366
  const bodyIsMultiRoot = loopBodyIsMultiRoot(children);
15174
- const callsReactive = exprCallsReactiveGetters(arrayExpr, ctx);
15175
- const hasCalls = exprHasFunctionCalls(arrayExpr);
15176
- const isDirectPropArray = method !== "flatMap" && isArrayExprDirectPropRef(arrayExpr, ctx);
15177
- const isStaticArray = !isSignalOrMemoArray(array, ctx) && !isDirectPropArray && !hasCalls && !objectIteration;
15178
- const preambleRegions = preamble && !isStaticArray ? collectPreambleRegions(children, new Set(preamble.declaredNames), ctx) : undefined;
15179
- if (preamble && !isStaticArray) {
15180
- markPreambleAttrSlots(children, new Set(preamble.declaredNames), ctx);
15181
- if (preamble.reactiveNames && preamble.reactiveNames.length > 0) {
15182
- markPreambleConditionalReactivity(children, new Set(preamble.reactiveNames), ctx);
15183
- }
15184
- }
15367
+ const arrayKind = classifyLoopArray(source, method, ctx);
15368
+ const preambleRegions = markPreambleReactivity(children, preamble, arrayKind.isStaticArray, ctx);
15185
15369
  const nestedComponents = collectNestedComponents(children).filter((c) => c.name !== childComponent?.name);
15186
- const callbackType = itemTypeNode && ctx.analyzer.checker ? tsTypeToTypeInfo(ctx.analyzer.checker.getTypeAtLocation(itemTypeNode), ctx.analyzer.checker) : null;
15187
- const scalarItemType = callbackType?.kind === "primitive" || callbackType?.kind === "union" && callbackType.unionTypes?.every((t) => t.kind === "primitive") ? callbackType : null;
15188
15370
  return {
15189
15371
  type: "loop",
15190
15372
  method: method === "flatMap" ? "flatMap" : undefined,
15191
- array,
15192
- templateArray,
15373
+ array: source.array,
15374
+ templateArray: source.templateArray,
15193
15375
  arrayType: null,
15194
- itemType: scalarItemType,
15195
- param,
15196
- index,
15376
+ itemType: scalarLoopItemType(row.itemTypeNode, ctx),
15377
+ param: row.param,
15378
+ index: row.index,
15197
15379
  key,
15198
15380
  children,
15199
15381
  slotId: null,
15200
15382
  markerId: `l${ctx.loopMarkerCounter++}`,
15201
- isStaticArray,
15202
- isPropDerivedArray: isDirectPropArray || undefined,
15203
- callsReactiveGetters: callsReactive || undefined,
15204
- hasFunctionCalls: hasCalls || undefined,
15383
+ isStaticArray: arrayKind.isStaticArray,
15384
+ isPropDerivedArray: arrayKind.isDirectPropArray || undefined,
15385
+ callsReactiveGetters: arrayKind.callsReactive || undefined,
15386
+ hasFunctionCalls: arrayKind.hasCalls || undefined,
15205
15387
  bodyIsMultiRoot: bodyIsMultiRoot || undefined,
15206
15388
  bodyIsItemConditional: bodyIsItemConditional || undefined,
15207
15389
  childComponent,
15208
15390
  nestedComponents,
15209
- filterPredicate,
15210
- sortComparator,
15211
- chainOrder,
15212
- iterationShape,
15213
- objectIteration,
15391
+ filterPredicate: source.filterPredicate,
15392
+ sortComparator: source.sortComparator,
15393
+ chainOrder: source.chainOrder,
15394
+ iterationShape: source.iterationShape,
15395
+ objectIteration: source.objectIteration,
15214
15396
  depth,
15215
15397
  clientOnly: isClientOnly || undefined,
15216
15398
  preamble,
15217
15399
  preambleRegions: preambleRegions && preambleRegions.length > 0 ? preambleRegions : undefined,
15218
- paramType,
15219
- indexType,
15220
- paramBindings,
15221
- arrayFreeIdentifiers: extractFreeIdentifiersFromNode(arrayExpr),
15400
+ paramType: row.paramType,
15401
+ indexType: row.indexType,
15402
+ paramBindings: row.paramBindings,
15403
+ arrayFreeIdentifiers: extractFreeIdentifiersFromNode(source.arrayExpr),
15222
15404
  flatMapCallback,
15223
15405
  loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath)
15224
15406
  };
@@ -24447,7 +24629,7 @@ function emitKeyedLookup(ls, ev, handlerCall, lookup) {
24447
24629
  ls.push(` const key = li.getAttribute('${DATA_KEY}')`);
24448
24630
  if (hasBindings) {
24449
24631
  ls.push(` const __bfLoopItem = ${arrayExpr}.find(item => String(${keyWithItem}) === key)`);
24450
- ls.push(` if (__bfLoopItem) {`);
24632
+ ls.push(` if (__bfLoopItem !== undefined) {`);
24451
24633
  ls.push(` const ${param} = __bfLoopItem`);
24452
24634
  if (preambleLine)
24453
24635
  ls.push(` ${preambleLine}`);
@@ -24457,7 +24639,7 @@ function emitKeyedLookup(ls, ev, handlerCall, lookup) {
24457
24639
  ls.push(` }`);
24458
24640
  } else {
24459
24641
  ls.push(` const ${param} = ${arrayExpr}.find(item => String(${keyWithItem}) === key)`);
24460
- ls.push(` if (${param}) {`);
24642
+ ls.push(` if (${param} !== undefined) {`);
24461
24643
  if (preambleLine)
24462
24644
  ls.push(` ${preambleLine}`);
24463
24645
  if (idxLine2)
@@ -24486,12 +24668,12 @@ function emitKeyedLookup(ls, ev, handlerCall, lookup) {
24486
24668
  const rawKey = nested.key ?? "";
24487
24669
  const innerKeyExpr = nested.paramBindings && nested.paramBindings.length > 0 ? substituteLoopBindings(rawKey, nested.paramBindings, "item") : rawKey.replace(identifierPattern(nested.param, "g"), "item");
24488
24670
  const outerRef = hasBindings ? "__bfLoopItem" : param;
24489
- ls.push(` const ${nested.param} = ${outerRef} && ${nested.array}.find(item => String(${innerKeyExpr}) === innerKey${nested.depth})`);
24671
+ ls.push(` const ${nested.param} = ${outerRef} !== undefined ? ${nested.array}.find(item => String(${innerKeyExpr}) === innerKey${nested.depth}) : undefined`);
24490
24672
  }
24491
24673
  const outerGuard = hasBindings ? "__bfLoopItem" : param;
24492
24674
  const allParams = [outerGuard, ...ev.nestedLoops.map((n) => n.param)];
24493
24675
  const idxLine = indexBindingLine(ev.handler, indexParam, `${arrayExpr}.findIndex(item => String(${keyWithItem}) === outerKey)`);
24494
- ls.push(` if (${allParams.join(" && ")}) {`);
24676
+ ls.push(` if (${allParams.map((p) => `${p} !== undefined`).join(" && ")}) {`);
24495
24677
  if (preambleLine)
24496
24678
  ls.push(` ${preambleLine}`);
24497
24679
  if (idxLine)
@@ -24508,7 +24690,7 @@ function emitDynamicIndexLookup(ls, ev, handlerCall, lookup) {
24508
24690
  ls.push(` const idx = Array.from(li.parentElement.children).indexOf(li)`);
24509
24691
  if (hasBindings) {
24510
24692
  ls.push(` const __bfLoopItem = ${arrayExpr}[idx]`);
24511
- ls.push(` if (__bfLoopItem) {`);
24693
+ ls.push(` if (__bfLoopItem !== undefined) {`);
24512
24694
  ls.push(` const ${param} = __bfLoopItem`);
24513
24695
  if (preambleLine)
24514
24696
  ls.push(` ${preambleLine}`);
@@ -24518,7 +24700,7 @@ function emitDynamicIndexLookup(ls, ev, handlerCall, lookup) {
24518
24700
  ls.push(` }`);
24519
24701
  } else {
24520
24702
  ls.push(` const ${param} = ${arrayExpr}[idx]`);
24521
- ls.push(` if (${param}) {`);
24703
+ ls.push(` if (${param} !== undefined) {`);
24522
24704
  if (preambleLine)
24523
24705
  ls.push(` ${preambleLine}`);
24524
24706
  if (idxLine)
@@ -24538,7 +24720,7 @@ function emitStaticIndexLookup(ls, ev, handlerCall, lookup, containerVar) {
24538
24720
  const idxOffset = buildLoopChildIndexSubtraction(offset ?? undefined);
24539
24721
  ls.push(` const __idx = Array.from(${containerVar}.children).indexOf(__el)${idxOffset}`);
24540
24722
  ls.push(` const ${param} = ${arrayExpr}[__idx]`);
24541
- ls.push(` if (${param}) {`);
24723
+ ls.push(` if (${param} !== undefined) {`);
24542
24724
  const { guardNames: nestedGuardNames, paramLines: nestedParamLines } = emitNestedIndexParams(ls, ev, "__el", " ");
24543
24725
  const guarded = nestedGuardNames.length > 0;
24544
24726
  if (guarded)
@@ -29222,7 +29404,7 @@ var COMPARISON_OPS = new Set([
29222
29404
  "!=",
29223
29405
  "!=="
29224
29406
  ]);
29225
- function isBooleanResultParsed(node) {
29407
+ function isBooleanResultParsed(node, isBooleanName) {
29226
29408
  switch (node.kind) {
29227
29409
  case "literal":
29228
29410
  return node.literalType === "boolean";
@@ -29231,9 +29413,15 @@ function isBooleanResultParsed(node) {
29231
29413
  case "unary":
29232
29414
  return node.op === "!";
29233
29415
  case "logical":
29234
- return isBooleanResultParsed(node.left) && isBooleanResultParsed(node.right);
29416
+ return isBooleanResultParsed(node.left, isBooleanName) && isBooleanResultParsed(node.right, isBooleanName);
29235
29417
  case "conditional":
29236
- return isBooleanResultParsed(node.consequent) && isBooleanResultParsed(node.alternate);
29418
+ return isBooleanResultParsed(node.consequent, isBooleanName) && isBooleanResultParsed(node.alternate, isBooleanName);
29419
+ case "call":
29420
+ return !!isBooleanName && node.callee.kind === "identifier" && node.args.length === 0 && isBooleanName(node.callee.name);
29421
+ case "member":
29422
+ return !!isBooleanName && !node.computed && node.object.kind === "identifier" && node.object.name === "props" && isBooleanName(node.property, true);
29423
+ case "identifier":
29424
+ return !!isBooleanName && isBooleanName(node.name);
29237
29425
  default:
29238
29426
  return false;
29239
29427
  }
@@ -29260,96 +29448,943 @@ function stringifyBooleanBranch(branch) {
29260
29448
  alternate: { kind: "literal", value: "false", literalType: "string" }
29261
29449
  };
29262
29450
  }
29263
- // src/static-literal.ts
29264
- function evaluateStaticLiteral(expr, bindings) {
29265
- switch (expr.kind) {
29266
- case "literal":
29267
- return { value: expr.value };
29268
- case "template-literal": {
29269
- let out = "";
29270
- for (const part of expr.parts) {
29271
- if (part.type === "string") {
29272
- out += part.value;
29273
- continue;
29274
- }
29275
- const resolved = evaluateStaticLiteral(part.expr, bindings);
29276
- if (!resolved)
29277
- return null;
29278
- out += String(resolved.value);
29279
- }
29280
- return { value: out };
29281
- }
29282
- case "array-literal": {
29283
- const values = [];
29284
- for (const element of expr.elements) {
29285
- const resolved = evaluateStaticLiteral(element, bindings);
29286
- if (!resolved)
29287
- return null;
29288
- values.push(resolved.value);
29289
- }
29290
- return { value: values };
29291
- }
29292
- case "object-literal": {
29293
- const out = {};
29294
- for (const prop of expr.properties) {
29295
- if (prop.kind === "spread") {
29296
- const resolved2 = evaluateStaticLiteral(prop.expr, bindings);
29297
- if (!resolved2)
29298
- return null;
29299
- if (resolved2.value === null || resolved2.value === undefined)
29300
- continue;
29301
- if (typeof resolved2.value !== "object" || Array.isArray(resolved2.value))
29302
- return null;
29303
- Object.assign(out, resolved2.value);
29304
- continue;
29305
- }
29306
- const resolved = evaluateStaticLiteral(prop.value, bindings);
29307
- if (!resolved)
29308
- return null;
29309
- out[prop.key] = resolved.value;
29310
- }
29311
- return { value: out };
29312
- }
29313
- case "unary": {
29314
- const resolved = evaluateStaticLiteral(expr.argument, bindings);
29315
- if (!resolved)
29316
- return null;
29317
- if (expr.op === "-")
29318
- return typeof resolved.value === "number" ? { value: -resolved.value } : null;
29319
- if (expr.op === "+")
29320
- return typeof resolved.value === "number" ? { value: +resolved.value } : null;
29321
- if (expr.op === "!")
29322
- return { value: !resolved.value };
29323
- return null;
29324
- }
29325
- case "identifier":
29326
- return bindings?.has(expr.name) ? { value: bindings.get(expr.name) } : null;
29327
- case "member": {
29328
- const base = evaluateStaticLiteral(expr.object, bindings);
29329
- if (!base || base.value === null || typeof base.value !== "object")
29330
- return null;
29331
- return { value: base.value[expr.property] };
29451
+ function collectBooleanValueNames(metadata) {
29452
+ const isBoolean = (type) => type?.kind === "primitive" && type.primitive === "boolean";
29453
+ const isBooleanSeed = (type, seed) => {
29454
+ const text = seed?.trim();
29455
+ return isBoolean(type) || (!type || type.kind === "unknown") && (text === "true" || text === "false");
29456
+ };
29457
+ const names = new Set;
29458
+ const props = new Set;
29459
+ for (const signal of metadata.signals) {
29460
+ if (isBooleanSeed(signal.type, signal.initialValue))
29461
+ names.add(signal.getter);
29462
+ }
29463
+ for (const memo of metadata.memos ?? []) {
29464
+ if (isBoolean(memo.type))
29465
+ names.add(memo.name);
29466
+ }
29467
+ const provenParams = new Set;
29468
+ for (const param of metadata.propsParams) {
29469
+ if (!isBoolean(param.type))
29470
+ continue;
29471
+ if (param.optional && !(param.parsed && isBooleanResultParsed(param.parsed, (n, member) => !member && provenParams.has(n))))
29472
+ continue;
29473
+ provenParams.add(param.name);
29474
+ props.add(param.sourceName ?? param.name);
29475
+ if (!metadata.propsObjectName)
29476
+ names.add(param.name);
29477
+ }
29478
+ const propsObject = metadata.propsObjectName;
29479
+ const booleanTyped = new Set(metadata.propsParams.filter((p) => isBoolean(p.type)).map((p) => p.sourceName ?? p.name));
29480
+ const readsBooleanProp = (e) => {
29481
+ if (!e)
29482
+ return false;
29483
+ if (e.kind === "member") {
29484
+ return !e.computed && !!propsObject && e.object.kind === "identifier" && e.object.name === propsObject && props.has(e.property);
29332
29485
  }
29333
- case "index-access": {
29334
- const base = evaluateStaticLiteral(expr.object, bindings);
29335
- const index = evaluateStaticLiteral(expr.index, bindings);
29336
- if (!base || !index || !Array.isArray(base.value) || typeof index.value !== "number")
29337
- return null;
29338
- return { value: base.value[index.value] };
29486
+ if (e.kind === "logical" && (e.op === "??" || e.op === "||")) {
29487
+ const left = e.left;
29488
+ return left.kind === "member" && !left.computed && !!propsObject && left.object.kind === "identifier" && left.object.name === propsObject && booleanTyped.has(left.property) && e.right.kind === "literal" && e.right.literalType === "boolean";
29339
29489
  }
29340
- default:
29341
- return null;
29490
+ return false;
29491
+ };
29492
+ for (const constant of metadata.localConstants ?? []) {
29493
+ if (readsBooleanProp(constant.parsed) || isBooleanSeed(constant.type ?? undefined, constant.value))
29494
+ names.add(constant.name);
29495
+ else
29496
+ names.delete(constant.name);
29342
29497
  }
29498
+ return { names, props };
29343
29499
  }
29344
- function isFullyStaticLiteral(expr) {
29345
- return evaluateStaticLiteral(expr) !== null;
29500
+ function isBooleanResultExpr(expr) {
29501
+ const parsed = parseExpression(expr.trim());
29502
+ if (!parsed)
29503
+ return false;
29504
+ return isBooleanResultParsed(parsed);
29346
29505
  }
29347
- function resolveStaticLoopSource(arrayParsed, localConstants, opts) {
29348
- if (!arrayParsed)
29349
- return null;
29350
- let target = arrayParsed;
29351
- if (arrayParsed.kind === "identifier") {
29352
- if (opts?.isNameShadowed?.(arrayParsed.name))
29506
+ function isExplicitStringCall(expr) {
29507
+ const parsed = parseExpression(expr.trim());
29508
+ return !!parsed && parsed.kind === "call" && parsed.callee.kind === "identifier" && parsed.callee.name === "String" && parsed.args.length === 1;
29509
+ }
29510
+ var ARIA_BOOLEAN_ATTRS = new Set([
29511
+ "aria-atomic",
29512
+ "aria-busy",
29513
+ "aria-disabled",
29514
+ "aria-hidden",
29515
+ "aria-modal",
29516
+ "aria-multiline",
29517
+ "aria-multiselectable",
29518
+ "aria-readonly",
29519
+ "aria-required",
29520
+ "aria-selected",
29521
+ "aria-expanded",
29522
+ "aria-checked",
29523
+ "aria-pressed"
29524
+ ]);
29525
+ function isAriaBooleanAttr(name) {
29526
+ return ARIA_BOOLEAN_ATTRS.has(name);
29527
+ }
29528
+ // src/adapters/literal-value.ts
29529
+ function isStringTypeInfo(type) {
29530
+ return type?.kind === "primitive" && type.primitive === "string";
29531
+ }
29532
+ function isBareStringLiteral(initialValue) {
29533
+ if (!initialValue)
29534
+ return false;
29535
+ const v = initialValue.trim();
29536
+ return v.startsWith("'") && v.endsWith("'") || v.startsWith('"') && v.endsWith('"');
29537
+ }
29538
+ function isLiteralIndex(index) {
29539
+ return index.kind === "literal" && (index.literalType === "number" || index.literalType === "string");
29540
+ }
29541
+ // src/adapters/prop-classes.ts
29542
+ function collectBooleanTypedProps(ir) {
29543
+ return new Set(ir.metadata.propsParams.filter((prop) => prop.type?.primitive === "boolean" || prop.type?.raw === "boolean").map((prop) => prop.name));
29544
+ }
29545
+ function collectNullableOptionalProps(ir) {
29546
+ return new Set([
29547
+ ...ir.metadata.propsParams.filter((p) => p.defaultValue === undefined && !p.isRest && (p.type?.kind !== "primitive" || p.optional)).map((p) => p.name),
29548
+ ...ir.metadata.restPropsExpandedKeys
29549
+ ]);
29550
+ }
29551
+ function isBooleanTypedPropRef(expr, ctx) {
29552
+ let bare = expr.trim();
29553
+ if (ctx.propsObjectName && bare.startsWith(`${ctx.propsObjectName}.`)) {
29554
+ bare = bare.slice(ctx.propsObjectName.length + 1);
29555
+ }
29556
+ if (!/^[A-Za-z_$][\w$]*$/.test(bare))
29557
+ return false;
29558
+ if (ctx.isBound(bare))
29559
+ return false;
29560
+ return ctx.booleanTypedProps.has(bare);
29561
+ }
29562
+ // src/adapters/component-tree.ts
29563
+ function hasClientInteractivity(ir) {
29564
+ return ir.metadata.signals.length > 0 || ir.metadata.effects.length > 0 || ir.metadata.onMounts.length > 0 || (ir.metadata.clientAnalysis?.needsInit ?? false);
29565
+ }
29566
+ function collectImportedLoopChildComponentErrors(ir, componentName, adapterName) {
29567
+ const errors = [];
29568
+ const relativeImports = new Set;
29569
+ for (const imp of ir.metadata.templateImports ?? ir.metadata.imports ?? []) {
29570
+ if (!imp.source.startsWith("./") && !imp.source.startsWith("../"))
29571
+ continue;
29572
+ if (imp.isTypeOnly)
29573
+ continue;
29574
+ for (const spec of imp.specifiers) {
29575
+ relativeImports.add(spec.alias ?? spec.name);
29576
+ }
29577
+ }
29578
+ if (relativeImports.size === 0)
29579
+ return errors;
29580
+ const loc = { file: componentName + ".tsx", start: { line: 1, column: 0 }, end: { line: 1, column: 0 } };
29581
+ const visit3 = (node, inLoop) => {
29582
+ if (node.type === "component" && inLoop && relativeImports.has(node.name)) {
29583
+ errors.push(importedLoopChildError(node, loc, adapterName));
29584
+ }
29585
+ const childInLoop = inLoop || node.type === "loop";
29586
+ for (const child of childNodes(node))
29587
+ visit3(child, childInLoop);
29588
+ };
29589
+ visit3(ir.root, false);
29590
+ return errors;
29591
+ }
29592
+ function importedLoopChildError(comp, loc, adapterName) {
29593
+ return {
29594
+ code: "BF103",
29595
+ severity: "error",
29596
+ message: `Component <${comp.name}> is imported from a sibling module and used inside a loop. The ${adapterName} adapter emits a cross-template call; the child template must be registered alongside the parent at render time.`,
29597
+ loc: comp.loc ?? loc,
29598
+ suggestion: {
29599
+ message: `Options:
29600
+ ` + ` 1. Compile '${comp.name}' (its source file) with the same adapter and register the resulting ${adapterName} template alongside the parent at render time.
29601
+ ` + ` 2. Inline <${comp.name}> directly inside the loop body so no cross-file template lookup is needed.
29602
+ ` + ` 3. Mark the loop position as @client-only so the template is materialised on the client instead of at SSR time.`
29603
+ }
29604
+ };
29605
+ }
29606
+ function childNodes(node) {
29607
+ switch (node.type) {
29608
+ case "component":
29609
+ case "element":
29610
+ case "fragment":
29611
+ case "loop":
29612
+ case "provider":
29613
+ return node.children;
29614
+ case "conditional": {
29615
+ const cond = node;
29616
+ return cond.whenFalse ? [cond.whenTrue, cond.whenFalse] : [cond.whenTrue];
29617
+ }
29618
+ case "if-statement": {
29619
+ const stmt = node;
29620
+ return stmt.alternate ? [stmt.consequent, stmt.alternate] : [stmt.consequent];
29621
+ }
29622
+ case "async": {
29623
+ const a = node;
29624
+ return [a.fallback, ...a.children];
29625
+ }
29626
+ default:
29627
+ return [];
29628
+ }
29629
+ }
29630
+ // src/adapters/array-method.ts
29631
+ var required = { kind: "required" };
29632
+ var optional = { kind: "optional" };
29633
+ var zero = { kind: "default", value: { kind: "number", value: 0 } };
29634
+ var ARRAY_METHOD_CATALOGUE = {
29635
+ join: { helper: "join", params: [{ kind: "default", value: { kind: "string", value: "," } }] },
29636
+ includes: { helper: "includes", params: [required] },
29637
+ indexOf: { helper: "index_of", params: [required] },
29638
+ lastIndexOf: { helper: "last_index_of", params: [required] },
29639
+ at: { helper: "at", params: [zero] },
29640
+ concat: { helper: "concat", params: [required], receiverWhenNoArgs: true },
29641
+ slice: { helper: "slice", params: [zero, { kind: "default", value: { kind: "undefined" } }] },
29642
+ reverse: { helper: "reverse", params: [] },
29643
+ toReversed: { helper: "reverse", params: [] },
29644
+ toLowerCase: { helper: "lc", params: [] },
29645
+ toUpperCase: { helper: "uc", params: [] },
29646
+ trim: { helper: "trim", params: [] },
29647
+ trimStart: { helper: "trim_start", params: [] },
29648
+ trimEnd: { helper: "trim_end", params: [] },
29649
+ toFixed: { helper: "to_fixed", params: [zero] },
29650
+ split: { helper: "split", params: [optional, optional] },
29651
+ startsWith: { helper: "starts_with", params: [required, optional] },
29652
+ endsWith: { helper: "ends_with", params: [required, optional] },
29653
+ replace: { helper: "replace", params: [required, required] },
29654
+ replaceAll: { helper: "replace_all", params: [required, required] },
29655
+ repeat: { helper: "repeat", params: [zero] },
29656
+ padStart: { helper: "pad_start", params: [zero, optional] },
29657
+ padEnd: { helper: "pad_end", params: [zero, optional] }
29658
+ };
29659
+ function lowerArrayMethod(method, object, args) {
29660
+ const entry = ARRAY_METHOD_CATALOGUE[method];
29661
+ if (entry.receiverWhenNoArgs && args.length === 0)
29662
+ return { kind: "receiver", object };
29663
+ const out = [];
29664
+ for (const [i, param] of entry.params.entries()) {
29665
+ const arg = args[i];
29666
+ if (arg) {
29667
+ out.push({ kind: "expr", expr: arg });
29668
+ } else if (param.kind === "default") {
29669
+ out.push({ kind: "default", value: param.value });
29670
+ } else if (param.kind === "optional") {
29671
+ break;
29672
+ } else {
29673
+ throw new Error(`lowerArrayMethod: '.${method}()' needs argument ${i + 1}`);
29674
+ }
29675
+ }
29676
+ return { kind: "call", helper: entry.helper, object, args: out };
29677
+ }
29678
+ function emitArrayMethod(plan, emit, spelling) {
29679
+ if (plan.kind === "receiver")
29680
+ return emit(plan.object);
29681
+ const operands = [emit(plan.object)];
29682
+ for (const arg of plan.args) {
29683
+ operands.push(arg.kind === "expr" ? emit(arg.expr) : defaultLiteral(arg.value, spelling));
29684
+ }
29685
+ return spelling.call(plan.helper, operands);
29686
+ }
29687
+ function defaultLiteral(value, spelling) {
29688
+ switch (value.kind) {
29689
+ case "number":
29690
+ return String(value.value);
29691
+ case "string":
29692
+ return `'${value.value}'`;
29693
+ case "undefined":
29694
+ return spelling.undefinedLiteral;
29695
+ }
29696
+ }
29697
+ function prefixedArrayMethodSpelling(prefix, undefinedLiteral) {
29698
+ return {
29699
+ call: (helper, operands) => `${prefix}${helper}(${operands.join(", ")})`,
29700
+ undefinedLiteral
29701
+ };
29702
+ }
29703
+ // src/adapters/callback-method.ts
29704
+ var PREDICATE_EVAL = {
29705
+ filter: { helper: "filter_eval" },
29706
+ every: { helper: "every_eval" },
29707
+ some: { helper: "some_eval" },
29708
+ find: { helper: "find_eval", forward: true },
29709
+ findLast: { helper: "find_eval", forward: false },
29710
+ findIndex: { helper: "find_index_eval", forward: true },
29711
+ findLastIndex: { helper: "find_index_eval", forward: false }
29712
+ };
29713
+ function isPredicateMethod(method) {
29714
+ return Object.hasOwn(PREDICATE_EVAL, method);
29715
+ }
29716
+ function lowerCallbackMethod(method, arrow, restArgs, options) {
29717
+ const { adapterName } = options;
29718
+ const { body, params } = arrow;
29719
+ if (isPredicateMethod(method))
29720
+ return lowerPredicate(method, arrow, options);
29721
+ if (method === "sort" || method === "toSorted") {
29722
+ const plan = sortEvalPlan(body, params);
29723
+ if (plan)
29724
+ return plan;
29725
+ const comparator = sortComparatorFromArrow(arrow);
29726
+ if (comparator)
29727
+ return { kind: "structured-sort", comparator };
29728
+ return sortRefusal(method, adapterName);
29729
+ }
29730
+ if (method === "reduce" || method === "reduceRight") {
29731
+ const init = restArgs[0];
29732
+ const plan = init ? reduceEvalPlan(body, params, init, method === "reduceRight" ? "right" : "left") : null;
29733
+ return plan ?? {
29734
+ kind: "refuse",
29735
+ message: `'.${method}(...)' is outside the ${adapterName} adapter's evaluable surface (needs a literal initial value and an evaluable reducer body)`,
29736
+ suggestion: `Pre-compute the reduced value, or move this position to a '/* @client */' boundary.`
29737
+ };
29738
+ }
29739
+ if (method === "flatMap" || method === "map") {
29740
+ const plan = projectionEvalPlan(method === "map" ? "map_eval" : "flat_map_eval", body, params);
29741
+ return plan ?? {
29742
+ kind: "refuse",
29743
+ message: `'.${method}(...)' projection is outside the ${adapterName} adapter's evaluable surface`,
29744
+ suggestion: `Pre-compute the projected array, or move this position to a '/* @client */' boundary.`
29745
+ };
29746
+ }
29747
+ return { kind: "receiver" };
29748
+ }
29749
+ function lowerPredicate(method, arrow, options) {
29750
+ const param = String(arrow.params[0]);
29751
+ const native = { kind: "native-predicate", method, param, predicate: arrow.body };
29752
+ const nativeOk = options.nativePredicate === true && !hasOpaqueCall(arrow.body) && !readsNestedCallbackIndex(arrow.body);
29753
+ const identity = method === "filter" && arrow.body.kind === "identifier" && arrow.body.name === param;
29754
+ if (nativeOk && identity)
29755
+ return native;
29756
+ const json = serializeParsedExpr(arrow.body);
29757
+ if (json !== null) {
29758
+ const { helper, forward } = PREDICATE_EVAL[method];
29759
+ const operands = [
29760
+ { kind: "string", value: json },
29761
+ { kind: "string", value: param }
29762
+ ];
29763
+ if (forward !== undefined)
29764
+ operands.push({ kind: "boolean", value: forward });
29765
+ return { kind: "eval", helper, operands, captured: freeVarsInBody(arrow.body, new Set(arrow.params.slice(0, 1))) };
29766
+ }
29767
+ if (nativeOk)
29768
+ return native;
29769
+ return {
29770
+ kind: "refuse",
29771
+ message: `'.${method}(...)' predicate is outside the ${options.adapterName} adapter's evaluable surface`,
29772
+ suggestion: `Rewrite the predicate as a pure expression the evaluator can serialize (no nested method-call callbacks), or move this position to a '/* @client */' boundary.`
29773
+ };
29774
+ }
29775
+ function sortEvalPlan(body, params) {
29776
+ const json = serializeParsedExpr(body);
29777
+ if (json === null || params.length < 2)
29778
+ return null;
29779
+ return {
29780
+ kind: "eval",
29781
+ helper: "sort_eval",
29782
+ operands: [
29783
+ { kind: "string", value: json },
29784
+ { kind: "string", value: params[0] },
29785
+ { kind: "string", value: params[1] }
29786
+ ],
29787
+ captured: freeVarsInBody(body, new Set(params))
29788
+ };
29789
+ }
29790
+ function sortRefusal(method, adapterName) {
29791
+ return {
29792
+ kind: "refuse",
29793
+ message: `'.${method}(...)' comparator is outside the ${adapterName} adapter's evaluable / structured surface`,
29794
+ suggestion: `Pre-compute the sorted array, or move this position to a '/* @client */' boundary.`
29795
+ };
29796
+ }
29797
+ function reduceEvalPlan(body, params, init, direction) {
29798
+ const json = serializeParsedExpr(body);
29799
+ if (json === null || init.kind !== "literal" || params.length < 2)
29800
+ return null;
29801
+ let seed;
29802
+ if (init.literalType === "string")
29803
+ seed = { kind: "string", value: String(init.value) };
29804
+ else if (init.literalType === "number")
29805
+ seed = { kind: "number", text: String(init.value) };
29806
+ else
29807
+ return null;
29808
+ return {
29809
+ kind: "eval",
29810
+ helper: "reduce_eval",
29811
+ operands: [
29812
+ { kind: "string", value: json },
29813
+ { kind: "string", value: params[0] },
29814
+ { kind: "string", value: params[1] },
29815
+ seed,
29816
+ { kind: "string", value: direction }
29817
+ ],
29818
+ captured: freeVarsInBody(body, new Set(params))
29819
+ };
29820
+ }
29821
+ function projectionEvalPlan(helper, body, params) {
29822
+ const json = serializeParsedExpr(body);
29823
+ if (json === null)
29824
+ return null;
29825
+ return {
29826
+ kind: "eval",
29827
+ helper,
29828
+ operands: [
29829
+ { kind: "string", value: json },
29830
+ { kind: "string", value: String(params[0]) }
29831
+ ],
29832
+ captured: freeVarsInBody(body, new Set(params.slice(0, 1)))
29833
+ };
29834
+ }
29835
+ function emitCallbackEval(plan, recv, emit, spelling) {
29836
+ const operands = [recv];
29837
+ for (const operand of plan.operands) {
29838
+ if (operand.kind === "string")
29839
+ operands.push(spelling.string(operand.value));
29840
+ else if (operand.kind === "number")
29841
+ operands.push(operand.text);
29842
+ else
29843
+ operands.push(spelling.boolean(operand.value));
29844
+ }
29845
+ const env = plan.captured.map((name) => [name, emit({ kind: "identifier", name })]);
29846
+ operands.push(spelling.env(env));
29847
+ return spelling.call(plan.helper, operands);
29848
+ }
29849
+ function nestedCallbackRefusal(method, adapterName) {
29850
+ return {
29851
+ message: `Filter predicate contains a nested '.${method}(...)' callback, which has no ${adapterName} scalar form`,
29852
+ suggestion: `Rewrite the predicate without a nested callback method, or add /* @client */ for client-only evaluation (no SSR).`
29853
+ };
29854
+ }
29855
+ // src/adapters/component-props.ts
29856
+ import { resolveJsxChildrenProp } from "@barefootjs/shared";
29857
+ function componentPropKey(entry) {
29858
+ if (entry.kind === "slot-id")
29859
+ return "_bf_slot";
29860
+ if (entry.kind === "children")
29861
+ return "children";
29862
+ return entry.name;
29863
+ }
29864
+ function planComponentProps(comp, options) {
29865
+ const segments = [{ kind: "entries", entries: [] }];
29866
+ const push = (entry) => {
29867
+ const last = segments[segments.length - 1];
29868
+ if (last.kind !== "entries") {
29869
+ segments.push({ kind: "entries", entries: [entry] });
29870
+ return;
29871
+ }
29872
+ const at = last.entries.findIndex((e) => componentPropKey(e) === componentPropKey(entry));
29873
+ if (at === -1)
29874
+ last.entries.push(entry);
29875
+ else
29876
+ last.entries[at] = entry;
29877
+ };
29878
+ for (const p of comp.props) {
29879
+ if ((/^on[A-Z]/.test(p.name) || p.name === "ref") && p.value.kind === "expression")
29880
+ continue;
29881
+ if (p.value.kind === "jsx-children") {
29882
+ if (p.name !== "children")
29883
+ push({ kind: "named-slot", name: p.name, children: p.value.children });
29884
+ } else if (p.value.kind === "spread") {
29885
+ if (options.propsObjectName !== null && options.propsObjectName === p.value.expr.trim()) {
29886
+ for (const param of options.propsParams)
29887
+ push({ kind: "props-param", name: param.name });
29888
+ } else {
29889
+ segments.push({ kind: "spread", value: p.value });
29890
+ }
29891
+ } else {
29892
+ push({ kind: "value", name: p.name, value: p.value });
29893
+ }
29894
+ }
29895
+ if (derivesScopeFromSlot(comp))
29896
+ push({ kind: "slot-id", slotId: comp.slotId });
29897
+ const children = comp.children.length > 0 ? comp.children : resolveJsxChildrenProp(comp.props);
29898
+ if (children.length > 0)
29899
+ push({ kind: "children", children });
29900
+ return segments;
29901
+ }
29902
+ function spellComponentProps(segments, spelling) {
29903
+ return segments.map((segment) => {
29904
+ if (segment.kind === "spread")
29905
+ return { kind: "spread", expr: spelling.spread(segment.value) };
29906
+ const parts = [];
29907
+ for (const entry of segment.entries) {
29908
+ const part = spelling.entry(entry);
29909
+ if (part)
29910
+ parts.push(part);
29911
+ }
29912
+ return { kind: "entries", parts };
29913
+ });
29914
+ }
29915
+ function isEmptyComponentProps(segments) {
29916
+ return segments.every((segment) => segment.kind === "entries" && segment.parts.length === 0);
29917
+ }
29918
+ function childTemplateName(componentName, importAliases) {
29919
+ const declaredName = importAliases.get(componentName) ?? componentName;
29920
+ return declaredName.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
29921
+ }
29922
+ // src/nullable-signal-attr.ts
29923
+ function isNullishType(type) {
29924
+ return type.kind === "primitive" && (type.primitive === "undefined" || type.primitive === "null");
29925
+ }
29926
+ function admitsNullish(type) {
29927
+ if (isNullishType(type))
29928
+ return true;
29929
+ return type.kind === "union" && (type.unionTypes ?? []).some(isNullishType);
29930
+ }
29931
+ function isNullishLiteral(expr) {
29932
+ if (!expr)
29933
+ return false;
29934
+ if (expr.kind === "identifier")
29935
+ return expr.name === "undefined";
29936
+ return expr.kind === "literal" && expr.literalType === "null";
29937
+ }
29938
+ function isNullableSignal(signal) {
29939
+ if (admitsNullish(signal.type))
29940
+ return true;
29941
+ return signal.type.kind === "unknown" && isNullishLiteral(signal.parsed);
29942
+ }
29943
+ function collectNullableSignalGetters(ir) {
29944
+ return new Set((ir.metadata.signals ?? []).filter(isNullableSignal).map((s) => s.getter));
29945
+ }
29946
+ function bareGetterCallName(parsed) {
29947
+ if (!parsed || parsed.kind !== "call" || parsed.args.length !== 0)
29948
+ return null;
29949
+ return parsed.callee.kind === "identifier" ? parsed.callee.name : null;
29950
+ }
29951
+ function nullableSignalAttrGetter(parsed, nullable) {
29952
+ const getter = bareGetterCallName(parsed);
29953
+ return getter !== null && nullable.has(getter) ? getter : null;
29954
+ }
29955
+ function collectNullishAttrContext(ir) {
29956
+ const signals = ir.metadata.signals ?? [];
29957
+ return {
29958
+ nullableSignals: collectNullableSignalGetters(ir),
29959
+ nullSeededSignals: new Set(signals.filter((s) => s.parsed?.kind === "literal" && s.parsed.literalType === "null").map((s) => s.getter)),
29960
+ undefinedSeededSignals: new Set(signals.filter((s) => s.parsed?.kind === "identifier" && s.parsed.name === "undefined").map((s) => s.getter)),
29961
+ memos: new Map((ir.metadata.memos ?? []).map((m) => [m.name, m])),
29962
+ nullableNumberProps: collectNullableNumberProps(ir)
29963
+ };
29964
+ }
29965
+ function isNullableNumberType(type, optional2) {
29966
+ if (!type)
29967
+ return false;
29968
+ const members = type.kind === "union" ? type.unionTypes ?? [] : [type];
29969
+ const families = new Set(members.map((m) => m.kind === "primitive" ? m.primitive : m.kind));
29970
+ const nullable = optional2 || families.has("null") || families.has("undefined");
29971
+ families.delete("null");
29972
+ families.delete("undefined");
29973
+ return nullable && families.size === 1 && families.has("number");
29974
+ }
29975
+ function collectNullableNumberProps(ir) {
29976
+ const names = new Set;
29977
+ const objectName = ir.metadata.propsObjectName;
29978
+ for (const p of ir.metadata.propsParams) {
29979
+ if (p.isRest || p.defaultValue !== undefined || !isNullableNumberType(p.type, p.optional))
29980
+ continue;
29981
+ names.add(objectName ? `${objectName}.${p.sourceName ?? p.name}` : p.name);
29982
+ }
29983
+ return names;
29984
+ }
29985
+ function attrValueMayBeNullish(parsed, ctx, isShadowed = () => false) {
29986
+ const visiting = new Set;
29987
+ const walk = (expr, shadowed) => {
29988
+ switch (expr.kind) {
29989
+ case "identifier":
29990
+ return expr.name === "undefined";
29991
+ case "literal":
29992
+ return expr.literalType === "null";
29993
+ case "call": {
29994
+ const getter = bareGetterCallName(expr);
29995
+ if (getter === null || shadowed(getter))
29996
+ return false;
29997
+ if (ctx.nullableSignals.has(getter))
29998
+ return true;
29999
+ const memo = ctx.memos.get(getter);
30000
+ if (!memo || visiting.has(getter))
30001
+ return false;
30002
+ if (admitsNullish(memo.type))
30003
+ return true;
30004
+ visiting.add(getter);
30005
+ const result = memo.parsed !== undefined && walk(memo.parsed, () => false);
30006
+ visiting.delete(getter);
30007
+ return result;
30008
+ }
30009
+ case "member":
30010
+ return expr.optional || walk(expr.object, shadowed);
30011
+ case "index-access":
30012
+ return walk(expr.object, shadowed);
30013
+ case "conditional":
30014
+ return walk(expr.consequent, shadowed) || walk(expr.alternate, shadowed);
30015
+ case "logical":
30016
+ return expr.op === "&&" ? walk(expr.left, shadowed) || walk(expr.right, shadowed) : walk(expr.right, shadowed);
30017
+ default:
30018
+ return false;
30019
+ }
30020
+ };
30021
+ return parsed !== undefined && walk(parsed, isShadowed);
30022
+ }
30023
+ function arithmeticOperandIsNull(parsed, ctx, isShadowed = () => false) {
30024
+ return arithmeticOperandSeed(parsed, ctx, isShadowed) === "null";
30025
+ }
30026
+ function arithmeticOperandIsUndefined(parsed, ctx, isShadowed = () => false) {
30027
+ return arithmeticOperandSeed(parsed, ctx, isShadowed) === "undefined";
30028
+ }
30029
+ function arithmeticOperandSeed(parsed, ctx, isShadowed) {
30030
+ const visiting = new Set;
30031
+ const walk = (expr, shadowed) => {
30032
+ if (expr.kind === "literal")
30033
+ return expr.literalType === "null" ? "null" : null;
30034
+ if (expr.kind === "identifier" && expr.name === "undefined" && !shadowed("undefined"))
30035
+ return "undefined";
30036
+ const prop = nullableNumberPropRead(expr, ctx, shadowed);
30037
+ if (prop)
30038
+ return "null";
30039
+ const getter = expr.kind === "identifier" ? expr.name : bareGetterCallName(expr);
30040
+ if (getter === null || shadowed(getter))
30041
+ return null;
30042
+ if (ctx.nullSeededSignals?.has(getter))
30043
+ return "null";
30044
+ if (ctx.undefinedSeededSignals?.has(getter))
30045
+ return "undefined";
30046
+ const memo = ctx.memos.get(getter);
30047
+ if (!memo?.parsed || visiting.has(getter))
30048
+ return null;
30049
+ visiting.add(getter);
30050
+ const result = walk(memo.parsed, () => false);
30051
+ visiting.delete(getter);
30052
+ return result;
30053
+ };
30054
+ return parsed === undefined ? null : walk(parsed, isShadowed);
30055
+ }
30056
+ function nullableNumberPropRead(expr, ctx, shadowed) {
30057
+ if (!ctx.nullableNumberProps?.size)
30058
+ return false;
30059
+ if (expr.kind === "identifier")
30060
+ return !shadowed(expr.name) && ctx.nullableNumberProps.has(expr.name);
30061
+ if (expr.kind === "member" && !expr.computed && expr.object.kind === "identifier" && !shadowed(expr.object.name)) {
30062
+ return ctx.nullableNumberProps.has(`${expr.object.name}.${expr.property}`);
30063
+ }
30064
+ return false;
30065
+ }
30066
+ var NULL_COERCING_ARITHMETIC_OPS = new Set(["-", "*", "/", "%", "**"]);
30067
+ function arithmeticOperandCoercion(op, operand, other, ctx, isShadowed = () => false) {
30068
+ const numeric = NULL_COERCING_ARITHMETIC_OPS.has(op) || op === "+" && isNumberLiteral(other);
30069
+ return numeric ? arithmeticOperandSeed(operand, ctx, isShadowed) : null;
30070
+ }
30071
+ function isNumberLiteral(expr) {
30072
+ if (expr?.kind === "unary" && expr.op === "-")
30073
+ return isNumberLiteral(expr.argument);
30074
+ return expr?.kind === "literal" && expr.literalType === "number";
30075
+ }
30076
+
30077
+ // src/adapters/attr-plan.ts
30078
+ var IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
30079
+ function unsupportedAttrExpression(expr, loweringMatchers) {
30080
+ let probe = expr.trim();
30081
+ while (probe.startsWith("("))
30082
+ probe = probe.slice(1).trimStart();
30083
+ const startsAsObjectLiteral = probe.startsWith("{");
30084
+ const hasTaggedTemplate = /[A-Za-z_$][\w$]*\s*`/.test(probe);
30085
+ if (!startsAsObjectLiteral && !hasTaggedTemplate)
30086
+ return null;
30087
+ const parsed = parseExpression(expr.trim());
30088
+ const support = isSupported(parsed, { loweringMatchers });
30089
+ if (parsed.kind !== "unsupported" && support.supported)
30090
+ return null;
30091
+ return { reason: support.reason ?? (parsed.kind === "unsupported" ? parsed.reason : undefined) };
30092
+ }
30093
+ function planAttrExpression(value, name, ctx) {
30094
+ const booleanAttr = isBooleanAttr(name);
30095
+ if (!booleanAttr && !value.presenceOrUndefined) {
30096
+ const nullable = nullableBareRead(value, ctx);
30097
+ if (nullable !== null)
30098
+ return { kind: "omit-nullable", boolStr: ctx.boolStr(value.expr, name), restKey: nullable.restKey };
30099
+ }
30100
+ if (booleanAttr)
30101
+ return { kind: "boolean-attr" };
30102
+ if (value.presenceOrUndefined)
30103
+ return { kind: "presence", boolStr: ctx.boolStr(value.expr, name) };
30104
+ const ternary = parseUndefinedAlternateTernary(value.expr);
30105
+ if (ternary)
30106
+ return { kind: "undefined-alternate", ternary };
30107
+ const boolStr = ctx.boolStr(value.expr, name);
30108
+ if (attrValueMayBeNullish(value.parsed, ctx.nullishAttrCtx, (n) => ctx.isLoopBound(n)))
30109
+ return { kind: "omit-nil", boolStr };
30110
+ return { kind: "plain", boolStr };
30111
+ }
30112
+ function nullableBareRead(value, ctx) {
30113
+ const bare = value.expr.trim();
30114
+ const restKey = ctx.restPropsName !== null && bare.startsWith(`${ctx.restPropsName}.`);
30115
+ let normalized = bare;
30116
+ if (ctx.propsObjectName && bare.startsWith(`${ctx.propsObjectName}.`))
30117
+ normalized = bare.slice(ctx.propsObjectName.length + 1);
30118
+ else if (restKey)
30119
+ normalized = bare.slice(ctx.restPropsName.length + 1);
30120
+ const prop = IDENTIFIER.test(normalized) && ctx.nullableOptionalProps.has(normalized) && !ctx.isLoopBound(normalized);
30121
+ const signal = nullableSignalAttrGetter(value.parsed, ctx.nullableSignalGetters);
30122
+ if (prop || signal !== null && !ctx.isLoopBound(signal))
30123
+ return { restKey };
30124
+ return null;
30125
+ }
30126
+ function parseUndefinedAlternateTernary(expr) {
30127
+ const parsed = parseExpression(expr.trim());
30128
+ if (parsed?.kind !== "conditional")
30129
+ return null;
30130
+ const alt = parsed.alternate;
30131
+ const isUndef = alt.kind === "identifier" && (alt.name === "undefined" || alt.name === "null") || alt.kind === "literal" && (alt.value === null || alt.value === undefined);
30132
+ if (!isUndef)
30133
+ return null;
30134
+ return {
30135
+ condition: exprToString(parsed.test),
30136
+ consequent: exprToString(parsed.consequent),
30137
+ testParsed: parsed.test,
30138
+ consequentParsed: parsed.consequent
30139
+ };
30140
+ }
30141
+ function planSpreadAttr(value, ctx) {
30142
+ const trimmed = value.expr.trim();
30143
+ if (ctx.propsObjectName && ctx.propsObjectName === trimmed) {
30144
+ return { kind: "props-object", params: ctx.propsParams.map((p) => p.name) };
30145
+ }
30146
+ const candidates = [value.parsed];
30147
+ const init = localConstInitializer(trimmed, ctx);
30148
+ if (init !== null)
30149
+ candidates.push(parseExpression(init));
30150
+ return { kind: "value", candidates };
30151
+ }
30152
+ function localConstInitializer(name, ctx) {
30153
+ if (!IDENTIFIER.test(name) || ctx.isBound(name))
30154
+ return null;
30155
+ const init = ctx.localConstants.find((c) => c.name === name && !c.isModule)?.value?.trim();
30156
+ return init !== undefined && !IDENTIFIER.test(init) ? init : null;
30157
+ }
30158
+ // src/loop-destructure.ts
30159
+ function isLowerableLoopDestructure(loop) {
30160
+ const bindings = loop.paramBindings;
30161
+ if (!bindings || bindings.length === 0)
30162
+ return false;
30163
+ if (loop.filterPredicate)
30164
+ return false;
30165
+ for (const name of [...bindings.map((b) => b.name), loop.index]) {
30166
+ if (name && name.startsWith("__bf_"))
30167
+ return false;
30168
+ }
30169
+ for (const b of bindings) {
30170
+ if (b.rest) {
30171
+ if (!b.segments)
30172
+ return false;
30173
+ } else if (!b.segments || b.segments.length === 0) {
30174
+ return false;
30175
+ }
30176
+ }
30177
+ const objectRestNames = bindings.filter((b) => b.rest?.kind === "object").map((b) => b.name);
30178
+ if (objectRestNames.length === 0)
30179
+ return true;
30180
+ return !restNamesMisused(loop, objectRestNames);
30181
+ }
30182
+ var isLowerableObjectRestDestructure = isLowerableLoopDestructure;
30183
+ function restNamesMisused(loop, names) {
30184
+ const nameSet = new Set(names);
30185
+ const valueUse = names.map((n) => new RegExp(`(?<![\\w.$])${escapeRe(n)}(?!\\s*\\??\\.)(?![\\w$])`));
30186
+ let misused = false;
30187
+ const check = (s) => {
30188
+ if (!s || misused)
30189
+ return;
30190
+ for (const re of valueUse) {
30191
+ if (re.test(s)) {
30192
+ misused = true;
30193
+ return;
30194
+ }
30195
+ }
30196
+ };
30197
+ const attr = (v, isIntrinsicElementAttrs) => {
30198
+ if (v.kind === "spread" && isIntrinsicElementAttrs && nameSet.has(v.expr.trim())) {
30199
+ return;
30200
+ }
30201
+ if (v.kind === "expression" || v.kind === "spread") {
30202
+ check(v.expr);
30203
+ check(v.templateExpr);
30204
+ } else if (v.kind === "template") {
30205
+ v.parts.forEach(part);
30206
+ }
30207
+ };
30208
+ const part = (p) => {
30209
+ if (p.type === "ternary") {
30210
+ check(p.condition);
30211
+ check(p.templateCondition);
30212
+ check(p.whenTrue);
30213
+ check(p.whenFalse);
30214
+ } else if (p.type === "lookup") {
30215
+ check(p.key);
30216
+ check(p.templateKey);
30217
+ }
30218
+ };
30219
+ const visitLoop = (l) => {
30220
+ if (misused)
30221
+ return;
30222
+ check(l.array);
30223
+ check(l.templateArray);
30224
+ check(l.key);
30225
+ if (l.preamble) {
30226
+ check(preambleAnalysisText(l.preamble));
30227
+ check(preambleAnalysisTemplateText(l.preamble));
30228
+ }
30229
+ if (l.flatMapCallback) {
30230
+ check(preambleAnalysisText(l.flatMapCallback));
30231
+ for (const seg of l.flatMapCallback.segments) {
30232
+ if (seg.kind === "jsx")
30233
+ visit3(seg.ir);
30234
+ }
30235
+ }
30236
+ l.children.forEach(visit3);
30237
+ };
30238
+ const visit3 = (node) => {
30239
+ if (misused)
30240
+ return;
30241
+ switch (node.type) {
30242
+ case "expression":
30243
+ check(node.expr);
30244
+ check(node.templateExpr);
30245
+ break;
30246
+ case "conditional":
30247
+ check(node.condition);
30248
+ check(node.templateCondition);
30249
+ visit3(node.whenTrue);
30250
+ visit3(node.whenFalse);
30251
+ break;
30252
+ case "if-statement":
30253
+ check(node.condition);
30254
+ check(node.templateCondition);
30255
+ for (const sv of node.scopeVariables) {
30256
+ check(sv.initializer);
30257
+ check(sv.templateInitializer);
30258
+ }
30259
+ visit3(node.consequent);
30260
+ if (node.alternate)
30261
+ visit3(node.alternate);
30262
+ break;
30263
+ case "element":
30264
+ node.attrs.forEach((a) => attr(a.value, true));
30265
+ node.events.forEach((e) => check(e.handler));
30266
+ node.children.forEach(visit3);
30267
+ break;
30268
+ case "component":
30269
+ node.props.forEach((p) => attr(p.value, false));
30270
+ node.children.forEach(visit3);
30271
+ break;
30272
+ case "provider":
30273
+ attr(node.valueProp.value, false);
30274
+ node.children.forEach(visit3);
30275
+ break;
30276
+ case "fragment":
30277
+ node.children.forEach(visit3);
30278
+ break;
30279
+ case "async":
30280
+ visit3(node.fallback);
30281
+ node.children.forEach(visit3);
30282
+ break;
30283
+ case "loop":
30284
+ visitLoop(node);
30285
+ break;
30286
+ case "text":
30287
+ case "slot":
30288
+ break;
30289
+ }
30290
+ };
30291
+ visitLoop(loop);
30292
+ return misused;
30293
+ }
30294
+ function escapeRe(s) {
30295
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
30296
+ }
30297
+
30298
+ // src/static-literal.ts
30299
+ function evaluateStaticLiteral(expr, bindings) {
30300
+ switch (expr.kind) {
30301
+ case "literal":
30302
+ return { value: expr.value };
30303
+ case "template-literal": {
30304
+ let out = "";
30305
+ for (const part of expr.parts) {
30306
+ if (part.type === "string") {
30307
+ out += part.value;
30308
+ continue;
30309
+ }
30310
+ const resolved = evaluateStaticLiteral(part.expr, bindings);
30311
+ if (!resolved)
30312
+ return null;
30313
+ out += String(resolved.value);
30314
+ }
30315
+ return { value: out };
30316
+ }
30317
+ case "array-literal": {
30318
+ const values = [];
30319
+ for (const element of expr.elements) {
30320
+ const resolved = evaluateStaticLiteral(element, bindings);
30321
+ if (!resolved)
30322
+ return null;
30323
+ values.push(resolved.value);
30324
+ }
30325
+ return { value: values };
30326
+ }
30327
+ case "object-literal": {
30328
+ const out = {};
30329
+ for (const prop of expr.properties) {
30330
+ if (prop.kind === "spread") {
30331
+ const resolved2 = evaluateStaticLiteral(prop.expr, bindings);
30332
+ if (!resolved2)
30333
+ return null;
30334
+ if (resolved2.value === null || resolved2.value === undefined)
30335
+ continue;
30336
+ if (typeof resolved2.value !== "object" || Array.isArray(resolved2.value))
30337
+ return null;
30338
+ Object.assign(out, resolved2.value);
30339
+ continue;
30340
+ }
30341
+ const resolved = evaluateStaticLiteral(prop.value, bindings);
30342
+ if (!resolved)
30343
+ return null;
30344
+ out[prop.key] = resolved.value;
30345
+ }
30346
+ return { value: out };
30347
+ }
30348
+ case "unary": {
30349
+ const resolved = evaluateStaticLiteral(expr.argument, bindings);
30350
+ if (!resolved)
30351
+ return null;
30352
+ if (expr.op === "-")
30353
+ return typeof resolved.value === "number" ? { value: -resolved.value } : null;
30354
+ if (expr.op === "+")
30355
+ return typeof resolved.value === "number" ? { value: +resolved.value } : null;
30356
+ if (expr.op === "!")
30357
+ return { value: !resolved.value };
30358
+ return null;
30359
+ }
30360
+ case "identifier":
30361
+ return bindings?.has(expr.name) ? { value: bindings.get(expr.name) } : null;
30362
+ case "member": {
30363
+ const base = evaluateStaticLiteral(expr.object, bindings);
30364
+ if (!base || base.value === null || typeof base.value !== "object")
30365
+ return null;
30366
+ return { value: base.value[expr.property] };
30367
+ }
30368
+ case "index-access": {
30369
+ const base = evaluateStaticLiteral(expr.object, bindings);
30370
+ const index = evaluateStaticLiteral(expr.index, bindings);
30371
+ if (!base || !index || !Array.isArray(base.value) || typeof index.value !== "number")
30372
+ return null;
30373
+ return { value: base.value[index.value] };
30374
+ }
30375
+ default:
30376
+ return null;
30377
+ }
30378
+ }
30379
+ function isFullyStaticLiteral(expr) {
30380
+ return evaluateStaticLiteral(expr) !== null;
30381
+ }
30382
+ function resolveStaticLoopSource(arrayParsed, localConstants, opts) {
30383
+ if (!arrayParsed)
30384
+ return null;
30385
+ let target = arrayParsed;
30386
+ if (arrayParsed.kind === "identifier") {
30387
+ if (opts?.isNameShadowed?.(arrayParsed.name))
29353
30388
  return null;
29354
30389
  const local = localConstants?.find((c) => c.name === arrayParsed.name);
29355
30390
  if (!local?.parsed || local.mutatedAfterDeclaration)
@@ -29361,117 +30396,36 @@ function resolveStaticLoopSource(arrayParsed, localConstants, opts) {
29361
30396
  return null;
29362
30397
  return resolved.value;
29363
30398
  }
29364
- // src/nullable-signal-attr.ts
29365
- function isNullishType(type) {
29366
- return type.kind === "primitive" && (type.primitive === "undefined" || type.primitive === "null");
29367
- }
29368
- function admitsNullish(type) {
29369
- if (isNullishType(type))
29370
- return true;
29371
- return type.kind === "union" && (type.unionTypes ?? []).some(isNullishType);
29372
- }
29373
- function isNullishLiteral(expr) {
29374
- if (!expr)
29375
- return false;
29376
- if (expr.kind === "identifier")
29377
- return expr.name === "undefined";
29378
- return expr.kind === "literal" && expr.literalType === "null";
29379
- }
29380
- function isNullableSignal(signal) {
29381
- if (admitsNullish(signal.type))
29382
- return true;
29383
- return signal.type.kind === "unknown" && isNullishLiteral(signal.parsed);
29384
- }
29385
- function collectNullableSignalGetters(ir) {
29386
- return new Set((ir.metadata.signals ?? []).filter(isNullableSignal).map((s) => s.getter));
29387
- }
29388
- function bareGetterCallName(parsed) {
29389
- if (!parsed || parsed.kind !== "call" || parsed.args.length !== 0)
29390
- return null;
29391
- return parsed.callee.kind === "identifier" ? parsed.callee.name : null;
29392
- }
29393
- function nullableSignalAttrGetter(parsed, nullable) {
29394
- const getter = bareGetterCallName(parsed);
29395
- return getter !== null && nullable.has(getter) ? getter : null;
29396
- }
29397
- function collectNullishAttrContext(ir) {
29398
- const signals = ir.metadata.signals ?? [];
30399
+
30400
+ // src/adapters/loop-plan.ts
30401
+ function planLoop(loop, ctx) {
30402
+ const staticItems = resolveStaticLoopSource(loop.arrayParsed, ctx.localConstants, {
30403
+ isNameShadowed: ctx.scope.asShadowPredicate()
30404
+ });
30405
+ const staticSource = staticItems !== null ? ctx.spellStatic(staticItems) : null;
29399
30406
  return {
29400
- nullableSignals: collectNullableSignalGetters(ir),
29401
- nullSeededSignals: new Set(signals.filter((s) => s.parsed?.kind === "literal" && s.parsed.literalType === "null").map((s) => s.getter)),
29402
- undefinedSeededSignals: new Set(signals.filter((s) => s.parsed?.kind === "identifier" && s.parsed.name === "undefined").map((s) => s.getter)),
29403
- memos: new Map((ir.metadata.memos ?? []).map((m) => [m.name, m]))
29404
- };
29405
- }
29406
- function attrValueMayBeNullish(parsed, ctx, isShadowed = () => false) {
29407
- const visiting = new Set;
29408
- const walk = (expr, shadowed) => {
29409
- switch (expr.kind) {
29410
- case "identifier":
29411
- return expr.name === "undefined";
29412
- case "literal":
29413
- return expr.literalType === "null";
29414
- case "call": {
29415
- const getter = bareGetterCallName(expr);
29416
- if (getter === null || shadowed(getter))
29417
- return false;
29418
- if (ctx.nullableSignals.has(getter))
29419
- return true;
29420
- const memo = ctx.memos.get(getter);
29421
- if (!memo || visiting.has(getter))
29422
- return false;
29423
- if (admitsNullish(memo.type))
29424
- return true;
29425
- visiting.add(getter);
29426
- const result = memo.parsed !== undefined && walk(memo.parsed, () => false);
29427
- visiting.delete(getter);
29428
- return result;
29429
- }
29430
- case "member":
29431
- return expr.optional || walk(expr.object, shadowed);
29432
- case "index-access":
29433
- return walk(expr.object, shadowed);
29434
- case "conditional":
29435
- return walk(expr.consequent, shadowed) || walk(expr.alternate, shadowed);
29436
- case "logical":
29437
- return expr.op === "&&" ? walk(expr.left, shadowed) || walk(expr.right, shadowed) : walk(expr.right, shadowed);
29438
- default:
29439
- return false;
29440
- }
30407
+ destructure: destructureKind(loop),
30408
+ staticSource,
30409
+ unresolvableConst: staticSource === null ? unresolvableConst(loop, ctx) : null,
30410
+ sort: loop.sortComparator ? lowerCallbackMethod("sort", loop.sortComparator.arrow, [], ctx.callbackLowering) : null,
30411
+ captureAliases: filterCaptureCollisions(loop).map((name) => ({ name, alias: `__bf_cap_${loop.markerId}_${name}` }))
29441
30412
  };
29442
- return parsed !== undefined && walk(parsed, isShadowed);
29443
- }
29444
- function arithmeticOperandIsNull(parsed, ctx, isShadowed = () => false) {
29445
- return arithmeticOperandSeed(parsed, ctx, isShadowed) === "null";
29446
30413
  }
29447
- function arithmeticOperandIsUndefined(parsed, ctx, isShadowed = () => false) {
29448
- return arithmeticOperandSeed(parsed, ctx, isShadowed) === "undefined";
30414
+ function destructureKind(loop) {
30415
+ if (!loop.paramBindings || loop.paramBindings.length === 0)
30416
+ return "none";
30417
+ return isLowerableLoopDestructure(loop) ? "lowerable" : "unlowerable";
29449
30418
  }
29450
- function arithmeticOperandSeed(parsed, ctx, isShadowed) {
29451
- const visiting = new Set;
29452
- const walk = (expr, shadowed) => {
29453
- if (expr.kind === "literal")
29454
- return expr.literalType === "null" ? "null" : null;
29455
- if (expr.kind === "identifier" && expr.name === "undefined" && !shadowed("undefined"))
29456
- return "undefined";
29457
- const getter = expr.kind === "identifier" ? expr.name : bareGetterCallName(expr);
29458
- if (getter === null || shadowed(getter))
29459
- return null;
29460
- if (ctx.nullSeededSignals?.has(getter))
29461
- return "null";
29462
- if (ctx.undefinedSeededSignals?.has(getter))
29463
- return "undefined";
29464
- const memo = ctx.memos.get(getter);
29465
- if (!memo?.parsed || visiting.has(getter))
29466
- return null;
29467
- visiting.add(getter);
29468
- const result = walk(memo.parsed, () => false);
29469
- visiting.delete(getter);
29470
- return result;
29471
- };
29472
- return parsed === undefined ? null : walk(parsed, isShadowed);
30419
+ function unresolvableConst(loop, ctx) {
30420
+ const source = loop.arrayParsed ?? parseExpression(loop.array.trim());
30421
+ if (source?.kind !== "identifier")
30422
+ return null;
30423
+ const name = source.name;
30424
+ if (ctx.scope.isBound(name))
30425
+ return null;
30426
+ const constant = ctx.localConstants.find((c) => c.name === name);
30427
+ return constant && ctx.resolveLiteralConst(name) === null ? constant : null;
29473
30428
  }
29474
- var NULL_COERCING_ARITHMETIC_OPS = new Set(["-", "*", "/", "%", "**"]);
29475
30429
  // src/query-href-lowering.ts
29476
30430
  function matchQueryHrefCall(callee, args, localNames) {
29477
30431
  if (callee.kind !== "identifier" || !localNames.has(callee.name))
@@ -29801,145 +30755,6 @@ function literalMemberIndex(property) {
29801
30755
  }
29802
30756
  return { kind: "literal", value: property, literalType: "string" };
29803
30757
  }
29804
- // src/loop-destructure.ts
29805
- function isLowerableLoopDestructure(loop) {
29806
- const bindings = loop.paramBindings;
29807
- if (!bindings || bindings.length === 0)
29808
- return false;
29809
- if (loop.filterPredicate)
29810
- return false;
29811
- for (const name of [...bindings.map((b) => b.name), loop.index]) {
29812
- if (name && name.startsWith("__bf_"))
29813
- return false;
29814
- }
29815
- for (const b of bindings) {
29816
- if (b.rest) {
29817
- if (!b.segments)
29818
- return false;
29819
- } else if (!b.segments || b.segments.length === 0) {
29820
- return false;
29821
- }
29822
- }
29823
- const objectRestNames = bindings.filter((b) => b.rest?.kind === "object").map((b) => b.name);
29824
- if (objectRestNames.length === 0)
29825
- return true;
29826
- return !restNamesMisused(loop, objectRestNames);
29827
- }
29828
- var isLowerableObjectRestDestructure = isLowerableLoopDestructure;
29829
- function restNamesMisused(loop, names) {
29830
- const nameSet = new Set(names);
29831
- const valueUse = names.map((n) => new RegExp(`(?<![\\w.$])${escapeRe(n)}(?!\\s*\\??\\.)(?![\\w$])`));
29832
- let misused = false;
29833
- const check = (s) => {
29834
- if (!s || misused)
29835
- return;
29836
- for (const re of valueUse) {
29837
- if (re.test(s)) {
29838
- misused = true;
29839
- return;
29840
- }
29841
- }
29842
- };
29843
- const attr = (v, isIntrinsicElementAttrs) => {
29844
- if (v.kind === "spread" && isIntrinsicElementAttrs && nameSet.has(v.expr.trim())) {
29845
- return;
29846
- }
29847
- if (v.kind === "expression" || v.kind === "spread") {
29848
- check(v.expr);
29849
- check(v.templateExpr);
29850
- } else if (v.kind === "template") {
29851
- v.parts.forEach(part);
29852
- }
29853
- };
29854
- const part = (p) => {
29855
- if (p.type === "ternary") {
29856
- check(p.condition);
29857
- check(p.templateCondition);
29858
- check(p.whenTrue);
29859
- check(p.whenFalse);
29860
- } else if (p.type === "lookup") {
29861
- check(p.key);
29862
- check(p.templateKey);
29863
- }
29864
- };
29865
- const visitLoop = (l) => {
29866
- if (misused)
29867
- return;
29868
- check(l.array);
29869
- check(l.templateArray);
29870
- check(l.key);
29871
- if (l.preamble) {
29872
- check(preambleAnalysisText(l.preamble));
29873
- check(preambleAnalysisTemplateText(l.preamble));
29874
- }
29875
- if (l.flatMapCallback) {
29876
- check(preambleAnalysisText(l.flatMapCallback));
29877
- for (const seg of l.flatMapCallback.segments) {
29878
- if (seg.kind === "jsx")
29879
- visit3(seg.ir);
29880
- }
29881
- }
29882
- l.children.forEach(visit3);
29883
- };
29884
- const visit3 = (node) => {
29885
- if (misused)
29886
- return;
29887
- switch (node.type) {
29888
- case "expression":
29889
- check(node.expr);
29890
- check(node.templateExpr);
29891
- break;
29892
- case "conditional":
29893
- check(node.condition);
29894
- check(node.templateCondition);
29895
- visit3(node.whenTrue);
29896
- visit3(node.whenFalse);
29897
- break;
29898
- case "if-statement":
29899
- check(node.condition);
29900
- check(node.templateCondition);
29901
- for (const sv of node.scopeVariables) {
29902
- check(sv.initializer);
29903
- check(sv.templateInitializer);
29904
- }
29905
- visit3(node.consequent);
29906
- if (node.alternate)
29907
- visit3(node.alternate);
29908
- break;
29909
- case "element":
29910
- node.attrs.forEach((a) => attr(a.value, true));
29911
- node.events.forEach((e) => check(e.handler));
29912
- node.children.forEach(visit3);
29913
- break;
29914
- case "component":
29915
- node.props.forEach((p) => attr(p.value, false));
29916
- node.children.forEach(visit3);
29917
- break;
29918
- case "provider":
29919
- attr(node.valueProp.value, false);
29920
- node.children.forEach(visit3);
29921
- break;
29922
- case "fragment":
29923
- node.children.forEach(visit3);
29924
- break;
29925
- case "async":
29926
- visit3(node.fallback);
29927
- node.children.forEach(visit3);
29928
- break;
29929
- case "loop":
29930
- visitLoop(node);
29931
- break;
29932
- case "text":
29933
- case "slot":
29934
- break;
29935
- }
29936
- };
29937
- visitLoop(loop);
29938
- return misused;
29939
- }
29940
- function escapeRe(s) {
29941
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
29942
- }
29943
30758
  // src/scope/root-prop-alias.ts
29944
30759
  function rootPropAliasNames(ir, propNames) {
29945
30760
  const { metadata } = ir;
@@ -32818,6 +33633,9 @@ function profileToJSON(profile) {
32818
33633
  // src/index.ts
32819
33634
  registerBuiltinLoweringPlugins();
32820
33635
  export {
33636
+ unsupportedAttrExpression,
33637
+ unboundCallbackParamReason,
33638
+ unboundCallbackParamRead,
32821
33639
  tsNodeToParsedExpr,
32822
33640
  traceableNames,
32823
33641
  traceUpdatePath,
@@ -32825,6 +33643,9 @@ export {
32825
33643
  templateNameCollisionErrors,
32826
33644
  stringifyParsedExpr,
32827
33645
  stringifyBooleanTernaryBranches,
33646
+ spellComponentProps,
33647
+ sortRefusal,
33648
+ sortEvalPlan,
32828
33649
  sortComparatorFromArrow,
32829
33650
  serializeParsedExpr,
32830
33651
  searchParamsLocalNames,
@@ -32850,7 +33671,13 @@ export {
32850
33671
  propsDestructureBinding,
32851
33672
  profileToJSON,
32852
33673
  prepareLoweringMatchers,
33674
+ prefixedArrayMethodSpelling,
32853
33675
  predicateTernaryToLogical,
33676
+ planSpreadAttr,
33677
+ planLoop,
33678
+ planComponentProps,
33679
+ planAttrExpression,
33680
+ parseUndefinedAlternateTernary,
32854
33681
  parseStyleObjectEntries,
32855
33682
  parseRecordIndexAccess,
32856
33683
  parseProviderObjectLiteral,
@@ -32859,6 +33686,7 @@ export {
32859
33686
  parseBlockBodyTolerant,
32860
33687
  parseBlockBody,
32861
33688
  nullableSignalAttrGetter,
33689
+ nestedCallbackRefusal,
32862
33690
  needsTypeBasedDetection,
32863
33691
  materializeGetterCalls,
32864
33692
  matchSearchParamsMethodCall,
@@ -32866,6 +33694,8 @@ export {
32866
33694
  matchLoweringCall,
32867
33695
  makeIdCallRegex,
32868
33696
  loweringNodeChildren,
33697
+ lowerCallbackMethod,
33698
+ lowerArrayMethod,
32869
33699
  lookupStaticRecordLiteral,
32870
33700
  lookupLiteralConst,
32871
33701
  literalMemberIndex,
@@ -32878,24 +33708,35 @@ export {
32878
33708
  isSupportedValue,
32879
33709
  isSupported,
32880
33710
  isStringTypedOperand,
33711
+ isStringTypeInfo,
32881
33712
  isStringConcatBinary,
33713
+ isPredicateMethod,
32882
33714
  isOpaqueLocalAccessorName,
32883
33715
  isNumericArithmeticResult,
32884
33716
  isNullishLiteral,
32885
33717
  isNullableSignal,
32886
33718
  isLowerableObjectRestDestructure,
32887
33719
  isLowerableLoopDestructure,
33720
+ isLiteralIndex,
32888
33721
  isIdentifierName,
32889
33722
  isFunctionShapedExpression,
32890
33723
  isFullyStaticLiteral,
33724
+ isExplicitStringCall,
32891
33725
  isEventHandlerName,
33726
+ isEmptyComponentProps,
32892
33727
  isElidedFactoryGetter,
32893
33728
  isDangerousInnerHtmlAttr,
33729
+ isBooleanTypedPropRef,
32894
33730
  isBooleanResultParsed,
33731
+ isBooleanResultExpr,
32895
33732
  isBooleanAttr,
33733
+ isBareStringLiteral,
33734
+ isAriaBooleanAttr,
32896
33735
  importsSearchParams,
32897
33736
  identifierPath,
32898
33737
  hasUnsafeStyleValue,
33738
+ hasOpaqueCall,
33739
+ hasClientInteractivity,
32899
33740
  groupObjectLiteralSegments,
32900
33741
  groupBinaryOperand,
32901
33742
  graphToJSON,
@@ -32944,7 +33785,9 @@ export {
32944
33785
  enableCompilerInstrumentation,
32945
33786
  emitParsedExpr,
32946
33787
  emitIRNode,
33788
+ emitCallbackEval,
32947
33789
  emitAttrValue,
33790
+ emitArrayMethod,
32948
33791
  disableCompilerInstrumentation,
32949
33792
  diffStaticBudget,
32950
33793
  diffProfiles,
@@ -32960,15 +33803,21 @@ export {
32960
33803
  createAnchoredProgram,
32961
33804
  containsHigherOrder,
32962
33805
  computeSsrSeedPlan,
33806
+ componentPropKey,
32963
33807
  compileJSX,
32964
33808
  combineParentChildClientJs,
32965
33809
  collectValueReferencedNames,
32966
33810
  collectNullishAttrContext,
32967
33811
  collectNullableSignalGetters,
33812
+ collectNullableOptionalProps,
32968
33813
  collectModuleStringConsts,
32969
33814
  collectLoopBoundNames,
33815
+ collectImportedLoopChildComponentErrors,
32970
33816
  collectContextConsumers,
33817
+ collectBooleanValueNames,
33818
+ collectBooleanTypedProps,
32971
33819
  collectAliasableGetterNames,
33820
+ childTemplateName,
32972
33821
  buildWhyUpdate,
32973
33822
  buildStaticBudget,
32974
33823
  buildSourceMapFromIR,
@@ -32993,6 +33842,7 @@ export {
32993
33842
  asCallbackMethodCall,
32994
33843
  arithmeticOperandIsUndefined,
32995
33844
  arithmeticOperandIsNull,
33845
+ arithmeticOperandCoercion,
32996
33846
  applyCssLayerPrefix,
32997
33847
  analyzeWastedReReruns,
32998
33848
  analyzeHotSubscribers,
@@ -33023,5 +33873,6 @@ export {
33023
33873
  BROWSER_ONLY_CLIENT_APIS,
33024
33874
  BOOLEAN_ATTRS,
33025
33875
  AttrValueOf,
33026
- ARRAY_METHOD_NAMES
33876
+ ARRAY_METHOD_NAMES,
33877
+ ARRAY_METHOD_CATALOGUE
33027
33878
  };