@libreflare/worker-runtime 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +235 -13
  2. package/dist/rule-evaluator/accept-encoding.d.ts +2 -2
  3. package/dist/rule-evaluator/accept-encoding.d.ts.map +1 -1
  4. package/dist/rule-evaluator/accept-encoding.js +62 -15
  5. package/dist/rule-evaluator/accept-encoding.js.map +1 -1
  6. package/dist/rule-evaluator/access-values.d.ts +77 -14
  7. package/dist/rule-evaluator/access-values.d.ts.map +1 -1
  8. package/dist/rule-evaluator/access-values.js +149 -17
  9. package/dist/rule-evaluator/access-values.js.map +1 -1
  10. package/dist/rule-evaluator/analysis.d.ts +43 -8
  11. package/dist/rule-evaluator/analysis.d.ts.map +1 -1
  12. package/dist/rule-evaluator/analysis.js +72 -29
  13. package/dist/rule-evaluator/analysis.js.map +1 -1
  14. package/dist/rule-evaluator/ast.d.ts +145 -11
  15. package/dist/rule-evaluator/ast.d.ts.map +1 -1
  16. package/dist/rule-evaluator/ast.js +102 -4
  17. package/dist/rule-evaluator/ast.js.map +1 -1
  18. package/dist/rule-evaluator/byte-strings.d.ts +23 -0
  19. package/dist/rule-evaluator/byte-strings.d.ts.map +1 -0
  20. package/dist/rule-evaluator/byte-strings.js +150 -0
  21. package/dist/rule-evaluator/byte-strings.js.map +1 -0
  22. package/dist/rule-evaluator/constants.d.ts +1 -1
  23. package/dist/rule-evaluator/constants.d.ts.map +1 -1
  24. package/dist/rule-evaluator/constants.js +1 -0
  25. package/dist/rule-evaluator/constants.js.map +1 -1
  26. package/dist/rule-evaluator/country-codes.generated.js +1 -1
  27. package/dist/rule-evaluator/custom-lists.d.ts +9 -0
  28. package/dist/rule-evaluator/custom-lists.d.ts.map +1 -1
  29. package/dist/rule-evaluator/custom-lists.js +43 -0
  30. package/dist/rule-evaluator/custom-lists.js.map +1 -1
  31. package/dist/rule-evaluator/diagnostics.d.ts +1 -3
  32. package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
  33. package/dist/rule-evaluator/diagnostics.js +10 -53
  34. package/dist/rule-evaluator/diagnostics.js.map +1 -1
  35. package/dist/rule-evaluator/engine-observations.d.ts +37 -0
  36. package/dist/rule-evaluator/engine-observations.d.ts.map +1 -0
  37. package/dist/rule-evaluator/engine-observations.generated.d.ts +991 -0
  38. package/dist/rule-evaluator/engine-observations.generated.d.ts.map +1 -0
  39. package/dist/rule-evaluator/engine-observations.generated.js +292 -0
  40. package/dist/rule-evaluator/engine-observations.generated.js.map +1 -0
  41. package/dist/rule-evaluator/engine-observations.js +13 -0
  42. package/dist/rule-evaluator/engine-observations.js.map +1 -0
  43. package/dist/rule-evaluator/evaluator.d.ts +1 -1
  44. package/dist/rule-evaluator/evaluator.d.ts.map +1 -1
  45. package/dist/rule-evaluator/evaluator.js +16 -15
  46. package/dist/rule-evaluator/evaluator.js.map +1 -1
  47. package/dist/rule-evaluator/explain.d.ts.map +1 -1
  48. package/dist/rule-evaluator/explain.js +35 -20
  49. package/dist/rule-evaluator/explain.js.map +1 -1
  50. package/dist/rule-evaluator/field-availability.d.ts +11 -10
  51. package/dist/rule-evaluator/field-availability.d.ts.map +1 -1
  52. package/dist/rule-evaluator/field-availability.js +136 -97
  53. package/dist/rule-evaluator/field-availability.js.map +1 -1
  54. package/dist/rule-evaluator/field-descriptions.generated.d.ts +1 -1
  55. package/dist/rule-evaluator/field-descriptions.generated.js +1 -1
  56. package/dist/rule-evaluator/field-descriptions.generated.js.map +1 -1
  57. package/dist/rule-evaluator/field-value-domains.d.ts.map +1 -1
  58. package/dist/rule-evaluator/field-value-domains.js +2 -4
  59. package/dist/rule-evaluator/field-value-domains.js.map +1 -1
  60. package/dist/rule-evaluator/fields.d.ts +25 -2
  61. package/dist/rule-evaluator/fields.d.ts.map +1 -1
  62. package/dist/rule-evaluator/fields.js +276 -119
  63. package/dist/rule-evaluator/fields.js.map +1 -1
  64. package/dist/rule-evaluator/function-availability.d.ts +16 -0
  65. package/dist/rule-evaluator/function-availability.d.ts.map +1 -0
  66. package/dist/rule-evaluator/function-availability.js +28 -0
  67. package/dist/rule-evaluator/function-availability.js.map +1 -0
  68. package/dist/rule-evaluator/function-descriptions.d.ts +15 -1
  69. package/dist/rule-evaluator/function-descriptions.d.ts.map +1 -1
  70. package/dist/rule-evaluator/function-descriptions.generated.d.ts +50 -7
  71. package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
  72. package/dist/rule-evaluator/function-descriptions.generated.js +98 -12
  73. package/dist/rule-evaluator/function-descriptions.generated.js.map +1 -1
  74. package/dist/rule-evaluator/function-descriptions.js +11 -2
  75. package/dist/rule-evaluator/function-descriptions.js.map +1 -1
  76. package/dist/rule-evaluator/function-signature-validation.d.ts +26 -2
  77. package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
  78. package/dist/rule-evaluator/function-signature-validation.js +311 -181
  79. package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
  80. package/dist/rule-evaluator/functions.d.ts +24 -5
  81. package/dist/rule-evaluator/functions.d.ts.map +1 -1
  82. package/dist/rule-evaluator/functions.js +353 -190
  83. package/dist/rule-evaluator/functions.js.map +1 -1
  84. package/dist/rule-evaluator/hash-in-range.d.ts +33 -0
  85. package/dist/rule-evaluator/hash-in-range.d.ts.map +1 -0
  86. package/dist/rule-evaluator/hash-in-range.js +72 -0
  87. package/dist/rule-evaluator/hash-in-range.js.map +1 -0
  88. package/dist/rule-evaluator/log-sample.d.ts.map +1 -1
  89. package/dist/rule-evaluator/log-sample.js +14 -6
  90. package/dist/rule-evaluator/log-sample.js.map +1 -1
  91. package/dist/rule-evaluator/match-chain.d.ts +3 -3
  92. package/dist/rule-evaluator/match-chain.d.ts.map +1 -1
  93. package/dist/rule-evaluator/match-chain.js +19 -13
  94. package/dist/rule-evaluator/match-chain.js.map +1 -1
  95. package/dist/rule-evaluator/minifier.d.ts.map +1 -1
  96. package/dist/rule-evaluator/minifier.js +16 -20
  97. package/dist/rule-evaluator/minifier.js.map +1 -1
  98. package/dist/rule-evaluator/normalizer.d.ts.map +1 -1
  99. package/dist/rule-evaluator/normalizer.js +6 -6
  100. package/dist/rule-evaluator/normalizer.js.map +1 -1
  101. package/dist/rule-evaluator/operators.d.ts +11 -4
  102. package/dist/rule-evaluator/operators.d.ts.map +1 -1
  103. package/dist/rule-evaluator/operators.js +62 -35
  104. package/dist/rule-evaluator/operators.js.map +1 -1
  105. package/dist/rule-evaluator/outcome.d.ts +2 -0
  106. package/dist/rule-evaluator/outcome.d.ts.map +1 -1
  107. package/dist/rule-evaluator/outcome.js +4 -0
  108. package/dist/rule-evaluator/outcome.js.map +1 -1
  109. package/dist/rule-evaluator/parse-cache.d.ts +3 -3
  110. package/dist/rule-evaluator/parse-cache.d.ts.map +1 -1
  111. package/dist/rule-evaluator/parse-cache.js +5 -13
  112. package/dist/rule-evaluator/parse-cache.js.map +1 -1
  113. package/dist/rule-evaluator/parser.d.ts +318 -11
  114. package/dist/rule-evaluator/parser.d.ts.map +1 -1
  115. package/dist/rule-evaluator/parser.js +1314 -333
  116. package/dist/rule-evaluator/parser.js.map +1 -1
  117. package/dist/rule-evaluator/quantifier.d.ts +1 -1
  118. package/dist/rule-evaluator/quantifier.d.ts.map +1 -1
  119. package/dist/rule-evaluator/quantifier.js +1 -16
  120. package/dist/rule-evaluator/quantifier.js.map +1 -1
  121. package/dist/rule-evaluator/request-headers.d.ts +101 -0
  122. package/dist/rule-evaluator/request-headers.d.ts.map +1 -0
  123. package/dist/rule-evaluator/request-headers.js +344 -0
  124. package/dist/rule-evaluator/request-headers.js.map +1 -0
  125. package/dist/rule-evaluator/rule-language-types.d.ts +80 -21
  126. package/dist/rule-evaluator/rule-language-types.d.ts.map +1 -1
  127. package/dist/rule-evaluator/rule-language-types.js +228 -67
  128. package/dist/rule-evaluator/rule-language-types.js.map +1 -1
  129. package/dist/rule-evaluator/tokenizer.d.ts +14 -4
  130. package/dist/rule-evaluator/tokenizer.d.ts.map +1 -1
  131. package/dist/rule-evaluator/tokenizer.js +24 -11
  132. package/dist/rule-evaluator/tokenizer.js.map +1 -1
  133. package/dist/rule-evaluator/transformation.d.ts.map +1 -1
  134. package/dist/rule-evaluator/transformation.js +10 -6
  135. package/dist/rule-evaluator/transformation.js.map +1 -1
  136. package/dist/rule-evaluator/url-decode.d.ts +8 -0
  137. package/dist/rule-evaluator/url-decode.d.ts.map +1 -0
  138. package/dist/rule-evaluator/url-decode.js +126 -0
  139. package/dist/rule-evaluator/url-decode.js.map +1 -0
  140. package/dist/rule-evaluator/validation.d.ts.map +1 -1
  141. package/dist/rule-evaluator/validation.js +405 -235
  142. package/dist/rule-evaluator/validation.js.map +1 -1
  143. package/dist/rule-evaluator.d.ts +2 -2
  144. package/dist/rule-evaluator.d.ts.map +1 -1
  145. package/dist/rule-evaluator.js.map +1 -1
  146. package/package.json +5 -2
  147. package/dist/rule-evaluator/comparison.d.ts +0 -16
  148. package/dist/rule-evaluator/comparison.d.ts.map +0 -1
  149. package/dist/rule-evaluator/comparison.js +0 -43
  150. package/dist/rule-evaluator/comparison.js.map +0 -1
  151. package/dist/rule-evaluator/custom-security-rule-analysis.d.ts +0 -36
  152. package/dist/rule-evaluator/custom-security-rule-analysis.d.ts.map +0 -1
  153. package/dist/rule-evaluator/custom-security-rule-analysis.js +0 -382
  154. package/dist/rule-evaluator/custom-security-rule-analysis.js.map +0 -1
  155. package/dist/rule-evaluator/values.d.ts +0 -26
  156. package/dist/rule-evaluator/values.d.ts.map +0 -1
  157. package/dist/rule-evaluator/values.js +0 -55
  158. package/dist/rule-evaluator/values.js.map +0 -1
  159. package/dist/rule-evaluator/warnings.d.ts +0 -2
  160. package/dist/rule-evaluator/warnings.d.ts.map +0 -1
  161. package/dist/rule-evaluator/warnings.js +0 -5
  162. package/dist/rule-evaluator/warnings.js.map +0 -1
@@ -1,25 +1,32 @@
1
- import { pushDiagnostic, ruleExpressionDiagnostic, } from './diagnostics.js';
2
- import { EQUALITY_ORDERING_OPERATORS, isDynamicValueNode, pushWarning, } from './ast.js';
1
+ import { ruleExpressionDiagnostic, } from './diagnostics.js';
2
+ import { EQUALITY_ORDERING_OPERATORS, isBooleanLiteralName, isConditionArgument, isDynamicValueNode, isEmptyArgument, isExpressionNode, mayHaveFewerArguments, unhandledNode, validSetElements, } from './ast.js';
3
3
  import { RULE_EXPRESSION_MATCH_ALL_EXPRESSION } from './constants.js';
4
+ import { isRuleExpressionFunctionAvailable, isRuleExpressionOperatorAvailable } from './function-availability.js';
4
5
  import { getUnreliableRuleExpressionFunctionReason } from './functions.js';
5
- import { validateFunctionSignature } from './function-signature-validation.js';
6
+ import { bindArguments, validateFunctionSignature, } from './function-signature-validation.js';
6
7
  import { minifyRuleExpression } from './minifier.js';
7
8
  import { parseExpression } from './parse-cache.js';
9
+ import { hasRuleExpressionSyntaxErrors } from './transformation.js';
8
10
  import { isKnownRuleExpressionFieldName, isRuleExpressionFieldAvailable, resolveRuleExpressionFieldAvailability, } from './field-availability.js';
9
- import { DEPRECATED_FIELD_REPLACEMENTS, KNOWN_DEPRECATED_FIELDS, } from './fields.js';
11
+ import { deprecatedFieldReplacement, KNOWN_DEPRECATED_FIELDS, REQUEST_HEADER_ARRAYS, REQUEST_HEADER_MAPS } from './fields.js';
10
12
  import { isRuleExpressionCountryCode } from './country-codes.js';
11
13
  import { getRuleExpressionFieldValueDomain } from './field-value-domains.js';
12
14
  import { customList, isRuleExpressionIpListItem, isRuleExpressionListName, } from './custom-lists.js';
13
- import { formatRuleExpressionDataType, isArrayExpandedNode, isConcreteComparisonFamily, isExpressionNode, isFieldNode, isFuncNode, inferRuleExpressionArgument, isIpAddressValueType, isLiteralNode, isUnknownRuleExpressionDataType, ruleExpressionComparisonTypeFamily, ruleExpressionValueTypes, } from './rule-language-types.js';
15
+ import { fieldDataType, formatRuleExpressionDataType, isArrayExpandedNode, isBooleanType, isConcreteComparisonFamily, isFieldNode, isFuncNode, inferRuleExpressionArgument, isIpAddressValueType, isLiteralNode, isUnknownRuleExpressionDataType, ruleExpressionComparisonTypeFamily, ruleExpressionValueTypes, singleValueType, } from './rule-language-types.js';
14
16
  import { extractQuantifierComparison, extractQuantifierPredicate } from './quantifier.js';
17
+ import { stringLiteralSource } from './tokenizer.js';
15
18
  export const MAX_CLOUDFLARE_RULE_EXPRESSION_LENGTH = 4096;
16
19
  export const RULE_EXPRESSION_VALIDATION_PRESETS = [
17
20
  'url-rewrite-filter',
18
21
  'url-rewrite-target',
19
22
  'logging-source-key',
20
23
  ];
21
- const URL_REWRITE_TARGET_SINGLE_USE_FUNCTIONS = new Set(['concat', 'regex_replace', 'wildcard_replace']);
22
- const URL_REWRITE_TARGET_NON_NESTABLE_REPLACEMENT_FUNCTIONS = new Set(['regex_replace', 'wildcard_replace']);
24
+ /** Functions Cloudflare accepts at most once in any expression. */
25
+ const SINGLE_USE_FUNCTIONS = new Set(['hash_in_range']);
26
+ /** Functions the URL rewrite phase accepts at most once in a filter or a rewrite target. */
27
+ const URL_REWRITE_SINGLE_USE_FUNCTIONS = new Set(['concat', 'regex_replace', 'wildcard_replace']);
28
+ /** Replacement functions the URL rewrite phase does not accept inside each other. */
29
+ const URL_REWRITE_NON_NESTABLE_REPLACEMENT_FUNCTIONS = new Set(['regex_replace', 'wildcard_replace']);
23
30
  const SUPPORTED_LIST_KIND = 'ip';
24
31
  export function validateRuleExpressionSyntax(source, config = {}) {
25
32
  const minify = config?.minify ?? true;
@@ -28,7 +35,6 @@ export function validateRuleExpressionSyntax(source, config = {}) {
28
35
  const preset = config.preset ?? 'url-rewrite-filter';
29
36
  const expression = source.trim();
30
37
  const errors = [];
31
- const warnings = [];
32
38
  const diagnostics = [];
33
39
  const semanticContext = {
34
40
  preset,
@@ -40,7 +46,7 @@ export function validateRuleExpressionSyntax(source, config = {}) {
40
46
  if (!expression) {
41
47
  const message = 'rule expression is required';
42
48
  errors.push(message);
43
- pushDiagnostic(diagnostics, {
49
+ diagnostics.push({
44
50
  id: 'rule_expression.required',
45
51
  severity: 'error',
46
52
  pos: null,
@@ -48,29 +54,25 @@ export function validateRuleExpressionSyntax(source, config = {}) {
48
54
  source: 'expression',
49
55
  });
50
56
  }
51
- const parseWarnings = [];
52
57
  const parseDiagnostics = [];
53
- const parsedExpression = expression ? parseExpression(expression, parseWarnings, parseDiagnostics, parseOptions) : null;
54
- const minified = minify ? minifyRuleExpression(expression, parseOptions) : { expression, diagnostics: [] };
55
- const minifiedParseWarnings = [];
58
+ const parsedExpression = expression ? parseExpression(expression, parseDiagnostics, parseOptions) : null;
59
+ // The minifier keeps an expression with a syntax error as it is, so only one without is minified.
60
+ const minifies = minify && !hasRuleExpressionSyntaxErrors(parseDiagnostics);
61
+ const minifiedExpression = minifies ? minifyRuleExpression(expression, parseOptions).expression : expression;
56
62
  const minifiedParseDiagnostics = [];
57
- const minificationFailed = minified.diagnostics.some(diagnostic => diagnostic.severity === 'error');
58
- if (minify && minified.expression && !minificationFailed) {
59
- parseExpression(minified.expression, minifiedParseWarnings, minifiedParseDiagnostics);
60
- }
61
- const lengthCheckedExpression = minify ? minified.expression : expression;
62
- collectValidationDiagnostics(errors, warnings, diagnostics, parseDiagnostics, 'expression');
63
+ if (minifies && minifiedExpression)
64
+ parseExpression(minifiedExpression, minifiedParseDiagnostics);
65
+ const lengthCheckedExpression = minify ? minifiedExpression : expression;
66
+ collectValidationDiagnostics(errors, diagnostics, parseDiagnostics, 'expression');
63
67
  if (parsedExpression)
64
- collectSemanticValidationDiagnostics(errors, warnings, diagnostics, parsedExpression, expression, semanticContext);
65
- for (const diagnostic of minified.diagnostics)
66
- pushDiagnostic(diagnostics, { ...diagnostic, source: 'expression' });
67
- collectValidationDiagnostics(errors, warnings, diagnostics, minifiedParseDiagnostics, 'minifiedExpression');
68
+ collectSemanticValidationDiagnostics(errors, diagnostics, parsedExpression, expression, semanticContext);
69
+ collectValidationDiagnostics(errors, diagnostics, minifiedParseDiagnostics, 'minifiedExpression');
68
70
  if ((config.enforceMaxLength ?? true) && lengthCheckedExpression.length > maxLength) {
69
71
  const expressionLabel = minify ? 'minified rule expression' : 'rule expression';
70
72
  const limitLabel = maxLength === MAX_CLOUDFLARE_RULE_EXPRESSION_LENGTH ? 'Cloudflare limit' : 'configured limit';
71
73
  const message = `${expressionLabel} is ${lengthCheckedExpression.length} characters; ${limitLabel} is ${maxLength}`;
72
74
  errors.push(message);
73
- pushDiagnostic(diagnostics, {
75
+ diagnostics.push({
74
76
  id: 'rule_expression.too_long',
75
77
  params: {
76
78
  actualLength: lengthCheckedExpression.length,
@@ -95,8 +97,8 @@ export function validateRuleExpressionSyntax(source, config = {}) {
95
97
  return validation;
96
98
  return {
97
99
  ...validation,
98
- minifiedExpression: minified.expression,
99
- minifiedLength: minified.expression.length,
100
+ minifiedExpression,
101
+ minifiedLength: minifiedExpression.length,
100
102
  };
101
103
  }
102
104
  /**
@@ -120,17 +122,16 @@ const evaluationErrors = new WeakMap();
120
122
  * result is cached with the parsed expression.
121
123
  */
122
124
  export function ruleExpressionEvaluationErrors(expression) {
123
- const parseWarnings = [];
124
125
  const parseDiagnostics = [];
125
- const node = parseExpression(expression, parseWarnings, parseDiagnostics);
126
+ const node = parseExpression(expression, parseDiagnostics);
126
127
  const cached = evaluationErrors.get(node);
127
128
  if (cached)
128
129
  return cached;
129
130
  const errors = [];
130
131
  const diagnostics = [];
131
- collectValidationDiagnostics(errors, [], diagnostics, parseDiagnostics, 'expression');
132
- collectSemanticValidationDiagnostics(errors, [], diagnostics, node, expression, {
133
- preset: 'url-rewrite-filter',
132
+ collectValidationDiagnostics(errors, diagnostics, parseDiagnostics, 'expression');
133
+ collectSemanticValidationDiagnostics(errors, diagnostics, node, expression, {
134
+ preset: null,
134
135
  fieldAvailability: null,
135
136
  rejectListReferences: false,
136
137
  deprecationNotices: false,
@@ -228,7 +229,7 @@ function isKnownFieldName(field) {
228
229
  }
229
230
  function pushValidationConfigError(message, errors, diagnostics, metadata) {
230
231
  errors.push(message);
231
- pushDiagnostic(diagnostics, {
232
+ diagnostics.push({
232
233
  ...metadata,
233
234
  severity: 'error',
234
235
  pos: null,
@@ -236,100 +237,120 @@ function pushValidationConfigError(message, errors, diagnostics, metadata) {
236
237
  source: 'expression',
237
238
  });
238
239
  }
239
- function collectValidationDiagnostics(errors, warnings, diagnostics, messageDiagnostics, source) {
240
+ function collectValidationDiagnostics(errors, diagnostics, messageDiagnostics, source) {
240
241
  for (const diagnostic of messageDiagnostics) {
241
- pushValidationMessage(errors, warnings, diagnostic.message, diagnostic.severity);
242
- pushDiagnostic(diagnostics, ruleExpressionDiagnostic(diagnostic, source));
242
+ if (diagnostic.severity === 'error')
243
+ errors.push(diagnostic.message);
244
+ diagnostics.push(ruleExpressionDiagnostic(diagnostic, source));
243
245
  }
244
246
  }
245
- function pushValidationMessage(errors, warnings, message, severity) {
246
- if (severity === 'error')
247
- errors.push(message);
248
- else
249
- warnings.push(message);
250
- }
251
- function collectSemanticValidationDiagnostics(errors, warnings, diagnostics, node, expression, context) {
247
+ function collectSemanticValidationDiagnostics(errors, diagnostics, node, expression, context) {
252
248
  const rootPosition = context.preset === 'url-rewrite-target' ? 'value' : 'predicate';
253
249
  validateBooleanLiterals(node, errors, diagnostics);
254
- validateSemanticNode(node, new Set(), errors, warnings, diagnostics, expression, context, rootPosition);
255
- if (context.preset === 'url-rewrite-target')
256
- validateRewriteTargetFunctionUsage(node, errors, diagnostics);
250
+ validateSemanticNode(node, new Set(), errors, diagnostics, expression, context, rootPosition);
251
+ validateFunctionUsage(node, context, errors, diagnostics);
257
252
  }
258
- function validateSemanticNode(node, guardedHeaders, errors, warnings, diagnostics, expression, context, position) {
253
+ function validateSemanticNode(node, guardedHeaders, errors, diagnostics, expression, context, position) {
259
254
  switch (node.kind) {
260
255
  case 'And': {
261
256
  const andGuards = unionHeaderGuards(guardedHeaders, collectHeaderPresenceGuards(node));
262
257
  for (const operand of node.operands) {
263
- validateSemanticNode(operand, andGuards, errors, warnings, diagnostics, expression, context, 'predicate');
258
+ validateSemanticNode(operand, andGuards, errors, diagnostics, expression, context, 'predicate');
264
259
  }
265
260
  return;
266
261
  }
267
262
  case 'Or':
268
263
  case 'Xor':
269
264
  for (const operand of node.operands) {
270
- validateSemanticNode(operand, guardedHeaders, errors, warnings, diagnostics, expression, context, 'predicate');
265
+ validateSemanticNode(operand, guardedHeaders, errors, diagnostics, expression, context, 'predicate');
271
266
  }
272
267
  return;
273
268
  case 'Not':
274
- validateSemanticNode(node.operand, guardedHeaders, errors, warnings, diagnostics, expression, context, 'predicate');
269
+ validateSemanticNode(node.operand, guardedHeaders, errors, diagnostics, expression, context, 'predicate');
275
270
  return;
276
271
  case 'Comparison':
277
- validateFieldOrFunc(node.left, guardedHeaders, errors, warnings, diagnostics, expression, context);
272
+ validateFieldOrFunc(node.left, guardedHeaders, errors, diagnostics, expression, context);
278
273
  if (isDynamicValueNode(node.right)) {
279
- validateFieldOrFunc(node.right, guardedHeaders, errors, warnings, diagnostics, expression, context);
274
+ validateFieldOrFunc(node.right, guardedHeaders, errors, diagnostics, expression, context);
280
275
  }
281
276
  validateComparisonRequirements(node, errors, diagnostics, context);
282
277
  return;
283
- case 'Func':
278
+ case 'Func': {
284
279
  if (position === 'predicate')
285
280
  validateFunctionPredicateResult(node, errors, diagnostics);
281
+ validateFunctionAvailability(node, errors, diagnostics, context);
286
282
  validateAccessPath(node, errors, diagnostics);
287
- validateFunctionSupport(node, warnings, diagnostics);
288
- validateFunctionArgRequirements(node, errors, diagnostics);
283
+ validateFunctionSupport(node, diagnostics);
284
+ const binding = bindArguments(node);
285
+ validateFunctionArgRequirements(node, binding, errors, diagnostics);
289
286
  if (node.name === 'coalesce')
290
- validateCoalesceFallbacks(node, warnings, diagnostics);
287
+ validateCoalesceFallbacks(node, binding, diagnostics);
291
288
  if (node.name === 'any' || node.name === 'all') {
292
- validateQuantifierPredicateArgs(node, guardedHeaders, errors, warnings, diagnostics, expression, context);
289
+ validateQuantifierPredicateArgs(node, guardedHeaders, errors, diagnostics, expression, context);
293
290
  }
294
291
  else {
295
- validateFuncArgs(node, guardedHeaders, errors, warnings, diagnostics, expression, context);
292
+ validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context);
296
293
  }
297
294
  return;
295
+ }
298
296
  case 'BoolField':
299
- validateBoolFieldNode(node, errors, warnings, diagnostics, expression, context);
297
+ validateBoolFieldNode(node, errors, diagnostics, expression, context);
300
298
  return;
299
+ case 'Invalid':
300
+ // A field or call that recovery cut short gets its own checks, but is not judged as a condition.
301
+ if (node.operand)
302
+ validateFieldOrFunc(node.operand, guardedHeaders, errors, diagnostics, expression, context);
303
+ return;
304
+ default:
305
+ unhandledNode(node);
301
306
  }
302
307
  }
303
308
  function validateFunctionPredicateResult(node, errors, diagnostics) {
304
- const result = inferRuleExpressionArgument(node);
305
- if (result.accessIssues.length > 0 || isUnknownRuleExpressionDataType(result.type))
306
- return;
307
- if (result.type.kind === 'scalar' && result.type.name === 'Boolean')
309
+ const type = conditionResultType(node);
310
+ if (!type || isUnknownRuleExpressionDataType(type) || isBooleanType(type))
308
311
  return;
309
- const actualType = formatRuleExpressionDataType(result.type);
312
+ const actualType = formatRuleExpressionDataType(type);
310
313
  pushFuncError(node, `function '${node.name}' result must be Boolean in predicate position; received ${actualType}`, errors, diagnostics, {
311
314
  id: 'function.result_type_mismatch',
312
315
  params: { functionName: node.name, expectedType: 'Boolean', actualType },
313
316
  });
314
317
  }
318
+ /**
319
+ * The type a call's result has as a condition, or null when it is invalid.
320
+ * Where only whether the call maps is unknown, the type of one invocation
321
+ * stands for its result, an array of it or not, which is a Boolean only
322
+ * where that type is one, and then may be either; see singleValueType().
323
+ */
324
+ function conditionResultType(node) {
325
+ const result = inferRuleExpressionArgument(node);
326
+ if (!result.invalid)
327
+ return result.type;
328
+ const type = singleValueType(node);
329
+ return type && !isBooleanType(type) ? type : null;
330
+ }
315
331
  function validateComparisonRequirements(node, errors, diagnostics, context) {
316
332
  let invalidArrayComparison = false;
317
333
  const leftInfo = inferRuleExpressionArgument(node.left);
318
- if (isFieldNode(node.left) && leftInfo.expanded && leftInfo.accessIssues.length === 0) {
334
+ const leftExpanded = !leftInfo.invalid && leftInfo.expanded;
335
+ if (isFieldNode(node.left) && leftExpanded) {
319
336
  pushComparisonError(node.left, '[*] cannot be used directly with comparison operators; wrap the comparison in any() or all()', errors, diagnostics, { id: 'array_expansion.direct_comparison' });
320
337
  invalidArrayComparison = true;
321
338
  }
322
- if (node.left.kind === 'Func' && leftInfo.expanded && leftInfo.accessIssues.length === 0) {
339
+ if (node.left.kind === 'Func' && leftExpanded) {
323
340
  pushFuncError(node.left, '[*] cannot be used directly with comparison operators; wrap the comparison in any() or all()', errors, diagnostics, { id: 'array_expansion.direct_comparison' });
324
341
  invalidArrayComparison = true;
325
342
  }
326
- const rightInfo = isDynamicValueNode(node.right) ? inferRuleExpressionArgument(node.right) : null;
327
- if (isDynamicValueNode(node.right) && rightInfo?.expanded && rightInfo.accessIssues.length === 0) {
343
+ if (isArrayExpandedNode(node.right)) {
328
344
  pushValueError(node.right, '[*] cannot be used directly with comparison operators; wrap the comparison in any() or all()', errors, diagnostics, { id: 'array_expansion.direct_comparison' });
329
345
  invalidArrayComparison = true;
330
346
  }
331
- if (!node.right)
347
+ // Invalid syntax already has its error, and nothing is judged by what it might have been. The checks
348
+ // that read only the left side still run.
349
+ if (!node.right || node.right.kind === 'Invalid') {
350
+ if (!invalidArrayComparison)
351
+ validateComparisonTypeCompatibility(node, undefined, errors, diagnostics);
332
352
  return;
353
+ }
333
354
  // Only equality and ordering operators compare dynamic values; `in` reports its own list requirement.
334
355
  if (isDynamicValueNode(node.right) && node.op !== 'in' && !EQUALITY_ORDERING_OPERATORS.has(node.op)) {
335
356
  pushValueError(node.right, `operator '${node.op}' requires a literal value on the right side`, errors, diagnostics, { id: 'operator.requires_literal_value', params: { operator: node.op } });
@@ -351,16 +372,15 @@ function validateComparisonRequirements(node, errors, diagnostics, context) {
351
372
  validateWildcardPattern(node.right, errors, diagnostics);
352
373
  }
353
374
  validateComparisonValueDomain(node, errors, diagnostics);
354
- if (!invalidArrayComparison && leftInfo.accessIssues.length === 0 && (rightInfo?.accessIssues.length ?? 0) === 0) {
355
- validateComparisonTypeCompatibility(node, errors, diagnostics);
356
- }
375
+ if (!invalidArrayComparison)
376
+ validateComparisonTypeCompatibility(node, node.right, errors, diagnostics);
357
377
  }
358
378
  function validateComparisonValueDomain(node, errors, diagnostics) {
359
379
  if (!isFieldNode(node.left) || (node.op !== 'eq' && node.op !== 'ne' && node.op !== 'in'))
360
380
  return;
361
381
  if (getRuleExpressionFieldValueDomain(node.left.name) !== 'country-code')
362
382
  return;
363
- const right = node.right;
383
+ const right = node.right?.kind === 'StringLiteral' || node.right?.kind === 'SetLiteral' ? node.right : undefined;
364
384
  for (const value of stringLiteralValues(right)) {
365
385
  if (isRuleExpressionCountryCode(value))
366
386
  continue;
@@ -375,25 +395,28 @@ function validateComparisonValueDomain(node, errors, diagnostics) {
375
395
  function stringLiteralValues(node) {
376
396
  if (node?.kind === 'StringLiteral')
377
397
  return [node.value];
378
- if (node?.kind !== 'SetLiteral')
379
- return [];
380
- return node.elements.flatMap(element => element.type === 'string' ? [element.value] : []);
398
+ return node?.elements.flatMap(element => element.type === 'string' ? [element.value] : []) ?? [];
381
399
  }
382
- function validateComparisonTypeCompatibility(node, errors, diagnostics) {
383
- if (node.op === 'in') {
384
- if (node.right?.kind === 'ListRef')
400
+ /**
401
+ * Checks that the comparison's operator accepts the types of its sides. The
402
+ * left side is checked whatever the right side is, unless that is of a type
403
+ * no operator supports. A right side that is missing, invalid, or of a type
404
+ * not known is not judged, as nothing is judged by what it might have been.
405
+ */
406
+ function validateComparisonTypeCompatibility(node, right, errors, diagnostics) {
407
+ if (node.op === 'in' && right) {
408
+ if (right.kind === 'ListRef')
385
409
  return;
386
- if (node.right?.kind !== 'SetLiteral') {
387
- pushComparisonTypeError(node.right ?? node.left, "operator 'in' requires an inline list or list reference", errors, diagnostics, { id: 'operator.in_requires_list', params: { operator: 'in' } });
410
+ if (right.kind !== 'SetLiteral') {
411
+ pushComparisonTypeError(right, "operator 'in' requires an inline list or list reference", errors, diagnostics, { id: 'operator.in_requires_list', params: { operator: 'in' } });
388
412
  return;
389
413
  }
390
414
  }
391
- if (!node.right)
415
+ const leftInfo = inferRuleExpressionArgument(node.left);
416
+ if (leftInfo.invalid)
392
417
  return;
393
- const leftType = inferRuleExpressionArgument(node.left).type;
394
- const rightType = inferRuleExpressionArgument(node.right).type;
418
+ const leftType = leftInfo.type;
395
419
  const leftFamily = ruleExpressionComparisonTypeFamily(leftType);
396
- const rightFamily = ruleExpressionComparisonTypeFamily(rightType);
397
420
  if (leftFamily === 'unsupported') {
398
421
  const leftTypeLabel = formatRuleExpressionDataType(leftType);
399
422
  pushComparisonTypeError(node.left, `operator '${node.op}' does not support ${leftTypeLabel} values`, errors, diagnostics, {
@@ -402,39 +425,37 @@ function validateComparisonTypeCompatibility(node, errors, diagnostics) {
402
425
  });
403
426
  return;
404
427
  }
405
- if (rightFamily === 'unsupported') {
428
+ const rightInfo = right && inferRuleExpressionArgument(right);
429
+ const rightType = rightInfo && !rightInfo.invalid ? rightInfo.type : null;
430
+ const rightFamily = rightType ? ruleExpressionComparisonTypeFamily(rightType) : 'unknown';
431
+ if (right && rightType && rightFamily === 'unsupported') {
406
432
  const rightTypeLabel = formatRuleExpressionDataType(rightType);
407
- pushComparisonTypeError(node.right, `operator '${node.op}' does not support ${rightTypeLabel} values`, errors, diagnostics, {
433
+ pushComparisonTypeError(right, `operator '${node.op}' does not support ${rightTypeLabel} values`, errors, diagnostics, {
408
434
  id: 'operator.unsupported_type',
409
435
  params: { operator: node.op, side: 'right', valueType: rightTypeLabel },
410
436
  });
411
437
  return;
412
438
  }
413
- if (!isConcreteComparisonFamily(leftFamily) || !isConcreteComparisonFamily(rightFamily))
439
+ if (!isConcreteComparisonFamily(leftFamily) || !validateLeftOperandType(node, leftFamily, errors, diagnostics))
440
+ return;
441
+ if (!right || !isConcreteComparisonFamily(rightFamily))
414
442
  return;
415
443
  const leftLabel = comparisonFamilyLabel(leftFamily);
416
444
  const rightLabel = comparisonFamilyLabel(rightFamily);
417
- const valueIsInlineSet = node.right.kind === 'SetLiteral';
445
+ const valueIsInlineSet = right.kind === 'SetLiteral';
418
446
  const rightValueLabel = valueIsInlineSet ? `inline list of ${rightLabel}` : rightLabel;
419
447
  switch (node.op) {
420
448
  case 'eq':
421
449
  case 'ne':
422
- if (!isEqualityFamily(leftFamily)) {
423
- pushComparisonTypeError(node.left, `operator '${node.op}' does not support ${leftLabel} values`, errors, diagnostics, {
424
- id: 'operator.unsupported_type',
425
- params: { operator: node.op, side: 'left', valueType: leftLabel },
426
- });
427
- return;
428
- }
429
450
  if (!isEqualityFamily(rightFamily)) {
430
- pushComparisonTypeError(node.right, `operator '${node.op}' does not support ${rightValueLabel}`, errors, diagnostics, {
451
+ pushComparisonTypeError(right, `operator '${node.op}' does not support ${rightValueLabel}`, errors, diagnostics, {
431
452
  id: 'operator.unsupported_type',
432
453
  params: { operator: node.op, side: 'right', valueType: rightLabel, valueIsInlineSet },
433
454
  });
434
455
  return;
435
456
  }
436
457
  if (leftFamily !== rightFamily) {
437
- pushComparisonTypeError(node.right, `operator '${node.op}' cannot compare ${leftLabel} with ${rightValueLabel}`, errors, diagnostics, {
458
+ pushComparisonTypeError(right, `operator '${node.op}' cannot compare ${leftLabel} with ${rightValueLabel}`, errors, diagnostics, {
438
459
  id: 'operator.type_mismatch',
439
460
  params: { operator: node.op, leftType: leftLabel, rightType: rightLabel, valueIsInlineSet },
440
461
  });
@@ -444,15 +465,10 @@ function validateComparisonTypeCompatibility(node, errors, diagnostics) {
444
465
  case 'le':
445
466
  case 'gt':
446
467
  case 'ge':
447
- if (!isOrderingFamily(leftFamily)) {
448
- pushComparisonTypeError(node.left, `operator '${node.op}' requires String or Number values; left side is ${leftLabel}`, errors, diagnostics, {
449
- id: 'operator.requires_type',
450
- params: { operator: node.op, side: 'left', requiredTypes: ['String', 'Number'], actualType: leftLabel },
451
- });
452
- return;
453
- }
454
- if (!isOrderingFamily(rightFamily) || leftFamily !== rightFamily) {
455
- pushComparisonTypeError(node.right, `operator '${node.op}' cannot compare ${leftLabel} with ${rightValueLabel}`, errors, diagnostics, {
468
+ case 'in':
469
+ // The left side's family suits the operator, so the same family on the right does too.
470
+ if (leftFamily !== rightFamily) {
471
+ pushComparisonTypeError(right, `operator '${node.op}' cannot compare ${leftLabel} with ${rightValueLabel}`, errors, diagnostics, {
456
472
  id: 'operator.type_mismatch',
457
473
  params: { operator: node.op, leftType: leftLabel, rightType: rightLabel, valueIsInlineSet },
458
474
  });
@@ -462,35 +478,51 @@ function validateComparisonTypeCompatibility(node, errors, diagnostics) {
462
478
  case 'matches':
463
479
  case 'wildcard':
464
480
  case 'strict_wildcard':
465
- if (leftFamily !== 'string') {
466
- pushComparisonTypeError(node.left, `operator '${node.op}' requires String values; left side is ${leftLabel}`, errors, diagnostics, {
467
- id: 'operator.requires_type',
468
- params: { operator: node.op, side: 'left', requiredTypes: ['String'], actualType: leftLabel },
469
- });
470
- return;
471
- }
472
481
  if (rightFamily !== 'string') {
473
- pushComparisonTypeError(node.right, `operator '${node.op}' requires String values; right side is ${rightValueLabel}`, errors, diagnostics, {
482
+ pushComparisonTypeError(right, `operator '${node.op}' requires String values; right side is ${rightValueLabel}`, errors, diagnostics, {
474
483
  id: 'operator.requires_type',
475
484
  params: { operator: node.op, side: 'right', requiredTypes: ['String'], actualType: rightLabel, valueIsInlineSet },
476
485
  });
477
486
  }
478
487
  return;
488
+ }
489
+ }
490
+ /** Checks that the operator accepts the left side's type, whatever the right side is; false after an error. */
491
+ function validateLeftOperandType(node, leftFamily, errors, diagnostics) {
492
+ const leftLabel = comparisonFamilyLabel(leftFamily);
493
+ switch (node.op) {
494
+ case 'eq':
495
+ case 'ne':
479
496
  case 'in':
480
- if (!isEqualityFamily(leftFamily)) {
481
- pushComparisonTypeError(node.left, `operator 'in' does not support ${leftLabel} values`, errors, diagnostics, {
482
- id: 'operator.unsupported_type',
483
- params: { operator: 'in', side: 'left', valueType: leftLabel },
484
- });
485
- return;
486
- }
487
- if (!isEqualityFamily(rightFamily) || leftFamily !== rightFamily) {
488
- pushComparisonTypeError(node.right, `operator 'in' cannot compare ${leftLabel} with ${rightValueLabel}`, errors, diagnostics, {
489
- id: 'operator.type_mismatch',
490
- params: { operator: 'in', leftType: leftLabel, rightType: rightLabel, valueIsInlineSet },
491
- });
492
- }
493
- return;
497
+ if (isEqualityFamily(leftFamily))
498
+ return true;
499
+ pushComparisonTypeError(node.left, `operator '${node.op}' does not support ${leftLabel} values`, errors, diagnostics, {
500
+ id: 'operator.unsupported_type',
501
+ params: { operator: node.op, side: 'left', valueType: leftLabel },
502
+ });
503
+ return false;
504
+ case 'lt':
505
+ case 'le':
506
+ case 'gt':
507
+ case 'ge':
508
+ if (isOrderingFamily(leftFamily))
509
+ return true;
510
+ pushComparisonTypeError(node.left, `operator '${node.op}' requires String or Number values; left side is ${leftLabel}`, errors, diagnostics, {
511
+ id: 'operator.requires_type',
512
+ params: { operator: node.op, side: 'left', requiredTypes: ['String', 'Number'], actualType: leftLabel },
513
+ });
514
+ return false;
515
+ case 'contains':
516
+ case 'matches':
517
+ case 'wildcard':
518
+ case 'strict_wildcard':
519
+ if (leftFamily === 'string')
520
+ return true;
521
+ pushComparisonTypeError(node.left, `operator '${node.op}' requires String values; left side is ${leftLabel}`, errors, diagnostics, {
522
+ id: 'operator.requires_type',
523
+ params: { operator: node.op, side: 'left', requiredTypes: ['String'], actualType: leftLabel },
524
+ });
525
+ return false;
494
526
  }
495
527
  }
496
528
  function isEqualityFamily(family) {
@@ -510,55 +542,106 @@ function comparisonFamilyLabel(family) {
510
542
  function pushComparisonTypeError(node, message, errors, diagnostics, metadata) {
511
543
  pushValueError(node, message, errors, diagnostics, metadata);
512
544
  }
513
- function validateRewriteTargetFunctionUsage(node, errors, diagnostics) {
514
- const functions = new Map();
515
- collectRewriteTargetFunctions(node, [], functions, errors, diagnostics);
516
- for (const functionName of URL_REWRITE_TARGET_SINGLE_USE_FUNCTIONS) {
517
- const nodes = functions.get(functionName) ?? [];
518
- for (const duplicate of nodes.slice(1)) {
519
- pushFuncError(duplicate, `function '${functionName}' can appear only once in url-rewrite-target expressions`, errors, diagnostics, {
520
- id: 'function.rewrite_target.single_use',
521
- params: { functionName, preset: 'url-rewrite-target' },
522
- });
523
- }
545
+ /**
546
+ * Reports functions used more often than Cloudflare allows, nested
547
+ * replacements, and, in rewrite targets, operators.
548
+ */
549
+ function validateFunctionUsage(node, context, errors, diagnostics) {
550
+ const { preset } = context;
551
+ const rewriteTarget = preset === 'url-rewrite-target';
552
+ const usage = { calls: new Map(), nestedReplacements: [], ...(rewriteTarget ? { operators: [] } : {}) };
553
+ collectFunctionUsage(node, [], usage);
554
+ for (const functionName of SINGLE_USE_FUNCTIONS)
555
+ reportSingleUseFunction(functionName, usage, errors, diagnostics);
556
+ if (preset !== 'url-rewrite-filter' && preset !== 'url-rewrite-target')
557
+ return;
558
+ for (const functionName of URL_REWRITE_SINGLE_USE_FUNCTIONS)
559
+ reportSingleUseFunction(functionName, usage, errors, diagnostics);
560
+ for (const { node: nested, parentFunctionName } of usage.nestedReplacements) {
561
+ pushFuncError(nested, `function '${nested.name}' cannot be nested inside '${parentFunctionName}'`, errors, diagnostics, {
562
+ id: 'function.nested_replacement',
563
+ params: { functionName: nested.name, parentFunctionName },
564
+ });
565
+ }
566
+ for (const { operator, node: operatorNode } of usage.operators ?? []) {
567
+ if (isRuleExpressionOperatorAvailable(operator, preset))
568
+ continue;
569
+ errors.push(`operator '${operator}' is not available for ${preset} expressions`);
570
+ diagnostics.push({
571
+ id: 'operator.unavailable',
572
+ params: { operator, preset },
573
+ severity: 'error',
574
+ pos: operatorNode.pos ?? null,
575
+ length: operatorNode.length ?? 0,
576
+ source: 'expression',
577
+ });
578
+ }
579
+ }
580
+ /** Reports every call of a function after its first. */
581
+ function reportSingleUseFunction(functionName, usage, errors, diagnostics) {
582
+ for (const duplicate of (usage.calls.get(functionName) ?? []).slice(1)) {
583
+ pushFuncError(duplicate, `function '${functionName}' can appear only once in an expression`, errors, diagnostics, {
584
+ id: 'function.single_use',
585
+ params: { functionName },
586
+ });
524
587
  }
525
588
  }
526
- function collectRewriteTargetFunctions(node, replacementFunctionStack, functions, errors, diagnostics) {
589
+ /**
590
+ * Whether an argument is a Boolean field or a call used as a condition, such
591
+ * as `(ssl)` or `(has_value(...))`, which Cloudflare evaluates with its IsTrue
592
+ * operator. Other conditions use their own operators, and so do quantifiers.
593
+ * One that recovery cut short may be a comparison instead, and is invalid;
594
+ * see InvalidNode.operand.
595
+ */
596
+ function isTruthTestArgument(arg) {
597
+ if (arg.kind === 'Func')
598
+ return arg.condition === true && arg.name !== 'any' && arg.name !== 'all';
599
+ return arg.kind === 'BoolField';
600
+ }
601
+ /** Collects every function call, nested replacement, and operator in an expression. */
602
+ function collectFunctionUsage(node, replacementFunctionStack, usage) {
527
603
  switch (node.kind) {
528
604
  case 'Func': {
529
605
  const functionName = node.name;
530
- if (URL_REWRITE_TARGET_SINGLE_USE_FUNCTIONS.has(functionName)) {
531
- functions.set(functionName, [...(functions.get(functionName) ?? []), node]);
532
- }
533
- const parentReplacementFunction = replacementFunctionStack.at(-1);
534
- if (parentReplacementFunction && URL_REWRITE_TARGET_NON_NESTABLE_REPLACEMENT_FUNCTIONS.has(functionName)) {
535
- pushFuncError(node, `function '${functionName}' cannot be nested inside '${parentReplacementFunction}' in url-rewrite-target expressions`, errors, diagnostics, {
536
- id: 'function.rewrite_target.nested_replacement',
537
- params: { functionName, parentFunctionName: parentReplacementFunction, preset: 'url-rewrite-target' },
538
- });
606
+ const calls = usage.calls.get(functionName);
607
+ if (calls)
608
+ calls.push(node);
609
+ else
610
+ usage.calls.set(functionName, [node]);
611
+ if (functionName === 'any' || functionName === 'all')
612
+ usage.operators?.push({ operator: functionName, node });
613
+ const parentFunctionName = replacementFunctionStack.at(-1);
614
+ const replacement = URL_REWRITE_NON_NESTABLE_REPLACEMENT_FUNCTIONS.has(functionName);
615
+ if (parentFunctionName && replacement)
616
+ usage.nestedReplacements.push({ node, parentFunctionName });
617
+ const nextReplacementFunctionStack = replacement ? [...replacementFunctionStack, functionName] : replacementFunctionStack;
618
+ for (const arg of node.args) {
619
+ if (isTruthTestArgument(arg))
620
+ usage.operators?.push({ operator: 'is_true', node: arg });
621
+ collectFunctionUsage(arg, nextReplacementFunctionStack, usage);
539
622
  }
540
- const nextReplacementFunctionStack = URL_REWRITE_TARGET_NON_NESTABLE_REPLACEMENT_FUNCTIONS.has(functionName)
541
- ? [...replacementFunctionStack, functionName]
542
- : replacementFunctionStack;
543
- for (const arg of node.args)
544
- collectRewriteTargetFunctions(arg, nextReplacementFunctionStack, functions, errors, diagnostics);
545
623
  return;
546
624
  }
547
625
  case 'And':
548
626
  case 'Or':
549
627
  case 'Xor':
550
- for (const operand of node.operands) {
551
- collectRewriteTargetFunctions(operand, replacementFunctionStack, functions, errors, diagnostics);
552
- }
628
+ usage.operators?.push({ operator: node.kind.toLowerCase(), node });
629
+ for (const operand of node.operands)
630
+ collectFunctionUsage(operand, replacementFunctionStack, usage);
553
631
  return;
554
632
  case 'Not':
555
- collectRewriteTargetFunctions(node.operand, replacementFunctionStack, functions, errors, diagnostics);
633
+ usage.operators?.push({ operator: 'not', node });
634
+ collectFunctionUsage(node.operand, replacementFunctionStack, usage);
556
635
  return;
557
636
  case 'Comparison':
558
- collectRewriteTargetFunctions(node.left, replacementFunctionStack, functions, errors, diagnostics);
559
- if (isDynamicValueNode(node.right)) {
560
- collectRewriteTargetFunctions(node.right, replacementFunctionStack, functions, errors, diagnostics);
561
- }
637
+ usage.operators?.push({ operator: node.op, node });
638
+ collectFunctionUsage(node.left, replacementFunctionStack, usage);
639
+ if (isDynamicValueNode(node.right))
640
+ collectFunctionUsage(node.right, replacementFunctionStack, usage);
641
+ return;
642
+ case 'Invalid':
643
+ if (node.operand)
644
+ collectFunctionUsage(node.operand, replacementFunctionStack, usage);
562
645
  return;
563
646
  case 'Field':
564
647
  case 'BoolField':
@@ -569,6 +652,8 @@ function collectRewriteTargetFunctions(node, replacementFunctionStack, functions
569
652
  case 'SetLiteral':
570
653
  case 'ListRef':
571
654
  return;
655
+ default:
656
+ unhandledNode(node);
572
657
  }
573
658
  }
574
659
  function validateListRef(node, left, op, errors, diagnostics, context) {
@@ -657,7 +742,8 @@ function isRecord(value) {
657
742
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
658
743
  }
659
744
  function validateInlineSetLiteral(node, errors, diagnostics) {
660
- const valueTypes = new Set(node.elements.map(element => element.type));
745
+ // An invalid member is not another element type.
746
+ const valueTypes = new Set(validSetElements(node).map(element => element.type));
661
747
  if (valueTypes.size <= 1)
662
748
  return;
663
749
  pushValueError(node, 'inline list elements must all have the same data type', errors, diagnostics, {
@@ -696,7 +782,7 @@ function hasConsecutiveUnescapedWildcards(pattern) {
696
782
  function pushComparisonError(node, requirement, errors, diagnostics, metadata) {
697
783
  const message = `${requirement}`;
698
784
  errors.push(message);
699
- pushDiagnostic(diagnostics, {
785
+ diagnostics.push({
700
786
  ...metadata,
701
787
  severity: 'error',
702
788
  pos: node.pos,
@@ -707,7 +793,7 @@ function pushComparisonError(node, requirement, errors, diagnostics, metadata) {
707
793
  function pushFuncError(node, requirement, errors, diagnostics, metadata) {
708
794
  const message = `${requirement}`;
709
795
  errors.push(message);
710
- pushDiagnostic(diagnostics, {
796
+ diagnostics.push({
711
797
  ...metadata,
712
798
  severity: 'error',
713
799
  pos: node.pos ?? null,
@@ -718,7 +804,7 @@ function pushFuncError(node, requirement, errors, diagnostics, metadata) {
718
804
  function pushValueError(node, message, errors, diagnostics, metadata) {
719
805
  errors.push(message);
720
806
  const span = argSpan(node);
721
- pushDiagnostic(diagnostics, {
807
+ diagnostics.push({
722
808
  ...metadata,
723
809
  severity: 'error',
724
810
  pos: span.pos,
@@ -726,14 +812,28 @@ function pushValueError(node, message, errors, diagnostics, metadata) {
726
812
  source: 'expression',
727
813
  });
728
814
  }
729
- function validateFunctionSupport(node, warnings, diagnostics) {
815
+ /**
816
+ * Reports a function the preset's Cloudflare phase rejects. Quantifiers are
817
+ * operators, which rewrite targets check separately.
818
+ */
819
+ function validateFunctionAvailability(node, errors, diagnostics, context) {
820
+ const functionName = node.name;
821
+ const { preset } = context;
822
+ if (!preset || functionName === 'any' || functionName === 'all')
823
+ return;
824
+ if (isRuleExpressionFunctionAvailable(functionName, preset))
825
+ return;
826
+ pushFuncError(node, `function '${functionName}' is not available for ${preset} expressions`, errors, diagnostics, {
827
+ id: 'function.unavailable',
828
+ params: { functionName, preset },
829
+ });
830
+ }
831
+ function validateFunctionSupport(node, diagnostics) {
730
832
  const functionName = node.name;
731
833
  const reason = getUnreliableRuleExpressionFunctionReason(functionName);
732
834
  if (!reason)
733
835
  return;
734
- const message = `function '${functionName}' cannot be evaluated reliably: ${reason}`;
735
- pushWarning(warnings, message);
736
- pushDiagnostic(diagnostics, {
836
+ diagnostics.push({
737
837
  id: 'function.unreliable',
738
838
  params: { functionName, reason },
739
839
  severity: 'warning',
@@ -748,17 +848,26 @@ function validateFunctionSupport(node, warnings, diagnostics) {
748
848
  * access are certain: Cloudflare produces nil from map keys, array indexes,
749
849
  * and functions, never from a field itself.
750
850
  */
751
- function validateCoalesceFallbacks(node, warnings, diagnostics) {
752
- const index = node.args.slice(0, -1).findIndex(arg => (isLiteralNode(arg) && arg.kind !== 'SetLiteral' && arg.kind !== 'ListRef') ||
753
- (isFieldNode(arg) && arg.accessPath.length === 0));
851
+ function validateCoalesceFallbacks(node, binding, diagnostics) {
852
+ // An argument counts only where it binds to a parameter for certain, which one that recovery from a
853
+ // syntax error left uncertain does not; see ArgumentBinding.positions. Only the values after it are
854
+ // unused, counting those the parser read, and an empty slot holds none. When some may be another
855
+ // call's, none may follow.
856
+ if (mayHaveFewerArguments(node))
857
+ return;
858
+ const { positions } = binding;
859
+ const index = node.args.findIndex((arg, argIndex) => positions[argIndex] !== null && ((isLiteralNode(arg) && arg.kind !== 'SetLiteral' && arg.kind !== 'ListRef') ||
860
+ (isFieldNode(arg) && arg.accessPath.length === 0) ||
861
+ isConditionArgument(arg)));
754
862
  if (index < 0)
755
863
  return;
756
- const parameterName = `value${index + 1}`;
757
- const unusedArgumentCount = node.args.length - index - 1;
758
- const message = `function 'coalesce' parameter '${parameterName}' is never nil, so the arguments after it are never used`;
864
+ const unusedArgumentCount = node.args.slice(index + 1).filter(arg => !isEmptyArgument(arg)).length;
865
+ if (unusedArgumentCount === 0)
866
+ return;
867
+ // The argument found has a position.
868
+ const parameterName = `value${positions[index] + 1}`;
759
869
  const span = argSpan(node.args[index]);
760
- pushWarning(warnings, message);
761
- pushDiagnostic(diagnostics, {
870
+ diagnostics.push({
762
871
  id: 'function.coalesce.never_nil_argument',
763
872
  params: { functionName: 'coalesce', parameterName, unusedArgumentCount },
764
873
  severity: 'warning',
@@ -767,54 +876,55 @@ function validateCoalesceFallbacks(node, warnings, diagnostics) {
767
876
  source: 'expression',
768
877
  });
769
878
  }
770
- function validateFieldOrFunc(node, guardedHeaders, errors, warnings, diagnostics, expression, context) {
879
+ function validateFieldOrFunc(node, guardedHeaders, errors, diagnostics, expression, context) {
771
880
  if (isFieldNode(node)) {
772
- validateFieldNode(node, guardedHeaders, errors, warnings, diagnostics, expression, context);
881
+ validateFieldNode(node, guardedHeaders, errors, diagnostics, expression, context);
773
882
  return;
774
883
  }
775
- validateSemanticNode(node, guardedHeaders, errors, warnings, diagnostics, expression, context, 'value');
884
+ validateSemanticNode(node, guardedHeaders, errors, diagnostics, expression, context, 'value');
776
885
  }
777
- function validateFuncArgs(node, guardedHeaders, errors, warnings, diagnostics, expression, context) {
886
+ function validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context) {
778
887
  for (const arg of node.args) {
779
888
  if (isFieldNode(arg)) {
780
- validateFieldNode(arg, guardedHeaders, errors, warnings, diagnostics, expression, context);
889
+ validateFieldNode(arg, guardedHeaders, errors, diagnostics, expression, context);
781
890
  }
782
891
  else if (isExpressionNode(arg)) {
783
- validateSemanticNode(arg, guardedHeaders, errors, warnings, diagnostics, expression, context, 'value');
892
+ const position = isConditionArgument(arg) ? 'predicate' : 'value';
893
+ validateSemanticNode(arg, guardedHeaders, errors, diagnostics, expression, context, position);
784
894
  }
785
895
  else if (arg.kind === 'ListRef') {
786
896
  validateFunctionListRefArg(node, arg, errors, diagnostics, context);
787
897
  }
788
898
  }
789
899
  }
790
- function validateQuantifierPredicateArgs(node, guardedHeaders, errors, warnings, diagnostics, expression, context) {
900
+ function validateQuantifierPredicateArgs(node, guardedHeaders, errors, diagnostics, expression, context) {
791
901
  const quantifier = extractQuantifierPredicate(node);
792
902
  if (!quantifier) {
793
903
  const comparison = extractQuantifierComparison(node);
794
904
  if (comparison && !comparison.comparison.right) {
795
- validateFieldOrFunc(comparison.source, guardedHeaders, errors, warnings, diagnostics, expression, context);
905
+ validateFieldOrFunc(comparison.source, guardedHeaders, errors, diagnostics, expression, context);
796
906
  return;
797
907
  }
798
- validateFuncArgs(node, guardedHeaders, errors, warnings, diagnostics, expression, context);
908
+ validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context);
799
909
  return;
800
910
  }
801
- validateFieldOrFunc(quantifier.source, guardedHeaders, errors, warnings, diagnostics, expression, context);
911
+ validateFieldOrFunc(quantifier.source, guardedHeaders, errors, diagnostics, expression, context);
802
912
  if (isDynamicValueNode(quantifier.value)) {
803
- validateFieldOrFunc(quantifier.value, guardedHeaders, errors, warnings, diagnostics, expression, context);
913
+ validateFieldOrFunc(quantifier.value, guardedHeaders, errors, diagnostics, expression, context);
804
914
  }
805
915
  if (quantifier.value.kind === 'ListRef') {
806
916
  validateFunctionListRefArg(node, quantifier.value, errors, diagnostics, context);
807
917
  }
808
918
  }
809
- function validateFunctionArgRequirements(node, errors, diagnostics) {
810
- for (const signatureError of validateFunctionSignature(node)) {
919
+ function validateFunctionArgRequirements(node, binding, errors, diagnostics) {
920
+ for (const signatureError of validateFunctionSignature(node, binding)) {
811
921
  pushFunctionSignatureError(signatureError, errors, diagnostics);
812
922
  }
813
923
  }
814
924
  function pushFunctionSignatureError(signatureError, errors, diagnostics) {
815
925
  errors.push(signatureError.message);
816
926
  const span = argSpan(signatureError.node);
817
- pushDiagnostic(diagnostics, {
927
+ diagnostics.push({
818
928
  id: signatureError.id,
819
929
  ...(signatureError.params ? { params: signatureError.params } : {}),
820
930
  severity: 'error',
@@ -834,11 +944,16 @@ function argSpan(arg) {
834
944
  }
835
945
  return { pos: null, length: 0 };
836
946
  }
837
- function validateFieldNode(node, guardedHeaders, errors, warnings, diagnostics, expression, context) {
947
+ function validateFieldNode(node, guardedHeaders, errors, diagnostics, expression, context) {
838
948
  validateAccessPath(node, errors, diagnostics);
949
+ const lowercaseKey = validateMapKeyCase(node, errors, diagnostics);
839
950
  validateFieldAvailability(node, errors, diagnostics, expression, context);
840
- validateDeprecatedField(node, warnings, diagnostics, expression, context);
841
- if (node.name !== 'http.request.headers')
951
+ validateDeprecatedField(node, diagnostics, expression, context);
952
+ // A guard for a rejected key would only repeat its error.
953
+ if (!REQUEST_HEADER_MAPS.has(node.name) || !lowercaseKey)
954
+ return;
955
+ // An invalid segment may have been the header's key or index, which leaves the ones after it uncertain.
956
+ if (node.accessPath.some(access => access.kind === 'Invalid'))
842
957
  return;
843
958
  const mapKey = node.accessPath.find(access => access.kind === 'MapKeyAccess');
844
959
  const arrayIndex = node.accessPath.find(access => access.kind === 'ArrayIndexAccess');
@@ -848,10 +963,8 @@ function validateFieldNode(node, guardedHeaders, errors, warnings, diagnostics,
848
963
  if (guardedHeaders.has(headerName))
849
964
  return;
850
965
  const fieldExpression = expression.slice(node.pos, node.pos + node.length);
851
- const guardExpression = `any(lower(http.request.headers.names[*])[*] eq "${headerName}")`;
852
- const message = `direct indexed header access '${fieldExpression}' should be grouped with '${guardExpression}' so the header exists before indexing`;
853
- pushWarning(warnings, message);
854
- pushDiagnostic(diagnostics, {
966
+ const guardExpression = `any(lower(${node.name}.names[*])[*] eq ${stringLiteralSource(headerName)})`;
967
+ diagnostics.push({
855
968
  id: 'field.header_index_requires_guard',
856
969
  params: { fieldExpression, guardExpression, headerName },
857
970
  severity: 'warning',
@@ -861,7 +974,8 @@ function validateFieldNode(node, guardedHeaders, errors, warnings, diagnostics,
861
974
  });
862
975
  }
863
976
  function validateAccessPath(node, errors, diagnostics) {
864
- for (const issue of inferRuleExpressionArgument(node).accessIssues) {
977
+ const info = inferRuleExpressionArgument(node);
978
+ for (const issue of info.invalid ? info.accessIssues : []) {
865
979
  const accessLabel = issue.accessKind === 'map-key'
866
980
  ? 'map key'
867
981
  : issue.accessKind === 'array-index' ? 'array index' : 'array wildcard';
@@ -869,7 +983,7 @@ function validateAccessPath(node, errors, diagnostics) {
869
983
  const expectedArticle = issue.expectedType === 'Array' ? 'an' : 'a';
870
984
  const message = `${accessLabel} access requires ${expectedArticle} ${issue.expectedType} value; received ${actualType}`;
871
985
  errors.push(message);
872
- pushDiagnostic(diagnostics, {
986
+ diagnostics.push({
873
987
  id: 'access.type_mismatch',
874
988
  params: {
875
989
  accessKind: issue.accessKind,
@@ -883,21 +997,49 @@ function validateAccessPath(node, errors, diagnostics) {
883
997
  });
884
998
  }
885
999
  }
886
- function validateBoolFieldNode(node, errors, warnings, diagnostics, expression, context) {
1000
+ /**
1001
+ * Map fields with lowercase keys, where Cloudflare rejects a key with an
1002
+ * uppercase letter, ASCII or not (dry runs, 2026-10-09). It accepts one for
1003
+ * raw.http.response.headers, and on a function's result, such as
1004
+ * coalesce(http.request.headers, ...)["X-A"], which reads nil, as the map's
1005
+ * keys are lowercase (2026-10-10).
1006
+ */
1007
+ const LOWERCASE_KEY_MAP_FIELDS = new Set([
1008
+ 'http.request.headers',
1009
+ 'http.response.headers',
1010
+ 'raw.http.request.headers',
1011
+ ]);
1012
+ /** Returns false when it rejects the field's map key. */
1013
+ function validateMapKeyCase(node, errors, diagnostics) {
1014
+ const access = node.accessPath[0];
1015
+ if (!LOWERCASE_KEY_MAP_FIELDS.has(node.name) || access?.kind !== 'MapKeyAccess' || !/\p{Uppercase}/u.test(access.key))
1016
+ return true;
1017
+ errors.push(`map key '${access.key}' of field '${node.name}' must be lowercase`);
1018
+ diagnostics.push({
1019
+ id: 'access.uppercase_map_key',
1020
+ params: { fieldName: node.name, key: access.key },
1021
+ severity: 'error',
1022
+ pos: access.pos ?? null,
1023
+ length: access.length ?? 0,
1024
+ source: 'expression',
1025
+ });
1026
+ return false;
1027
+ }
1028
+ function validateBoolFieldNode(node, errors, diagnostics, expression, context) {
887
1029
  // validateBooleanLiterals() reports `true` and `false`.
888
- if (node.name === 'true' || node.name === 'false')
1030
+ if (isBooleanLiteralName(node.name))
889
1031
  return;
890
1032
  validateFieldAvailability(node, errors, diagnostics, expression, context);
891
- validateDeprecatedField(node, warnings, diagnostics, expression, context);
1033
+ validateDeprecatedField(node, diagnostics, expression, context);
892
1034
  if (!isKnownFieldName(node.name))
893
1035
  return;
894
- const type = inferRuleExpressionArgument({ kind: 'Field', name: node.name, accessPath: [], pos: node.pos ?? 0, length: node.length ?? 0 }).type;
895
- if (isUnknownRuleExpressionDataType(type) || (type.kind === 'scalar' && type.name === 'Boolean'))
1036
+ const type = fieldDataType(node.name);
1037
+ if (isUnknownRuleExpressionDataType(type) || isBooleanType(type))
896
1038
  return;
897
1039
  const actualType = formatRuleExpressionDataType(type);
898
1040
  const message = `field '${node.name}' must be Boolean in predicate position; received ${actualType}`;
899
1041
  errors.push(message);
900
- pushDiagnostic(diagnostics, {
1042
+ diagnostics.push({
901
1043
  id: 'field.predicate_type_mismatch',
902
1044
  params: { fieldName: node.name, expectedType: 'Boolean', actualType },
903
1045
  severity: 'error',
@@ -914,9 +1056,9 @@ function validateBooleanLiterals(root, errors, diagnostics) {
914
1056
  if (root.kind === 'BoolField' && root.name === RULE_EXPRESSION_MATCH_ALL_EXPRESSION)
915
1057
  return;
916
1058
  const visit = (node) => {
917
- switch (node?.kind) {
1059
+ switch (node.kind) {
918
1060
  case 'BoolField':
919
- if (node.name === 'true' || node.name === 'false')
1061
+ if (isBooleanLiteralName(node.name))
920
1062
  pushBooleanLiteralError(node, node.name, errors, diagnostics);
921
1063
  return;
922
1064
  case 'BoolLiteral':
@@ -924,7 +1066,8 @@ function validateBooleanLiterals(root, errors, diagnostics) {
924
1066
  return;
925
1067
  case 'Comparison':
926
1068
  visit(node.left);
927
- visit(node.right);
1069
+ if (node.right)
1070
+ visit(node.right);
928
1071
  return;
929
1072
  case 'Func':
930
1073
  node.args.forEach(visit);
@@ -937,6 +1080,19 @@ function validateBooleanLiterals(root, errors, diagnostics) {
937
1080
  case 'Xor':
938
1081
  node.operands.forEach(visit);
939
1082
  return;
1083
+ case 'Invalid':
1084
+ if (node.operand)
1085
+ visit(node.operand);
1086
+ return;
1087
+ case 'Field':
1088
+ case 'StringLiteral':
1089
+ case 'NumberLiteral':
1090
+ case 'IpLiteral':
1091
+ case 'SetLiteral':
1092
+ case 'ListRef':
1093
+ return;
1094
+ default:
1095
+ unhandledNode(node);
940
1096
  }
941
1097
  };
942
1098
  visit(root);
@@ -944,7 +1100,7 @@ function validateBooleanLiterals(root, errors, diagnostics) {
944
1100
  function pushBooleanLiteralError(node, literal, errors, diagnostics) {
945
1101
  const message = `'${literal}' is not a value; Cloudflare accepts 'true' only as the entire expression`;
946
1102
  errors.push(message);
947
- pushDiagnostic(diagnostics, {
1103
+ diagnostics.push({
948
1104
  id: 'rule_expression.boolean_literal',
949
1105
  params: { literal },
950
1106
  severity: 'error',
@@ -953,16 +1109,12 @@ function pushBooleanLiteralError(node, literal, errors, diagnostics) {
953
1109
  source: 'expression',
954
1110
  });
955
1111
  }
956
- function validateDeprecatedField(node, warnings, diagnostics, expression, context) {
1112
+ function validateDeprecatedField(node, diagnostics, expression, context) {
957
1113
  if (!context.deprecationNotices || !KNOWN_DEPRECATED_FIELDS.has(node.name))
958
1114
  return;
959
- const replacement = deprecatedFieldReplacement(node.name);
1115
+ const replacement = availableReplacement(node.name, context.fieldAvailability);
960
1116
  const fieldExpression = expressionForNode(node, expression);
961
- const message = replacement
962
- ? `field '${fieldExpression}' is deprecated; use '${replacement}' instead`
963
- : `field '${fieldExpression}' is deprecated`;
964
- pushWarning(warnings, message);
965
- pushDiagnostic(diagnostics, {
1117
+ diagnostics.push({
966
1118
  id: 'field.deprecated',
967
1119
  params: replacement
968
1120
  ? { fieldExpression, replacement }
@@ -973,6 +1125,17 @@ function validateDeprecatedField(node, warnings, diagnostics, expression, contex
973
1125
  source: 'expression',
974
1126
  });
975
1127
  }
1128
+ /**
1129
+ * The replacement of a deprecated field, where it is available. Cloudflare
1130
+ * judges an alias by its own verdict, so a replacement can be unavailable
1131
+ * where the alias is not.
1132
+ */
1133
+ function availableReplacement(field, rules) {
1134
+ const replacement = deprecatedFieldReplacement(field);
1135
+ if (!replacement || !rules || isRuleExpressionFieldAvailable({ name: replacement }, rules))
1136
+ return replacement;
1137
+ return undefined;
1138
+ }
976
1139
  function validateFieldAvailability(node, errors, diagnostics, expression, context) {
977
1140
  // Unknown fields are invalid in every product, whatever its field availability.
978
1141
  if (!isKnownFieldName(node.name)) {
@@ -982,13 +1145,17 @@ function validateFieldAvailability(node, errors, diagnostics, expression, contex
982
1145
  const rules = context.fieldAvailability;
983
1146
  if (!rules)
984
1147
  return;
985
- const map = isFieldNode(node) && node.accessPath.some(access => access.kind === 'MapKeyAccess');
1148
+ const accessPath = isFieldNode(node) ? node.accessPath : [];
1149
+ const map = accessPath.some(access => access.kind === 'MapKeyAccess');
986
1150
  if (isRuleExpressionFieldAvailable({ name: node.name, map }, rules))
987
1151
  return;
1152
+ // An invalid segment may have been a map key, so the field is unavailable only if it is either way.
1153
+ if (accessPath.some(access => access.kind === 'Invalid') && isRuleExpressionFieldAvailable({ name: node.name, map: true }, rules))
1154
+ return;
988
1155
  const fieldExpression = expressionForNode(node, expression);
989
1156
  const message = `field '${fieldExpression}' is not available for ${rules.preset} expressions`;
990
1157
  errors.push(message);
991
- pushDiagnostic(diagnostics, {
1158
+ diagnostics.push({
992
1159
  id: 'field.unavailable',
993
1160
  params: { fieldExpression, fieldName: node.name, preset: rules.preset },
994
1161
  severity: 'error',
@@ -1001,7 +1168,7 @@ function pushUnknownFieldError(node, errors, diagnostics, expression) {
1001
1168
  const fieldExpression = expressionForNode(node, expression);
1002
1169
  const message = `unknown field '${fieldExpression}'`;
1003
1170
  errors.push(message);
1004
- pushDiagnostic(diagnostics, {
1171
+ diagnostics.push({
1005
1172
  id: 'field.unknown',
1006
1173
  params: { fieldExpression, fieldName: node.name },
1007
1174
  severity: 'error',
@@ -1015,19 +1182,21 @@ function expressionForNode(node, expression) {
1015
1182
  ? expression.slice(node.pos, node.pos + node.length)
1016
1183
  : node.name;
1017
1184
  }
1018
- function deprecatedFieldReplacement(field) {
1019
- if (!KNOWN_DEPRECATED_FIELDS.has(field))
1020
- return undefined;
1021
- return DEPRECATED_FIELD_REPLACEMENTS[field];
1022
- }
1023
1185
  function collectHeaderPresenceGuards(node) {
1024
1186
  switch (node.kind) {
1025
1187
  case 'And':
1026
1188
  return node.operands.reduce((guards, operand) => unionHeaderGuards(guards, collectHeaderPresenceGuards(operand)), new Set());
1027
1189
  case 'Func':
1028
1190
  return getHeaderPresenceGuardNames(node);
1029
- default:
1191
+ case 'Comparison':
1192
+ case 'BoolField':
1193
+ case 'Or':
1194
+ case 'Xor':
1195
+ case 'Not':
1196
+ case 'Invalid':
1030
1197
  return new Set();
1198
+ default:
1199
+ return unhandledNode(node);
1031
1200
  }
1032
1201
  }
1033
1202
  function getHeaderPresenceGuardNames(node) {
@@ -1052,15 +1221,16 @@ function getHeaderPresenceGuardNames(node) {
1052
1221
  }
1053
1222
  return names;
1054
1223
  }
1224
+ /**
1225
+ * Whether a guard reads request header names, plain or through lower(). A
1226
+ * guard on either names field counts for both header maps: Cloudflare
1227
+ * documents only the raw fields as unaffected by transforms, but live
1228
+ * requests showed the plain ones list the headers from before them too
1229
+ * (2026-10-09).
1230
+ */
1055
1231
  function isHeaderNamesCollection(node) {
1056
- if (isFieldNode(node)) {
1057
- return isArrayExpandedNode(node) && node.name === 'http.request.headers.names';
1058
- }
1059
- if (isFuncNode(node) && node.name === 'lower' && isArrayExpandedNode(node)) {
1060
- const arg = node.args[0];
1061
- return isFieldNode(arg) && isArrayExpandedNode(arg) && arg.name === 'http.request.headers.names';
1062
- }
1063
- return false;
1232
+ const names = isFuncNode(node) && node.name === 'lower' && isArrayExpandedNode(node) ? node.args[0] : node;
1233
+ return isFieldNode(names) && isArrayExpandedNode(names) && REQUEST_HEADER_ARRAYS.get(names.name) === 'names';
1064
1234
  }
1065
1235
  function unionHeaderGuards(left, right) {
1066
1236
  return new Set([...left, ...right]);