Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 | 2x 2x 2x 2x 2x 69x 39x 4956x 4371x 767x 3604x 196x 16x 180x 180x 180x 180x 180x 180x 180x 180x 110x 69x 69x 69x 69x 69x 70x 70x 54x 30x 30x 30x 16x 16x 16x 16x 10x 10x 10x 10x 10x 10x 10x 20x 20x 10x 20x 20x 20x 10x 149x 62x 62x 62x 62x 1061x 1061x 1061x 41x 41x 41x 1020x 1020x 1020x 1020x 1020x 108x 108x 200x 1020x 244x 493x 493x 493x 1020x 1020x 11x 1020x 81x 1020x 1020x 16x 32x 32x 3638x 3638x 3638x 3314x 324x 324x 324x 324x 324x 1x 324x 1x 324x 61x 86x 40x 1x 1x 324x 324x 297x 527x 27x 324x 830x 830x 830x 830x 787x 689x 787x 1528x 6x 787x 1602x 1602x 1x 1601x 1x 1600x 43x 28x 54x 15x 39x 39x 830x 3802x 3802x 3802x 3802x 3x 3x 3799x 3799x 3799x 70x 140x 70x 1x 69x 70x 3729x 3729x 52x 3x 52x 3677x 3677x 57x 39x 2x 39x 3638x 3638x 3638x 3638x 1741x 2x 2x 1739x 1739x 1739x 1739x 1x 1739x 2x 1739x 104x 104x 4x 1739x 1739x 1897x 349x 349x 349x 349x 349x 349x 2x 349x 8x 349x 1548x 189x 189x 189x 189x 189x 189x 189x 1359x 199x 199x 1160x 324x 324x 324x 836x 830x 830x 830x 6x 6x 6x 6x 6x 6x 1055x 127x 127x 4x 4x 123x 120x 123x 928x 928x 6x 6x 922x 38x 83x 1x 1x 82x 82x 2x 2x 80x 80x 80x 3x 80x 80x 80x 117x 117x 117x 73x 73x 73x 100x 73x 70x 124x 124x 124x 1x 1x 123x 4x 1x 4x 119x 119x 119x 119x 3x 44x 32x 30x 18x 30x 7x 7x 331x 427x 70x 668x 427x 11x 427x 3x 3x 3x 3x 3x 6x 3x 3x 6x 3x 6x 3x 2x 93x 93x 93x 93x 93x 93x 93x 582x 93x 3x 3x 3x 93x 93x 93x 6x 93x 332x 428x 332x 332x 332x 93x 93x 171x 1x 93x 3x 93x 93x 183x 168x 83x 2x 406x 406x 406x 406x 1x 1x 405x 82x 82x 82x 1x 82x 82x 323x 323x 323x 116x 55x 166x 3x 6x 3x 166x 166x 166x 55x 116x 166x 121x 121x 406x 406x 83x 83x 3x 80x 406x 406x 7x 406x 323x 323x 323x 323x 406x 2x 406x 406x 6x 166x 55x 116x 44x 380x 116x 27x 166x 166x 332x 331x 332x 32x 93x | import type { Schema, SchemaType } from "@featurevisor/types";
import { z } from "zod";
import { ProjectConfig } from "../config";
import { isMutationKey, validateMutationKey } from "./mutationNotation";
import {
valueZodSchema,
propertyTypeEnum,
getSchemaZodSchema,
refineEnumMatchesType,
refineMinimumMaximum,
refineStringLengthPattern,
refineArrayItems,
} from "./schema";
import { refineWithMessage } from "./zodHelpers";
const tagRegex = /^[a-z0-9-]+$/;
function isArrayOfStrings(value: unknown): value is string[] {
return Array.isArray(value) && value.every((v) => typeof v === "string");
}
function isFlatObjectValue(value: unknown): boolean {
return (
value === null ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
);
}
function getVariableLabel(variableSchema, variableKey, path) {
return (
variableKey ??
variableSchema?.key ??
(path.length > 0 ? String(path[path.length - 1]) : "variable")
);
}
/**
* Resolve variable schema to the Schema used for value validation.
* When variable has `schema` (reference), returns the parsed Schema from schemasByKey; otherwise returns the inline variable schema.
*/
function resolveVariableSchema(
variableSchema: {
schema?: string;
type?: string;
items?: unknown;
properties?: unknown;
additionalProperties?: unknown;
required?: string[];
enum?: unknown[];
const?: unknown;
oneOf?: unknown[];
minimum?: number;
maximum?: number;
minLength?: number;
maxLength?: number;
pattern?: string;
minItems?: number;
maxItems?: number;
uniqueItems?: boolean;
},
schemasByKey?: Record<string, Schema>,
): {
type?: string;
items?: unknown;
properties?: unknown;
additionalProperties?: unknown;
required?: string[];
enum?: unknown[];
const?: unknown;
oneOf?: unknown[];
minimum?: number;
maximum?: number;
minLength?: number;
maxLength?: number;
pattern?: string;
minItems?: number;
maxItems?: number;
uniqueItems?: boolean;
} | null {
if (variableSchema.schema) {
return schemasByKey?.[variableSchema.schema] ?? null;
}
return variableSchema as {
type?: string;
items?: unknown;
properties?: unknown;
additionalProperties?: unknown;
required?: string[];
enum?: unknown[];
const?: unknown;
oneOf?: unknown[];
minimum?: number;
maximum?: number;
minLength?: number;
maxLength?: number;
pattern?: string;
minItems?: number;
maxItems?: number;
uniqueItems?: boolean;
};
}
/** Resolve a schema by following schema references (schema: key). Used for nested schemas that may have oneOf. */
function resolveSchemaRefs(
schema: { schema?: string; [k: string]: unknown },
schemasByKey?: Record<string, Schema>,
): { [k: string]: unknown } {
if (schema.schema && schemasByKey?.[schema.schema]) {
return resolveSchemaRefs(
schemasByKey[schema.schema] as { schema?: string; [k: string]: unknown },
schemasByKey,
);
}
return schema;
}
/**
* Returns true if the value matches the given schema (const, enum, type, object properties, array items, or exactly one of oneOf).
* Used for oneOf validation: value must match exactly one branch.
*/
function valueMatchesSchema(
schema: { [k: string]: unknown },
value: unknown,
schemasByKey?: Record<string, Schema>,
): boolean {
const resolved = resolveSchemaRefs(schema, schemasByKey) as {
type?: string;
const?: unknown;
enum?: unknown[];
oneOf?: unknown[];
properties?: Record<string, unknown>;
additionalProperties?: unknown;
required?: string[];
items?: unknown;
minimum?: number;
maximum?: number;
minLength?: number;
maxLength?: number;
pattern?: string;
minItems?: number;
maxItems?: number;
uniqueItems?: boolean;
};
Iif (resolved.oneOf && Array.isArray(resolved.oneOf) && resolved.oneOf.length > 0) {
const matchCount = resolved.oneOf.filter((branch) =>
valueMatchesSchema(branch as { [k: string]: unknown }, value, schemasByKey),
).length;
return matchCount === 1;
}
Iif (resolved.const !== undefined) {
return valueDeepEqual(value, resolved.const);
}
Iif (resolved.enum !== undefined && Array.isArray(resolved.enum)) {
return resolved.enum.some((e) => valueDeepEqual(value, e));
}
const type = resolved.type;
Iif (!type) return false;
if (type === "string") {
if (typeof value !== "string") return false;
const s = value as string;
Iif (resolved.minLength !== undefined && s.length < resolved.minLength) return false;
Iif (resolved.maxLength !== undefined && s.length > resolved.maxLength) return false;
Iif (resolved.pattern !== undefined) {
try {
Iif (!new RegExp(resolved.pattern).test(s)) return false;
} catch {
return true;
}
}
return true;
}
Iif (type === "boolean") return typeof value === "boolean";
if (type === "integer") {
if (typeof value !== "number" || !Number.isInteger(value)) return false;
Iif (resolved.minimum !== undefined && (value as number) < resolved.minimum) return false;
Iif (resolved.maximum !== undefined && (value as number) > resolved.maximum) return false;
return true;
}
Iif (type === "double") {
Iif (typeof value !== "number") return false;
Iif (resolved.minimum !== undefined && (value as number) < resolved.minimum) return false;
Iif (resolved.maximum !== undefined && (value as number) > resolved.maximum) return false;
return true;
}
Iif (type === "json") return typeof value === "string";
if (type === "object") {
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
const props = resolved.properties;
const additional = resolved.additionalProperties;
const obj = value as Record<string, unknown>;
Iif ((!props || typeof props !== "object") && (!additional || typeof additional !== "object")) {
return true;
}
Iif (!props || typeof props !== "object") {
return Object.keys(obj).every((key) =>
valueMatchesSchema(additional as { [k: string]: unknown }, obj[key], schemasByKey),
);
}
const required = new Set(resolved.required || []);
for (const key of required) {
Iif (!Object.prototype.hasOwnProperty.call(obj, key)) return false;
Iif (!valueMatchesSchema(props[key] as { [k: string]: unknown }, obj[key], schemasByKey))
return false;
}
for (const key of Object.keys(obj)) {
const propSchema = props[key];
if (propSchema) {
Iif (!valueMatchesSchema(propSchema as { [k: string]: unknown }, obj[key], schemasByKey))
return false;
} else Eif (additional && typeof additional === "object") {
Iif (!valueMatchesSchema(additional as { [k: string]: unknown }, obj[key], schemasByKey))
return false;
} else {
return false;
}
}
return true;
}
Iif (type === "array") {
Iif (!Array.isArray(value)) return false;
const arr = value as unknown[];
Iif (resolved.minItems !== undefined && arr.length < resolved.minItems) return false;
Iif (resolved.maxItems !== undefined && arr.length > resolved.maxItems) return false;
Iif (resolved.uniqueItems) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
Iif (valueDeepEqual(arr[i], arr[j])) return false;
}
}
}
const itemSchema = resolved.items;
Iif (!itemSchema || typeof itemSchema !== "object")
return arr.every((v) => typeof v === "string");
return arr.every((item) =>
valueMatchesSchema(itemSchema as { [k: string]: unknown }, item, schemasByKey),
);
}
return false;
}
/** Deep equality for variable values (primitives, plain objects, arrays). */
function valueDeepEqual(a: unknown, b: unknown): boolean {
if (a === b) return true;
Iif (typeof a !== typeof b) return false;
Iif (a === null || b === null) return a === b;
Iif (typeof a === "object" && typeof b === "object") {
Iif (Array.isArray(a) !== Array.isArray(b)) return false;
Iif (Array.isArray(a) && Array.isArray(b)) {
Iif (a.length !== b.length) return false;
return a.every((v, i) => valueDeepEqual(v, b[i]));
}
const keysA = Object.keys(a as object).sort();
const keysB = Object.keys(b as object).sort();
Iif (keysA.length !== keysB.length || keysA.some((k, i) => k !== keysB[i])) return false;
return keysA.every((k) =>
valueDeepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),
);
}
return false;
}
type SchemaLikeForRequired = {
type?: string;
properties?: Record<string, unknown>;
additionalProperties?: unknown;
required?: string[];
items?: unknown;
schema?: string;
oneOf?: unknown[];
};
/**
* Recursively validates that every `required` array (at this level and in nested
* object/array schemas) only contains keys that exist in the same level's `properties`.
* Adds Zod issues with the correct path for invalid required field names.
* When schemasByKey is provided, resolves schema references (schema: key) so that
* referenced and nested schemas are validated too.
*/
function refineRequiredKeysInSchema(
schema: SchemaLikeForRequired,
pathPrefix: (string | number)[],
ctx: z.RefinementCtx,
schemasByKey?: Record<string, Schema>,
): void {
Iif (!schema || typeof schema !== "object") return;
// Resolve schema reference so we validate the referenced schema (and can recurse into it)
let current: SchemaLikeForRequired = schema;
if (schema.schema && schemasByKey?.[schema.schema]) {
current = schemasByKey[schema.schema] as SchemaLikeForRequired;
refineRequiredKeysInSchema(current, pathPrefix, ctx, schemasByKey);
return;
}
const effectiveType = current.type;
const properties = current.properties;
const required = current.required;
const items = current.items;
if (
effectiveType === "object" &&
Array.isArray(required) &&
required.length > 0 &&
properties &&
typeof properties === "object"
) {
const allowedKeys = Object.keys(properties);
required.forEach((key, index) => {
Iif (!allowedKeys.includes(key)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Unknown required field "${key}". \`required\` must only contain property names defined in \`properties\`. Allowed: ${allowedKeys.length ? allowedKeys.join(", ") : "(none)"}.`,
path: [...pathPrefix, "required", index],
});
}
});
}
if (properties && typeof properties === "object") {
for (const key of Object.keys(properties)) {
const nested = properties[key];
if (nested && typeof nested === "object") {
refineRequiredKeysInSchema(
nested as SchemaLikeForRequired,
[...pathPrefix, "properties", key],
ctx,
schemasByKey,
);
}
}
}
const additionalProperties = (current as { additionalProperties?: unknown }).additionalProperties;
if (
additionalProperties &&
typeof additionalProperties === "object" &&
!Array.isArray(additionalProperties)
) {
refineRequiredKeysInSchema(
additionalProperties as SchemaLikeForRequired,
[...pathPrefix, "additionalProperties"],
ctx,
schemasByKey,
);
}
if (items && typeof items === "object" && !Array.isArray(items)) {
refineRequiredKeysInSchema(
items as SchemaLikeForRequired,
[...pathPrefix, "items"],
ctx,
schemasByKey,
);
}
const oneOf = (current as { oneOf?: unknown[] }).oneOf;
if (oneOf && Array.isArray(oneOf)) {
oneOf.forEach((branch, i) => {
if (branch && typeof branch === "object") {
refineRequiredKeysInSchema(
branch as SchemaLikeForRequired,
[...pathPrefix, "oneOf", i],
ctx,
schemasByKey,
);
}
});
}
}
function typeOfValue(value: unknown): string {
Iif (value === null) return "null";
Iif (value === undefined) return "undefined";
if (Array.isArray(value)) return "array";
return typeof value;
}
/**
* Validates a variable value against an array schema. Recursively validates each item
* when the schema defines `items` (nested arrays/objects use the same refinement).
* Enforces minItems, maxItems, and uniqueItems when set.
*/
function refineVariableValueArray(
projectConfig: ProjectConfig,
variableSchema: {
items?: unknown;
type: string;
minItems?: number;
maxItems?: number;
uniqueItems?: boolean;
},
variableValue: unknown[],
path: (string | number)[],
ctx: z.RefinementCtx,
variableKey?: string,
schemasByKey?: Record<string, Schema>,
): void {
const label = getVariableLabel(variableSchema, variableKey, path);
const minItems = variableSchema.minItems;
const maxItems = variableSchema.maxItems;
const uniqueItems = variableSchema.uniqueItems;
if (minItems !== undefined && variableValue.length < minItems) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type array) length (${variableValue.length}) is less than \`minItems\` (${minItems}).`,
path,
});
}
if (maxItems !== undefined && variableValue.length > maxItems) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type array) length (${variableValue.length}) is greater than \`maxItems\` (${maxItems}).`,
path,
});
}
if (uniqueItems) {
for (let i = 0; i < variableValue.length; i++) {
for (let j = i + 1; j < variableValue.length; j++) {
if (valueDeepEqual(variableValue[i], variableValue[j])) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type array) has duplicate items at indices ${i} and ${j} but \`uniqueItems\` is true.`,
path,
});
break;
}
}
}
}
const itemSchema = variableSchema.items;
if (itemSchema) {
variableValue.forEach((item, index) => {
superRefineVariableValue(
projectConfig,
itemSchema,
item,
[...path, index],
ctx,
variableKey,
schemasByKey,
);
});
} else {
Iif (!isArrayOfStrings(variableValue)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type array): when \`items\` is not set, array must contain only strings; found non-string element.`,
path,
});
}
}
Iif (projectConfig.maxVariableArrayStringifiedLength) {
const stringified = JSON.stringify(variableValue);
Iif (stringified.length > projectConfig.maxVariableArrayStringifiedLength) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" array is too long (${stringified.length} characters), max length is ${projectConfig.maxVariableArrayStringifiedLength}`,
path,
});
}
}
}
/**
* Validates a variable value against an object schema. Recursively validates each property
* when the schema defines `properties` (nested objects/arrays use the same refinement).
*/
function refineVariableValueObject(
projectConfig: ProjectConfig,
variableSchema: {
properties?: Record<string, unknown>;
additionalProperties?: unknown;
required?: string[];
type: string;
},
variableValue: Record<string, unknown>,
path: (string | number)[],
ctx: z.RefinementCtx,
variableKey?: string,
schemasByKey?: Record<string, Schema>,
): void {
const label = getVariableLabel(variableSchema, variableKey, path);
const schemaProperties = variableSchema.properties;
const additionalProperties = variableSchema.additionalProperties;
if (schemaProperties && typeof schemaProperties === "object") {
const requiredKeys =
variableSchema.required && variableSchema.required.length > 0
? variableSchema.required.filter((k) =>
Object.prototype.hasOwnProperty.call(schemaProperties, k),
)
: Object.keys(schemaProperties);
for (const key of requiredKeys) {
if (!Object.prototype.hasOwnProperty.call(variableValue, key)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Missing required property "${key}" in variable "${label}"`,
path: [...path, key],
});
}
}
for (const key of Object.keys(variableValue)) {
const propSchema = schemaProperties[key];
if (!propSchema && additionalProperties && typeof additionalProperties === "object") {
superRefineVariableValue(
projectConfig,
additionalProperties as Parameters<typeof superRefineVariableValue>[1],
variableValue[key],
[...path, key],
ctx,
key,
schemasByKey,
);
} else if (!propSchema) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Unknown property "${key}" in variable "${label}" (not in schema)`,
path: [...path, key],
});
} else {
superRefineVariableValue(
projectConfig,
propSchema,
variableValue[key],
[...path, key],
ctx,
key,
schemasByKey,
);
}
}
} else if (additionalProperties && typeof additionalProperties === "object") {
for (const key of Object.keys(variableValue)) {
superRefineVariableValue(
projectConfig,
additionalProperties as Parameters<typeof superRefineVariableValue>[1],
variableValue[key],
[...path, key],
ctx,
key,
schemasByKey,
);
}
} else {
for (const key of Object.keys(variableValue)) {
const propValue = variableValue[key];
Iif (!isFlatObjectValue(propValue)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" is a flat object (no \`properties\` in schema); property "${key}" must be a primitive (string, number, boolean, or null), got: ${typeof propValue}`,
path: [...path, key],
});
}
}
}
Iif (projectConfig.maxVariableObjectStringifiedLength) {
const stringified = JSON.stringify(variableValue);
Iif (stringified.length > projectConfig.maxVariableObjectStringifiedLength) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" object is too long (${stringified.length} characters), max length is ${projectConfig.maxVariableObjectStringifiedLength}`,
path,
});
}
}
}
/** Schema or variable schema (e.g. type "json", defaultValue); used for value validation. */
type VariableSchemaLike =
| (Omit<Schema, "type"> & { type?: SchemaType | "json" })
| null
| undefined;
function superRefineVariableValue(
projectConfig: ProjectConfig,
variableSchema: VariableSchemaLike,
variableValue: unknown,
path: (string | number)[],
ctx: z.RefinementCtx,
variableKey?: string,
schemasByKey?: Record<string, Schema>,
): void {
const label = getVariableLabel(variableSchema, variableKey, path);
Iif (!variableSchema) {
const variableName =
path.length > 0 && typeof path[path.length - 1] === "string"
? String(path[path.length - 1])
: "variable";
const message = `Variable "${variableName}" is used but not defined in variablesSchema. Define it under variablesSchema first, then use it here.`;
ctx.addIssue({
code: z.ZodIssueCode.custom,
message,
path,
});
return;
}
const effectiveSchema = resolveVariableSchema(variableSchema, schemasByKey);
if (variableSchema.schema && effectiveSchema === null) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Schema "${variableSchema.schema}" could not be loaded for value validation.`,
path,
});
return;
}
Iif (!effectiveSchema) {
return;
}
const effectiveOneOf = (effectiveSchema as { oneOf?: unknown[] }).oneOf;
if (effectiveOneOf !== undefined && Array.isArray(effectiveOneOf) && effectiveOneOf.length > 0) {
const matchCount = effectiveOneOf.filter((branch) =>
valueMatchesSchema(branch as { [k: string]: unknown }, variableValue, schemasByKey),
).length;
if (matchCount === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" must match exactly one of the \`oneOf\` schemas (got ${JSON.stringify(variableValue)}; matched none).`,
path,
});
} else Iif (matchCount > 1) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" must match exactly one of the \`oneOf\` schemas (matched ${matchCount}).`,
path,
});
}
return;
}
const effectiveConst = (effectiveSchema as { const?: unknown }).const;
if (effectiveConst !== undefined) {
if (!valueDeepEqual(variableValue, effectiveConst)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" must equal the constant value defined in schema (got ${JSON.stringify(variableValue)}).`,
path,
});
}
return;
}
const effectiveEnum = (effectiveSchema as { enum?: unknown[] }).enum;
if (effectiveEnum !== undefined && Array.isArray(effectiveEnum) && effectiveEnum.length > 0) {
const allowed = effectiveEnum.some((v) => valueDeepEqual(variableValue, v));
if (!allowed) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" must be one of the allowed enum values (got ${JSON.stringify(variableValue)}).`,
path,
});
}
return;
}
// Require a value (no undefined) for every variable usage
Iif (variableValue === undefined) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" value is required (got undefined).`,
path,
});
return;
}
const expectedType = effectiveSchema.type;
const gotType = typeOfValue(variableValue);
// string — only string allowed; schema minLength/maxLength/pattern applied when set
if (expectedType === "string") {
if (typeof variableValue !== "string") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type string) must be a string; got ${gotType}.`,
path,
});
return;
}
const strMinLen = (effectiveSchema as { minLength?: number }).minLength;
const strMaxLen = (effectiveSchema as { maxLength?: number }).maxLength;
const strPattern = (effectiveSchema as { pattern?: string }).pattern;
if (strMinLen !== undefined && variableValue.length < strMinLen) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type string) length (${variableValue.length}) is less than \`minLength\` (${strMinLen}).`,
path,
});
}
if (strMaxLen !== undefined && variableValue.length > strMaxLen) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type string) length (${variableValue.length}) is greater than \`maxLength\` (${strMaxLen}).`,
path,
});
}
if (strPattern !== undefined) {
try {
if (!new RegExp(strPattern).test(variableValue)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type string) does not match \`pattern\`.`,
path,
});
}
} catch {
// invalid regex already reported at schema parse time
}
}
Iif (
projectConfig.maxVariableStringLength &&
variableValue.length > projectConfig.maxVariableStringLength
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" value is too long (${variableValue.length} characters), max length is ${projectConfig.maxVariableStringLength}`,
path,
});
}
return;
}
// integer — only integer number allowed (no NaN, no Infinity, no float)
if (expectedType === "integer") {
Iif (typeof variableValue !== "number") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type integer) must be a number; got ${gotType}.`,
path,
});
return;
}
Iif (!Number.isFinite(variableValue)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type integer) must be a finite number; got ${variableValue}.`,
path,
});
return;
}
Iif (!Number.isInteger(variableValue)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type integer) must be an integer; got ${variableValue}.`,
path,
});
return;
}
const intMin = (effectiveSchema as { minimum?: number }).minimum;
const intMax = (effectiveSchema as { maximum?: number }).maximum;
if (intMin !== undefined && variableValue < intMin) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type integer) must be >= minimum (${intMin}); got ${variableValue}.`,
path,
});
}
if (intMax !== undefined && variableValue > intMax) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type integer) must be <= maximum (${intMax}); got ${variableValue}.`,
path,
});
}
return;
}
// double — only finite number allowed
if (expectedType === "double") {
Iif (typeof variableValue !== "number") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type double) must be a number; got ${gotType}.`,
path,
});
return;
}
Iif (!Number.isFinite(variableValue)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type double) must be a finite number; got ${variableValue}.`,
path,
});
return;
}
const doubleMin = (effectiveSchema as { minimum?: number }).minimum;
const doubleMax = (effectiveSchema as { maximum?: number }).maximum;
Iif (doubleMin !== undefined && variableValue < doubleMin) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type double) must be >= minimum (${doubleMin}); got ${variableValue}.`,
path,
});
}
Iif (doubleMax !== undefined && variableValue > doubleMax) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type double) must be <= maximum (${doubleMax}); got ${variableValue}.`,
path,
});
}
return;
}
// boolean — only boolean allowed
if (expectedType === "boolean") {
Iif (typeof variableValue !== "boolean") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type boolean) must be a boolean; got ${gotType}.`,
path,
});
}
return;
}
// array — only array allowed; without items schema = array of strings
if (expectedType === "array") {
Iif (!Array.isArray(variableValue)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type array) must be an array; got ${gotType}.`,
path,
});
return;
}
refineVariableValueArray(
projectConfig,
effectiveSchema as {
items?: unknown;
type: string;
minItems?: number;
maxItems?: number;
uniqueItems?: boolean;
},
variableValue,
path,
ctx,
variableKey,
schemasByKey,
);
return;
}
// object — only plain object allowed (no null, no array)
if (expectedType === "object") {
Iif (
typeof variableValue !== "object" ||
variableValue === null ||
Array.isArray(variableValue)
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type object) must be a plain object; got ${gotType}.`,
path,
});
return;
}
refineVariableValueObject(
projectConfig,
effectiveSchema as {
properties?: Record<string, unknown>;
required?: string[];
type: string;
},
variableValue as Record<string, unknown>,
path,
ctx,
variableKey,
schemasByKey,
);
return;
}
// json — only string containing valid JSON allowed
if (expectedType === "json") {
Iif (typeof variableValue !== "string") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type json) must be a string (JSON string); got ${gotType}.`,
path,
});
return;
}
try {
JSON.parse(variableValue);
Iif (projectConfig.maxVariableJSONStringifiedLength) {
Iif (variableValue.length > projectConfig.maxVariableJSONStringifiedLength) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" JSON is too long (${variableValue.length} characters), max length is ${projectConfig.maxVariableJSONStringifiedLength}`,
path,
});
}
}
// eslint-disable-next-line
} catch (e) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" (type json) must be a valid JSON string; parse failed.`,
path,
});
}
return;
}
// Unknown variable type — schema is invalid or unsupported
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${label}" has unknown or unsupported type "${String(expectedType)}" in variablesSchema.`,
path,
});
}
/**
* Validate a single variable entry (key + value) in variables map.
* Key may be a root variable name or mutation notation (e.g. "config.width", "items[0].name").
*/
function refineVariableEntry(
projectConfig: ProjectConfig,
variableSchemaByKey: Record<string, unknown>,
variableKey: string,
variableValue: unknown,
path: (string | number)[],
ctx: z.RefinementCtx,
schemasByKey?: Record<string, Schema>,
): void {
if (isMutationKey(variableKey)) {
const validation = validateMutationKey(
variableKey,
variableSchemaByKey as Record<string, Schema>,
schemasByKey,
);
if (!validation.valid && validation.error) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: validation.error,
path,
});
return;
}
if (validation.valueSchema) {
superRefineVariableValue(
projectConfig,
validation.valueSchema,
variableValue,
path,
ctx,
variableKey,
schemasByKey,
);
}
return;
}
const variableSchema = variableSchemaByKey[variableKey];
if (!variableSchema) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${variableKey}" is not defined in \`variablesSchema\`.`,
path,
});
return;
}
superRefineVariableValue(
projectConfig,
variableSchema as Parameters<typeof superRefineVariableValue>[1],
variableValue,
path,
ctx,
variableKey,
schemasByKey,
);
}
function refineVariableOverrides({
ctx,
variableSchemaByKey,
variableOverrides,
pathPrefix,
projectConfig,
schemasByKey,
}: {
ctx: z.RefinementCtx;
variableSchemaByKey: Record<string, unknown>;
variableOverrides: Record<string, Array<{ value?: unknown }>>;
pathPrefix: (string | number)[];
projectConfig: ProjectConfig;
schemasByKey?: Record<string, Schema>;
}) {
for (const variableKey of Object.keys(variableOverrides)) {
if (isMutationKey(variableKey)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
`Variable override key "${variableKey}" must be a declared variable key, not mutation notation. ` +
"Use mutation notation inside each override's `value` object.",
path: [...pathPrefix, variableKey],
});
continue;
}
const variableSchema = variableSchemaByKey[variableKey];
if (!variableSchema) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable "${variableKey}" is not defined in \`variablesSchema\`.`,
path: [...pathPrefix, variableKey],
});
continue;
}
const variableSchemaWithRef = variableSchema as { schema?: string };
const resolvedVariableSchema = resolveVariableSchema(
variableSchema as Parameters<typeof resolveVariableSchema>[0],
schemasByKey,
);
if (variableSchemaWithRef.schema) {
Iif (!resolvedVariableSchema) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Schema "${variableSchemaWithRef.schema}" could not be loaded for variable "${variableKey}".`,
path: [...pathPrefix, variableKey],
});
continue;
}
}
const overrides = variableOverrides[variableKey];
Iif (!Array.isArray(overrides)) {
continue;
}
overrides.forEach((override, overrideN) => {
const overrideValue = override.value;
const valuePath = [...pathPrefix, variableKey, overrideN, "value"];
if (
typeof overrideValue === "object" &&
overrideValue !== null &&
!Array.isArray(overrideValue)
) {
const pathMap = overrideValue as Record<string, unknown>;
const pathKeys = Object.keys(pathMap);
const hasStructuredObjectSchema =
resolvedVariableSchema?.type === "object" &&
(Boolean(resolvedVariableSchema.properties) ||
Boolean(resolvedVariableSchema.additionalProperties));
const treatAsPathMap =
pathKeys.some((pathKey) => isMutationKey(pathKey)) ||
(hasStructuredObjectSchema && pathKeys.length > 0);
if (treatAsPathMap) {
for (const pathKey of pathKeys) {
const composedMutationKey = `${variableKey}.${pathKey}`;
const validation = validateMutationKey(
composedMutationKey,
variableSchemaByKey as Record<string, Schema>,
schemasByKey,
);
if (!validation.valid) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
validation.error ??
`Invalid mutation path "${pathKey}" in variableOverride for "${variableKey}".`,
path: [...valuePath, pathKey],
});
continue;
}
if (validation.operation === "remove") {
if (pathMap[pathKey] !== null) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Mutation "${pathKey}:remove" must use \`null\` as value.`,
path: [...valuePath, pathKey],
});
}
continue;
}
const fallbackValueSchema =
validation.operation === "append" ||
validation.operation === "prepend" ||
validation.operation === "before" ||
validation.operation === "after"
? ({ type: "string" } as Schema)
: null;
const valueSchema = validation.valueSchema ?? fallbackValueSchema;
Iif (!valueSchema) {
continue;
}
superRefineVariableValue(
projectConfig,
valueSchema,
pathMap[pathKey],
[...valuePath, pathKey],
ctx,
pathKey,
schemasByKey,
);
}
} else {
superRefineVariableValue(
projectConfig,
variableSchema as Parameters<typeof superRefineVariableValue>[1],
overrideValue,
valuePath,
ctx,
variableKey,
schemasByKey,
);
}
} else {
superRefineVariableValue(
projectConfig,
variableSchema as Parameters<typeof superRefineVariableValue>[1],
overrideValue,
valuePath,
ctx,
variableKey,
schemasByKey,
);
}
});
}
}
function refineForce({
ctx,
parsedFeature, // eslint-disable-line
variableSchemaByKey,
variationValues,
force,
pathPrefix,
projectConfig,
schemasByKey,
}) {
force.forEach((f, fN) => {
// force[n].variation
if (f.variation) {
Iif (variationValues.indexOf(f.variation) === -1) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Unknown variation "${f.variation}" in force`,
path: [...pathPrefix, fN, "variation"],
});
}
}
// force[n].variables[key]
if (f.variables) {
Object.keys(f.variables).forEach((variableKey) => {
refineVariableEntry(
projectConfig,
variableSchemaByKey,
variableKey,
f.variables[variableKey],
pathPrefix.concat([fN, "variables", variableKey]),
ctx,
schemasByKey,
);
});
}
});
}
function refineRules({
ctx,
parsedFeature,
variableSchemaByKey,
variationValues,
rules,
pathPrefix,
projectConfig,
schemasByKey,
}) {
rules.forEach((rule, ruleN) => {
// rules[n].variables[key]
if (rule.variables) {
Object.keys(rule.variables).forEach((variableKey) => {
refineVariableEntry(
projectConfig,
variableSchemaByKey,
variableKey,
rule.variables[variableKey],
pathPrefix.concat([ruleN, "variables", variableKey]),
ctx,
schemasByKey,
);
});
}
// rules[n].variableOverrides[key][].value (path-map or full value)
if (rule.variableOverrides) {
refineVariableOverrides({
ctx,
variableSchemaByKey,
variableOverrides: rule.variableOverrides,
pathPrefix: [...pathPrefix, ruleN, "variableOverrides"],
projectConfig,
schemasByKey,
});
}
// rules[n].variationWeights
if (rule.variationWeights) {
Iif (!parsedFeature.variations) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"Variation weights are overridden from rule, but no variations are present in feature.",
path: pathPrefix.concat([ruleN, "variationWeights"]),
});
} else {
const overriddenVariationValues = Object.keys(rule.variationWeights);
const overriddenVariationWeights: number[] = Object.values(rule.variationWeights);
// unique keys
Iif (overriddenVariationValues.length !== new Set(overriddenVariationValues).size) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"Duplicate variation values found in variationWeights: " +
overriddenVariationValues.join(", "),
path: pathPrefix.concat([ruleN, "variationWeights"]),
});
}
// all original variations must be used
const missingVariations = variationValues.filter(
(v) => !overriddenVariationValues.includes(v),
);
Iif (missingVariations.length > 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Missing variations: " + missingVariations.join(", "),
path: pathPrefix.concat([ruleN, "variationWeights"]),
});
}
// unknown variations
const unknownVariations = overriddenVariationValues.filter(
(v) => !variationValues.includes(v),
);
Iif (unknownVariations.length > 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"Variation weights contain unknown variations: " + unknownVariations.join(", "),
path: pathPrefix.concat([ruleN, "variationWeights"]),
});
}
// weights sum must be 100
const weightsSum = overriddenVariationWeights.reduce((sum, weight) => sum + weight, 0);
Iif (weightsSum !== 100) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Variation weights must sum to 100",
path: pathPrefix.concat([ruleN, "variationWeights"]),
});
}
}
}
});
}
export function getFeatureZodSchema(
projectConfig: ProjectConfig,
conditionsZodSchema,
availableAttributeKeys: [string, ...string[]],
availableSegmentKeys: [string, ...string[]],
availableFeatureKeys: [string, ...string[]],
availableSchemaKeys: string[] = [],
schemasByKey: Record<string, Schema> = {},
) {
const schemaZodSchema = getSchemaZodSchema(availableSchemaKeys);
const variableValueZodSchema = valueZodSchema;
const variableValueOrNullZodSchema = z.union([valueZodSchema, z.null()]);
const overridePathMapValueZodSchema = z.record(z.string(), variableValueOrNullZodSchema);
const overrideValueZodSchema = z.union([
variableValueOrNullZodSchema,
overridePathMapValueZodSchema,
]);
const variationValueZodSchema = z.string().min(1);
const plainGroupSegment = refineWithMessage(
z.string(),
(value) => value === "*" || availableSegmentKeys.includes(value),
(value) => `Unknown segment key "${value}"`,
);
const andOrNotGroupSegment = z.union([
z
.object({
and: z.array(z.lazy(() => groupSegmentZodSchema)),
})
.strict(),
z
.object({
or: z.array(z.lazy(() => groupSegmentZodSchema)),
})
.strict(),
z
.object({
not: z.array(z.lazy(() => groupSegmentZodSchema)),
})
.strict(),
]);
const groupSegmentZodSchema = z.union([andOrNotGroupSegment, plainGroupSegment]);
const groupSegmentsZodSchema = z.union([z.array(groupSegmentZodSchema), groupSegmentZodSchema]);
const exposeSchema = z
.union([z.boolean(), z.array(z.string().refine((value) => projectConfig.tags.includes(value)))])
.optional();
const rulesSchema = z
.array(
z
.object({
key: z.string(),
description: z.string().optional(),
segments: groupSegmentsZodSchema,
percentage: z.number().min(0).max(100),
enabled: z.boolean().optional(),
variation: variationValueZodSchema.optional(),
variables: z.record(z.string(), variableValueOrNullZodSchema).optional(),
variableOverrides: z
.record(
z.string(),
z.array(
z.union([
z
.object({
conditions: conditionsZodSchema,
value: overrideValueZodSchema,
})
.strict(),
z
.object({
segments: groupSegmentsZodSchema,
value: overrideValueZodSchema,
})
.strict(),
]),
),
)
.optional(),
variationWeights: z.record(z.string(), z.number().min(0).max(100)).optional(),
})
.strict(),
)
// must have at least one rule
.superRefine((value, ctx) => {
Iif (value.length === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Must have at least one rule",
});
}
})
// duplicate rules
.superRefine((value, ctx) => {
const keys = value.map((v) => v.key);
Iif (keys.length !== new Set(keys).size) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Duplicate rule keys found: " + value.map((v) => v.key).join(", "),
});
}
})
// enforce catch-all rule
.superRefine((value, ctx) => {
if (!projectConfig.enforceCatchAllRule) {
return;
}
const hasCatchAllAsLastRule = value[value.length - 1].segments === "*";
Iif (!hasCatchAllAsLastRule) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Missing catch-all rule with \`segments: "*"\` at the end`,
});
}
});
const forceSchema = z
.array(
z.union([
z
.object({
segments: groupSegmentsZodSchema,
enabled: z.boolean().optional(),
variation: variationValueZodSchema.optional(),
variables: z.record(z.string(), variableValueOrNullZodSchema).optional(),
})
.strict(),
z
.object({
conditions: conditionsZodSchema,
enabled: z.boolean().optional(),
variation: variationValueZodSchema.optional(),
variables: z.record(z.string(), variableValueOrNullZodSchema).optional(),
})
.strict(),
]),
)
.optional();
const attributeKeyZodSchema = refineWithMessage(
z.string(),
(value) => value === "*" || availableAttributeKeys.includes(value),
(value) => `Unknown attribute "${value}"`,
);
const featureKeyZodSchema = refineWithMessage(
z.string(),
(value) => availableFeatureKeys.includes(value),
(value) => `Unknown feature "${value}"`,
);
const environmentKeys = projectConfig.environments || [];
const featureZodSchema = z
.object({
archived: z.boolean().optional(),
deprecated: z.boolean().optional(),
description: z.string(),
tags: z
.array(
refineWithMessage(
z.string(),
(value) => tagRegex.test(value),
(value) =>
`Tag "${value}" must be lower cased and alphanumeric, and may contain hyphens.`,
),
)
.superRefine((value, ctx) => {
Iif (value.length !== new Set(value).size) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Duplicate tags found: " + value.join(", "),
});
}
}),
required: z
.array(
z.union([
featureKeyZodSchema,
z
.object({
key: featureKeyZodSchema,
variation: z.string().optional(),
})
.strict(),
]),
)
.optional(),
bucketBy: z.union([
attributeKeyZodSchema,
z.array(attributeKeyZodSchema),
z
.object({
or: z.array(attributeKeyZodSchema),
})
.strict(),
]),
variablesSchema: z
.record(
z.string(),
z
.object({
deprecated: z.boolean().optional(),
// Reference to a reusable schema (mutually exclusive with type/properties/required/items)
schema: refineWithMessage(
z.string(),
(value) => availableSchemaKeys.includes(value),
(value) => `Unknown schema "${value}"`,
).optional(),
// Inline schema (mutually exclusive with schema)
type: z.union([z.literal("json"), propertyTypeEnum]).optional(),
items: schemaZodSchema.optional(),
properties: z.record(z.string(), schemaZodSchema).optional(),
additionalProperties: schemaZodSchema.optional(),
required: z.array(z.string()).optional(),
enum: z.array(variableValueZodSchema).optional(),
const: variableValueZodSchema.optional(),
oneOf: z.array(schemaZodSchema).min(1).optional(),
minimum: z.number().optional(),
maximum: z.number().optional(),
minLength: z.number().optional(),
maxLength: z.number().optional(),
pattern: z.string().optional(),
minItems: z.number().optional(),
maxItems: z.number().optional(),
uniqueItems: z.boolean().optional(),
description: z.string().optional(),
defaultValue: variableValueZodSchema,
disabledValue: variableValueZodSchema.optional(),
useDefaultWhenDisabled: z.boolean().optional(),
})
.strict()
.superRefine((variableSchema, ctx) => {
const hasRef = "schema" in variableSchema && variableSchema.schema != null;
const hasInline =
"type" in variableSchema &&
variableSchema.type != null &&
variableSchema.type !== undefined;
const hasOneOf =
"oneOf" in variableSchema &&
Array.isArray(variableSchema.oneOf) &&
variableSchema.oneOf.length > 0;
if (hasRef && (hasInline || hasOneOf)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"Variable schema cannot have both `schema` (reference) and inline properties (`type`, `oneOf`, `properties`, `additionalProperties`, `required`, `items`). Use one or the other.",
path: [],
});
return;
}
if (hasRef) {
const hasInlineStructure =
("type" in variableSchema && variableSchema.type != null) ||
("properties" in variableSchema && variableSchema.properties != null) ||
("additionalProperties" in variableSchema &&
variableSchema.additionalProperties != null) ||
("required" in variableSchema && variableSchema.required != null) ||
("items" in variableSchema && variableSchema.items != null) ||
("oneOf" in variableSchema && variableSchema.oneOf != null);
const hasInlineValidation =
("minimum" in variableSchema && variableSchema.minimum !== undefined) ||
("maximum" in variableSchema && variableSchema.maximum !== undefined) ||
("minLength" in variableSchema && variableSchema.minLength !== undefined) ||
("maxLength" in variableSchema && variableSchema.maxLength !== undefined) ||
("pattern" in variableSchema && variableSchema.pattern !== undefined) ||
("minItems" in variableSchema && variableSchema.minItems !== undefined) ||
("maxItems" in variableSchema && variableSchema.maxItems !== undefined) ||
("uniqueItems" in variableSchema && variableSchema.uniqueItems !== undefined);
if (hasInlineStructure) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"When `schema` is set, do not set `type`, `oneOf`, `properties`, `additionalProperties`, `required`, or `items`.",
path: [],
});
}
Iif (hasInlineValidation) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"When `schema` is set, do not set `minimum`, `maximum`, `minLength`, `maxLength`, `pattern`, `minItems`, `maxItems`, or `uniqueItems`; use the referenced schema to define these.",
path: [],
});
}
return;
}
Iif (!hasInline && !hasOneOf) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"Variable schema must have either `schema` (reference to a schema key), `type` (inline schema), or `oneOf` (inline oneOf schemas).",
path: [],
});
return;
}
Iif (hasInline && hasOneOf) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"Variable schema cannot have both `type` and `oneOf` at the top level. Use one or the other.",
path: [],
});
return;
}
// Validate required ⊆ properties at this level and in all nested object schemas (resolve refs when schemasByKey provided)
refineRequiredKeysInSchema(
variableSchema as SchemaLikeForRequired,
[],
ctx,
schemasByKey,
);
}),
)
.optional(),
disabledVariationValue: variationValueZodSchema.optional(),
variations: z
.array(
z
.object({
description: z.string().optional(),
value: variationValueZodSchema,
weight: z.number().min(0).max(100),
variables: z.record(z.string(), variableValueOrNullZodSchema).optional(),
variableOverrides: z
.record(
z.string(),
z.array(
z.union([
z
.object({
conditions: conditionsZodSchema,
value: overrideValueZodSchema,
})
.strict(),
z
.object({
segments: groupSegmentsZodSchema,
value: overrideValueZodSchema,
})
.strict(),
]),
),
)
.optional(),
})
.strict(),
)
.superRefine((value, ctx) => {
const variationValues = value.map((v) => v.value);
Iif (variationValues.length !== new Set(variationValues).size) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Duplicate variation values found: " + value.map((v) => v.value).join(", "),
});
}
})
.optional(),
expose:
projectConfig.environments === false
? exposeSchema.optional()
: z
.partialRecord(z.enum(environmentKeys as [string, ...string[]]), exposeSchema)
.optional(),
force:
projectConfig.environments === false
? forceSchema
: z
.partialRecord(z.enum(environmentKeys as [string, ...string[]]), forceSchema)
.optional(),
rules:
projectConfig.environments === false
? rulesSchema
: z.partialRecord(z.enum(environmentKeys as [string, ...string[]]), rulesSchema),
})
.strict()
.superRefine((value, ctx) => {
// disabledVariationValue
if (value.disabledVariationValue) {
Iif (!value.variations) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Disabled variation value is set, but no variations are present in feature.",
path: ["disabledVariationValue"],
});
} else {
const variationValues = value.variations.map((v) => v.value);
Iif (variationValues.indexOf(value.disabledVariationValue) === -1) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Disabled variation value "${value.disabledVariationValue}" is not one of the defined variations: ${variationValues.join(", ")}`,
path: ["disabledVariationValue"],
});
}
}
}
// When variablesSchema is absent, variableSchemaByKey is {} so any variable key used in
// rules/force/variations will be reported as "not defined in variablesSchema".
const variableSchemaByKey = value.variablesSchema ?? {};
const variationValues: string[] = [];
if (value.variations) {
value.variations.forEach((variation) => {
variationValues.push(variation.value);
});
}
// variablesSchema[key] — only when feature defines variablesSchema
if (value.variablesSchema) {
const variableKeys = Object.keys(variableSchemaByKey);
variableKeys.forEach((variableKey) => {
const variableSchema = variableSchemaByKey[variableKey];
// When variable references a schema by name, ensure it resolves and validate the referenced schema
if ("schema" in variableSchema && variableSchema.schema) {
const resolvedSchema = resolveVariableSchema(
variableSchema as Parameters<typeof resolveVariableSchema>[0],
schemasByKey,
);
if (!resolvedSchema) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Schema "${variableSchema.schema}" could not be loaded for variable "${variableKey}".`,
path: ["variablesSchema", variableKey],
});
} else {
refineRequiredKeysInSchema(
resolvedSchema as SchemaLikeForRequired,
["variablesSchema", variableKey],
ctx,
schemasByKey,
);
}
}
// When type and enum are both present, all enum values must match the type
const effectiveSchema = resolveVariableSchema(variableSchema, schemasByKey);
if (
effectiveSchema &&
effectiveSchema.type &&
Array.isArray(effectiveSchema.enum) &&
effectiveSchema.enum.length > 0
) {
refineEnumMatchesType(
effectiveSchema as Parameters<typeof refineEnumMatchesType>[0],
["variablesSchema", variableKey],
ctx,
);
}
// Inline variable schemas: validate minimum/maximum, minLength/maxLength/pattern, minItems/maxItems/uniqueItems
if (!("schema" in variableSchema) || !variableSchema.schema) {
const pathPrefix = ["variablesSchema", variableKey];
refineMinimumMaximum(
variableSchema as Parameters<typeof refineMinimumMaximum>[0],
pathPrefix,
ctx,
);
refineStringLengthPattern(
variableSchema as Parameters<typeof refineStringLengthPattern>[0],
pathPrefix,
ctx,
);
refineArrayItems(
variableSchema as Parameters<typeof refineArrayItems>[0],
pathPrefix,
ctx,
);
}
if (variableKey === "variation") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Variable key "${variableKey}" is reserved and cannot be used.`,
path: ["variablesSchema", variableKey],
});
}
// defaultValue
superRefineVariableValue(
projectConfig,
variableSchema,
variableSchema.defaultValue,
["variablesSchema", variableKey, "defaultValue"],
ctx,
variableKey,
schemasByKey,
);
// disabledValue (only when present)
if (variableSchema.disabledValue !== undefined) {
superRefineVariableValue(
projectConfig,
variableSchema,
variableSchema.disabledValue,
["variablesSchema", variableKey, "disabledValue"],
ctx,
variableKey,
schemasByKey,
);
}
});
}
// variations: validate variation.variables and variation.variableOverrides (each value against its variable schema)
if (value.variations) {
value.variations.forEach((variation, variationN) => {
// variations[n].variables[key]
if (variation.variables) {
for (const variableKey of Object.keys(variation.variables)) {
refineVariableEntry(
projectConfig,
variableSchemaByKey,
variableKey,
variation.variables[variableKey],
["variations", variationN, "variables", variableKey],
ctx,
schemasByKey,
);
}
}
// variations[n].variableOverrides[key][].value (path-map or full value)
if (variation.variableOverrides) {
refineVariableOverrides({
ctx,
variableSchemaByKey,
variableOverrides: variation.variableOverrides,
pathPrefix: ["variations", variationN, "variableOverrides"],
projectConfig,
schemasByKey,
});
}
});
}
if (environmentKeys.length > 0) {
// with environments
for (const environmentKey of environmentKeys) {
// rules
if (value.rules && value.rules[environmentKey]) {
refineRules({
parsedFeature: value,
variableSchemaByKey,
variationValues,
rules: value.rules[environmentKey],
pathPrefix: ["rules", environmentKey],
ctx,
projectConfig,
schemasByKey,
});
}
// force
if (value.force && value.force[environmentKey]) {
refineForce({
parsedFeature: value,
variableSchemaByKey,
variationValues,
force: value.force[environmentKey],
pathPrefix: ["force", environmentKey],
ctx,
projectConfig,
schemasByKey,
});
}
}
} else E{
// no environments
// rules
Iif (value.rules) {
refineRules({
parsedFeature: value,
variableSchemaByKey,
variationValues,
rules: value.rules,
pathPrefix: ["rules"],
ctx,
projectConfig,
schemasByKey,
});
}
// force
Iif (value.force) {
refineForce({
parsedFeature: value,
variableSchemaByKey,
variationValues,
force: value.force,
pathPrefix: ["force"],
ctx,
projectConfig,
schemasByKey,
});
}
}
});
return featureZodSchema;
}
|