@libreflare/worker-runtime 0.5.11 → 0.7.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 (113) hide show
  1. package/README.md +120 -22
  2. package/dist/rule-evaluator/accept-encoding.d.ts +2 -1
  3. package/dist/rule-evaluator/accept-encoding.d.ts.map +1 -1
  4. package/dist/rule-evaluator/accept-encoding.js +27 -30
  5. package/dist/rule-evaluator/accept-encoding.js.map +1 -1
  6. package/dist/rule-evaluator/access-values.d.ts +28 -0
  7. package/dist/rule-evaluator/access-values.d.ts.map +1 -0
  8. package/dist/rule-evaluator/access-values.js +60 -0
  9. package/dist/rule-evaluator/access-values.js.map +1 -0
  10. package/dist/rule-evaluator/analysis.d.ts +31 -18
  11. package/dist/rule-evaluator/analysis.d.ts.map +1 -1
  12. package/dist/rule-evaluator/analysis.js +46 -127
  13. package/dist/rule-evaluator/analysis.js.map +1 -1
  14. package/dist/rule-evaluator/ast.d.ts +36 -17
  15. package/dist/rule-evaluator/ast.d.ts.map +1 -1
  16. package/dist/rule-evaluator/ast.js +5 -0
  17. package/dist/rule-evaluator/ast.js.map +1 -1
  18. package/dist/rule-evaluator/comparison.d.ts +16 -0
  19. package/dist/rule-evaluator/comparison.d.ts.map +1 -0
  20. package/dist/rule-evaluator/comparison.js +43 -0
  21. package/dist/rule-evaluator/comparison.js.map +1 -0
  22. package/dist/rule-evaluator/constants.d.ts +7 -3
  23. package/dist/rule-evaluator/constants.d.ts.map +1 -1
  24. package/dist/rule-evaluator/constants.js +7 -1
  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 +6 -0
  28. package/dist/rule-evaluator/custom-lists.d.ts.map +1 -1
  29. package/dist/rule-evaluator/custom-lists.js +21 -1
  30. package/dist/rule-evaluator/custom-lists.js.map +1 -1
  31. package/dist/rule-evaluator/diagnostics.d.ts +10 -7
  32. package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
  33. package/dist/rule-evaluator/diagnostics.js +31 -1
  34. package/dist/rule-evaluator/diagnostics.js.map +1 -1
  35. package/dist/rule-evaluator/evaluator.d.ts +10 -3
  36. package/dist/rule-evaluator/evaluator.d.ts.map +1 -1
  37. package/dist/rule-evaluator/evaluator.js +85 -78
  38. package/dist/rule-evaluator/evaluator.js.map +1 -1
  39. package/dist/rule-evaluator/explain.d.ts +11 -2
  40. package/dist/rule-evaluator/explain.d.ts.map +1 -1
  41. package/dist/rule-evaluator/explain.js +217 -121
  42. package/dist/rule-evaluator/explain.js.map +1 -1
  43. package/dist/rule-evaluator/field-availability.d.ts +2 -2
  44. package/dist/rule-evaluator/field-availability.d.ts.map +1 -1
  45. package/dist/rule-evaluator/field-availability.js +9 -3
  46. package/dist/rule-evaluator/field-availability.js.map +1 -1
  47. package/dist/rule-evaluator/field-descriptions.d.ts +1 -1
  48. package/dist/rule-evaluator/field-descriptions.d.ts.map +1 -1
  49. package/dist/rule-evaluator/field-descriptions.generated.d.ts +129 -2
  50. package/dist/rule-evaluator/field-descriptions.generated.d.ts.map +1 -1
  51. package/dist/rule-evaluator/field-descriptions.generated.js +289 -3
  52. package/dist/rule-evaluator/field-descriptions.generated.js.map +1 -1
  53. package/dist/rule-evaluator/fields.d.ts +14 -3
  54. package/dist/rule-evaluator/fields.d.ts.map +1 -1
  55. package/dist/rule-evaluator/fields.js +188 -43
  56. package/dist/rule-evaluator/fields.js.map +1 -1
  57. package/dist/rule-evaluator/function-descriptions.d.ts +2 -0
  58. package/dist/rule-evaluator/function-descriptions.d.ts.map +1 -1
  59. package/dist/rule-evaluator/function-descriptions.generated.d.ts +14 -0
  60. package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
  61. package/dist/rule-evaluator/function-descriptions.generated.js +25 -0
  62. package/dist/rule-evaluator/function-descriptions.generated.js.map +1 -1
  63. package/dist/rule-evaluator/function-descriptions.js.map +1 -1
  64. package/dist/rule-evaluator/function-signature-validation.d.ts +1 -1
  65. package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
  66. package/dist/rule-evaluator/function-signature-validation.js +147 -33
  67. package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
  68. package/dist/rule-evaluator/functions.d.ts +18 -5
  69. package/dist/rule-evaluator/functions.d.ts.map +1 -1
  70. package/dist/rule-evaluator/functions.js +281 -183
  71. package/dist/rule-evaluator/functions.js.map +1 -1
  72. package/dist/rule-evaluator/minifier.d.ts +2 -6
  73. package/dist/rule-evaluator/minifier.d.ts.map +1 -1
  74. package/dist/rule-evaluator/minifier.js +9 -9
  75. package/dist/rule-evaluator/minifier.js.map +1 -1
  76. package/dist/rule-evaluator/normalizer.d.ts +2 -6
  77. package/dist/rule-evaluator/normalizer.d.ts.map +1 -1
  78. package/dist/rule-evaluator/normalizer.js +8 -8
  79. package/dist/rule-evaluator/normalizer.js.map +1 -1
  80. package/dist/rule-evaluator/operators.d.ts +21 -2
  81. package/dist/rule-evaluator/operators.d.ts.map +1 -1
  82. package/dist/rule-evaluator/operators.js +162 -104
  83. package/dist/rule-evaluator/operators.js.map +1 -1
  84. package/dist/rule-evaluator/outcome.d.ts +63 -0
  85. package/dist/rule-evaluator/outcome.d.ts.map +1 -0
  86. package/dist/rule-evaluator/outcome.js +78 -0
  87. package/dist/rule-evaluator/outcome.js.map +1 -0
  88. package/dist/rule-evaluator/parser.d.ts +8 -2
  89. package/dist/rule-evaluator/parser.d.ts.map +1 -1
  90. package/dist/rule-evaluator/parser.js +118 -102
  91. package/dist/rule-evaluator/parser.js.map +1 -1
  92. package/dist/rule-evaluator/quantifier.d.ts +2 -2
  93. package/dist/rule-evaluator/quantifier.d.ts.map +1 -1
  94. package/dist/rule-evaluator/rule-language-types.d.ts +46 -12
  95. package/dist/rule-evaluator/rule-language-types.d.ts.map +1 -1
  96. package/dist/rule-evaluator/rule-language-types.js +195 -69
  97. package/dist/rule-evaluator/rule-language-types.js.map +1 -1
  98. package/dist/rule-evaluator/tokenizer.d.ts.map +1 -1
  99. package/dist/rule-evaluator/tokenizer.js +25 -0
  100. package/dist/rule-evaluator/tokenizer.js.map +1 -1
  101. package/dist/rule-evaluator/validation.d.ts +8 -9
  102. package/dist/rule-evaluator/validation.d.ts.map +1 -1
  103. package/dist/rule-evaluator/validation.js +249 -82
  104. package/dist/rule-evaluator/validation.js.map +1 -1
  105. package/dist/rule-evaluator/values.d.ts +26 -0
  106. package/dist/rule-evaluator/values.d.ts.map +1 -0
  107. package/dist/rule-evaluator/values.js +55 -0
  108. package/dist/rule-evaluator/values.js.map +1 -0
  109. package/dist/rule-evaluator.d.ts +4 -4
  110. package/dist/rule-evaluator.d.ts.map +1 -1
  111. package/dist/rule-evaluator.js +1 -1
  112. package/dist/rule-evaluator.js.map +1 -1
  113. package/package.json +2 -2
@@ -1,8 +1,10 @@
1
- import { pushWarning } from './ast.js';
1
+ import { isDynamicValueNode, pushWarning, } from './ast.js';
2
+ import { applyValueAccessPath, RuleMapValue } from './access-values.js';
2
3
  import { resolveFieldNode } from './fields.js';
3
- import { applyOp, findMatchingSetMember, literalValue } from './operators.js';
4
+ import { applyOp, compareOperands, findMatchingSetMember, literalValue } from './operators.js';
5
+ import { andOutcome, isUnknown, known, negateOutcome, orOutcome, outcomeValue, unavailable, } from './outcome.js';
4
6
  import { extractQuantifierPredicate } from './quantifier.js';
5
- import { baseFunctionName, isArrayMappedFunctionNode } from './rule-language-types.js';
7
+ import { collectionElementDataType, compareRuleExpressionDataTypes, inferFunctionInvocation, inferRuleExpressionArgument, } from './rule-language-types.js';
6
8
  const UNRELIABLE_FUNCTION_REASONS = {
7
9
  bit_slice: 'packet bit slicing is not available in Worker request context',
8
10
  is_jwt_present: 'Cloudflare API JWT token configurations are not available in Worker request context',
@@ -14,17 +16,36 @@ const UNRELIABLE_FUNCTION_REASONS = {
14
16
  export function getUnreliableRuleExpressionFunctionReason(name) {
15
17
  return UNRELIABLE_FUNCTION_REASONS[name];
16
18
  }
17
- export function resolveCollectionValues(fieldArg, ctx) {
18
- const raw = fieldArg.kind === 'Func' && fieldArg.name.endsWith('_array')
19
- ? evaluateFuncArray(fieldArg, ctx)
20
- : evaluateArgValue(fieldArg, ctx);
21
- if (Array.isArray(raw))
22
- return raw.filter((value) => typeof value === 'string' || typeof value === 'number');
23
- if (raw === null)
24
- return [];
25
- if (typeof raw === 'number')
26
- return [raw];
27
- return [String(raw)];
19
+ /**
20
+ * Evaluates a field or function comparison operand. A null value is a
21
+ * Cloudflare missing value.
22
+ */
23
+ export function evaluateOperand(node, ctx) {
24
+ return withoutMap(node.kind === 'Func' ? evaluateFuncValue(node, ctx) : resolveFieldNode(node, ctx));
25
+ }
26
+ /**
27
+ * Narrows a value to a rule-language value. Only coalesce(), has_key(), and
28
+ * postfix access read maps, and validation rejects maps anywhere else, so a
29
+ * map here is unknown.
30
+ */
31
+ function withoutMap(evaluated) {
32
+ if (isUnknown(evaluated))
33
+ return evaluated;
34
+ return evaluated.value instanceof RuleMapValue ? unavailable('a map value') : known(evaluated.value);
35
+ }
36
+ /** Evaluates the values an any()/all() collection yields. */
37
+ export function evaluateCollection(fieldArg, ctx) {
38
+ const evaluated = evaluateOperand(fieldArg, ctx);
39
+ if (isUnknown(evaluated))
40
+ return evaluated;
41
+ const { value } = evaluated;
42
+ if (Array.isArray(value))
43
+ return known(value.filter((item) => typeof item === 'string' || typeof item === 'number'));
44
+ if (value === null)
45
+ return known([]);
46
+ if (typeof value === 'number')
47
+ return known([value]);
48
+ return known([String(value)]);
28
49
  }
29
50
  export function findMatchedSetMemberForFunc(node, ctx) {
30
51
  if (node.name !== 'any' && node.name !== 'all')
@@ -34,7 +55,10 @@ export function findMatchedSetMemberForFunc(node, ctx) {
34
55
  return null;
35
56
  if (quantifier.op !== 'in' || quantifier.value.kind !== 'SetLiteral')
36
57
  return null;
37
- for (const v of resolveCollectionValues(quantifier.source, ctx)) {
58
+ const collection = evaluateCollection(quantifier.source, ctx);
59
+ if (isUnknown(collection))
60
+ return null;
61
+ for (const v of collection.value) {
38
62
  const matchedValue = findMatchingSetMember(v, quantifier.value);
39
63
  if (matchedValue !== null)
40
64
  return matchedValue;
@@ -42,173 +66,222 @@ export function findMatchedSetMemberForFunc(node, ctx) {
42
66
  return null;
43
67
  }
44
68
  /**
45
- * Evaluates a function node as a boolean predicate.
69
+ * Evaluates a function node as a condition. A condition computed from a value
70
+ * this evaluator cannot resolve is unknown.
46
71
  */
47
- export function evaluateFuncBool(node, ctx) {
48
- const { name, args } = node;
49
- if (name === 'any' || name === 'all') {
50
- const quantifier = extractQuantifierPredicate(node);
51
- if (!quantifier)
52
- return false;
53
- const arr = resolveCollectionValues(quantifier.source, ctx);
54
- const check = (v) => {
55
- const result = applyOp(quantifier.op, v, quantifier.value, ctx.warnings, ctx.customLists);
56
- return quantifier.negated && result !== null ? !result : result;
57
- };
58
- if (name === 'any') {
59
- const results = arr.map(check);
60
- if (results.some(result => result === true))
61
- return true;
62
- if (results.some(result => result === null))
63
- return null;
64
- return false;
65
- }
66
- if (name === 'all') {
67
- const results = arr.map(check);
68
- if (results.some(result => result === false))
69
- return false;
70
- if (results.some(result => result === null))
71
- return null;
72
- return true;
73
- }
74
- }
75
- if (name === 'starts_with' || name === 'ends_with') {
76
- const val = evaluateArgValue(args[0], ctx);
77
- const needle = evaluateArgValue(args[1], ctx);
78
- if (val === null || needle === null)
79
- return false;
80
- return name === 'starts_with'
81
- ? String(val).startsWith(String(needle))
82
- : String(val).endsWith(String(needle));
83
- }
84
- if (name === 'has_key') {
85
- return evaluateHasKey(args[0], evaluateArgValue(args[1], ctx), ctx);
86
- }
87
- if (name === 'has_value') {
88
- return evaluateHasValue(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx));
89
- }
90
- if (name === 'is_jwt_present' || name === 'is_jwt_valid' || name === 'is_timed_hmac_valid_v0') {
91
- warnUnreliableFunction(ctx, name);
72
+ export function evaluateFuncPredicate(node, ctx) {
73
+ if (node.name === 'any' || node.name === 'all')
74
+ return evaluateQuantifier(node, ctx);
75
+ // Other functions match when they return true. A nil result, such as
76
+ // has_key() with a nil key, does not match.
77
+ const evaluated = evaluateFuncValue(node, ctx);
78
+ return isUnknown(evaluated) ? evaluated : evaluated.value === true;
79
+ }
80
+ function evaluateQuantifier(node, ctx) {
81
+ const quantifier = extractQuantifierPredicate(node);
82
+ if (!quantifier)
92
83
  return false;
93
- }
94
- return false;
84
+ const collection = evaluateCollection(quantifier.source, ctx);
85
+ if (isUnknown(collection))
86
+ return collection;
87
+ const compare = comparatorFor(node, quantifier, ctx);
88
+ const outcomes = collection.value.map((value) => {
89
+ const outcome = compare(value);
90
+ return quantifier.negated ? negateOutcome(outcome) : outcome;
91
+ });
92
+ return node.name === 'any' ? orOutcome(outcomes) : andOutcome(outcomes);
95
93
  }
96
- // Evaluate a FuncNode as a scalar value (for transforms used as left side of comparison or as arguments)
94
+ /**
95
+ * Returns a comparison of collection values against the quantifier's
96
+ * right-hand value. A dynamic value is resolved once, when the first value is
97
+ * compared, so an empty collection settles any()/all() without reading it. An
98
+ * unknown value, or values Cloudflare would not compare, make the comparison
99
+ * unknown.
100
+ */
101
+ function comparatorFor(node, quantifier, ctx) {
102
+ const { op, value: right } = quantifier;
103
+ if (right.kind === 'ListRef' || right.kind === 'SetLiteral')
104
+ return left => applyOp(op, left, right, ctx.customLists);
105
+ const elementType = collectionElementDataType(inferRuleExpressionArgument(quantifier.source).type)
106
+ ?? { kind: 'unknown' };
107
+ const rightType = inferRuleExpressionArgument(right).type;
108
+ let operand;
109
+ return (left) => {
110
+ operand ??= isDynamicValueNode(right) ? evaluateOperand(right, ctx) : known(literalValue(right));
111
+ if (isUnknown(operand))
112
+ return operand;
113
+ const outcome = compareOperands(op, { value: left, type: elementType }, { value: operand.value, type: rightType }, ctx.warnings);
114
+ if (isUnknown(outcome) && outcome.cause.kind === 'incomparable') {
115
+ pushWarning(ctx.warnings, `comparison in '${node.raw}' cannot be evaluated: ${outcome.cause.reason}`);
116
+ }
117
+ return outcome;
118
+ };
119
+ }
120
+ /**
121
+ * Evaluates a function call as a value and applies its postfix access, as for
122
+ * fields. The result may be a map, such as coalesce() over map fields.
123
+ */
97
124
  export function evaluateFuncValue(node, ctx) {
125
+ const invocation = inferFunctionInvocation(node);
126
+ const evaluated = invocation.mapped
127
+ ? evaluateFuncArray(node, ctx, invocation)
128
+ : evaluateDirectFuncValue(node, ctx, invocation);
129
+ if (isUnknown(evaluated))
130
+ return evaluated;
131
+ return known(applyValueAccessPath(evaluated.value, node.accessPath));
132
+ }
133
+ function evaluateDirectFuncValue(node, ctx, invocation, firstArgumentValue) {
98
134
  const { name, args } = node;
99
- if (isArrayMappedFunctionNode(node))
100
- return toCfArray(evaluateFuncArray(node, ctx));
135
+ const runtimeArgument = (index) => index === 0 && firstArgumentValue !== undefined
136
+ ? known(firstArgumentValue)
137
+ : evaluateArgValue(args[index], ctx);
138
+ const argument = (index) => withoutMap(runtimeArgument(index));
101
139
  switch (name) {
140
+ case 'all':
141
+ case 'any':
142
+ return outcomeValue(evaluateQuantifier(node, ctx));
143
+ case 'coalesce':
144
+ // Arguments after the first present value are never read.
145
+ for (let index = 0; index < args.length; index++) {
146
+ const value = runtimeArgument(index);
147
+ if (isUnknown(value) || value.value !== null)
148
+ return value;
149
+ }
150
+ return known(null);
151
+ case 'has_key': {
152
+ // A nil key gives nil without reading the map, as Cloudflare documents.
153
+ const key = argument(1);
154
+ if (isUnknown(key) || key.value === null)
155
+ return key;
156
+ const map = runtimeArgument(0);
157
+ if (isUnknown(map))
158
+ return map;
159
+ if (!(map.value instanceof RuleMapValue))
160
+ return unavailable('a map value');
161
+ return known(map.value.get(String(key.value)) !== null);
162
+ }
163
+ case 'lookup_json_integer':
164
+ return lookupJsonValue('integer', args.length, argument);
165
+ case 'lookup_json_string':
166
+ return lookupJsonValue('string', args.length, argument);
102
167
  case 'bit_slice':
103
- warnUnreliableFunction(ctx, name);
104
- return 0;
168
+ case 'is_jwt_present':
169
+ case 'is_jwt_valid':
170
+ case 'is_timed_hmac_valid_v0':
171
+ case 'sha256':
172
+ case 'uuidv4':
173
+ return unreliableFunction(ctx, name);
174
+ }
175
+ // Other functions read every argument, so an unknown argument makes the result unknown.
176
+ const values = [];
177
+ for (let index = 0; index < args.length; index++) {
178
+ const value = argument(index);
179
+ if (isUnknown(value))
180
+ return value;
181
+ values.push(value.value);
182
+ }
183
+ const value = functionResult(name, values, invocation);
184
+ return value === undefined ? unavailable(functionSource(name)) : known(value);
185
+ }
186
+ /** Computes a function result from its argument values, or undefined for a function this evaluator does not implement. */
187
+ function functionResult(name, values, invocation) {
188
+ // An omitted optional argument is null, which functions treat as absent.
189
+ const at = (index) => values[index] ?? null;
190
+ switch (name) {
105
191
  case 'cidr':
106
- return evaluateCidr(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx), evaluateArgValue(args[2], ctx));
192
+ return evaluateCidr(at(0), at(1), at(2));
107
193
  case 'cidr6':
108
- return evaluateCidr(evaluateArgValue(args[0], ctx), 32, evaluateArgValue(args[1], ctx));
194
+ return evaluateCidr(at(0), 32, at(1));
109
195
  case 'concat':
110
- return concatValues(args.map(arg => evaluateArgValue(arg, ctx)));
196
+ return concatValues(values, invocation.argumentTypes);
111
197
  case 'decode_base64':
112
- return decodeBase64Value(evaluateArgValue(args[0], ctx));
198
+ return decodeBase64Value(at(0));
113
199
  case 'encode_base64':
114
- return encodeBase64Value(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx));
200
+ return encodeBase64Value(at(0), at(1));
201
+ case 'ends_with':
202
+ case 'starts_with':
203
+ return matchesAffix(name, at(0), at(1));
204
+ case 'has_value':
205
+ return evaluateHasValue(at(0), at(1));
115
206
  case 'join':
116
- return joinValues(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx));
207
+ return joinValues(at(0), at(1));
117
208
  case 'len':
118
- return lengthOfValue(evaluateArgValue(args[0], ctx));
119
- case 'lookup_json_integer':
120
- return lookupJsonValue(args, ctx, 'integer');
121
- case 'lookup_json_string':
122
- return lookupJsonValue(args, ctx, 'string');
209
+ return lengthOfValue(at(0));
123
210
  case 'lower':
124
- return mapStringValue(evaluateArgValue(args[0], ctx), value => value.toLowerCase());
211
+ return mapStringValue(at(0), value => value.toLowerCase());
125
212
  case 'regex_replace':
126
- return regexReplace(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx), evaluateArgValue(args[2], ctx));
213
+ return regexReplace(at(0), at(1), at(2));
127
214
  case 'remove_bytes':
128
- return removeBytes(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx));
215
+ return removeBytes(at(0), at(1));
129
216
  case 'remove_query_args':
130
- return removeQueryArgs(evaluateArgValue(args[0], ctx), args.slice(1).map(arg => evaluateArgValue(arg, ctx)));
131
- case 'sha256':
132
- warnUnreliableFunction(ctx, name);
133
- return evaluateArgValue(args[0], ctx);
217
+ return removeQueryArgs(at(0), values.slice(1));
134
218
  case 'split':
135
- return splitValue(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx), evaluateArgValue(args[2], ctx));
219
+ return splitValue(at(0), at(1), at(2));
136
220
  case 'substring':
137
- return substringValue(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx), evaluateArgValue(args[2], ctx));
221
+ return substringValue(at(0), at(1), at(2));
138
222
  case 'to_string':
139
- return mapStringValue(evaluateArgValue(args[0], ctx), value => value);
223
+ return mapStringValue(at(0), value => value);
140
224
  case 'upper':
141
- return mapStringValue(evaluateArgValue(args[0], ctx), value => value.toUpperCase());
225
+ return mapStringValue(at(0), value => value.toUpperCase());
142
226
  case 'url_decode':
143
- return urlDecodeValue(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx));
144
- case 'uuidv4':
145
- warnUnreliableFunction(ctx, name);
146
- return globalThis.crypto?.randomUUID?.()
147
- ?? '00000000-0000-4000-8000-000000000000';
227
+ return urlDecodeValue(at(0), at(1));
148
228
  case 'wildcard_replace':
149
- return wildcardReplaceValue(evaluateArgValue(args[0], ctx), evaluateArgValue(args[1], ctx), evaluateArgValue(args[2], ctx), evaluateArgValue(args[3], ctx));
229
+ return wildcardReplaceValue(at(0), at(1), at(2), at(3));
150
230
  default:
151
- return null;
231
+ return undefined;
152
232
  }
153
233
  }
154
- function evaluateFuncArray(node, ctx) {
155
- const functionName = baseFunctionName(node.name);
156
- if (functionName === 'split') {
157
- const value = evaluateFuncValue({ kind: 'Func', name: functionName, args: node.args, raw: node.raw }, ctx);
158
- return Array.isArray(value) ? value.filter((item) => typeof item === 'string' || typeof item === 'number') : [];
159
- }
160
- const sourceValues = resolveCollectionValues(node.args[0], ctx);
161
- const restArgs = node.args.slice(1);
234
+ function evaluateFuncArray(node, ctx, invocation) {
235
+ const source = withoutMap(evaluateArgValue(node.args[0], ctx));
236
+ if (isUnknown(source))
237
+ return source;
238
+ if (source.value === null)
239
+ return known([]);
240
+ const sourceValues = Array.isArray(source.value) ? source.value : [source.value];
162
241
  const results = [];
163
- for (const value of sourceValues) {
164
- const transformed = evaluateFuncValue({
165
- kind: 'Func',
166
- name: functionName,
167
- args: [{ kind: 'StringLiteral', value: String(value) }, ...restArgs],
168
- raw: node.raw,
169
- }, ctx);
170
- if (typeof transformed === 'string' || typeof transformed === 'number')
171
- results.push(transformed);
242
+ for (const sourceValue of sourceValues) {
243
+ const element = withoutMap(evaluateDirectFuncValue(node, ctx, invocation, sourceValue));
244
+ if (isUnknown(element))
245
+ return element;
246
+ if (element.value !== null)
247
+ results.push(element.value);
172
248
  }
173
- return results;
174
- }
175
- function toCfArray(values) {
176
- if (values.every(value => typeof value === 'number'))
177
- return values;
178
- return values.map(value => String(value));
249
+ return known(results);
179
250
  }
180
251
  function evaluateArgValue(arg, ctx) {
252
+ // An omitted optional argument is null, which functions treat as absent.
181
253
  if (!arg || typeof arg !== 'object' || !('kind' in arg))
182
- return null;
183
- if (arg.kind === 'Field' || arg.kind === 'ArrayField' || arg.kind === 'MapField')
254
+ return known(null);
255
+ if (arg.kind === 'Field')
184
256
  return resolveFieldNode(arg, ctx);
185
257
  if (arg.kind === 'Func')
186
258
  return evaluateFuncValue(arg, ctx);
187
259
  if (arg.kind === 'StringLiteral' ||
188
260
  arg.kind === 'NumberLiteral' ||
189
261
  arg.kind === 'IpLiteral' ||
190
- arg.kind === 'BoolLiteral' ||
191
- arg.kind === 'ListRef') {
192
- return literalValue(arg);
193
- }
194
- return null;
195
- }
196
- function evaluateHasKey(mapArg, keyValue, ctx) {
197
- if (keyValue === null)
198
- return null;
199
- const key = String(keyValue).toLowerCase();
200
- if (!mapArg || typeof mapArg !== 'object' || !('kind' in mapArg))
201
- return null;
202
- if (mapArg.kind === 'Field') {
203
- if (mapArg.name === 'http.request.headers')
204
- return ctx.request.headers.has(key);
205
- if (mapArg.name === 'http.request.cookies')
206
- return ctx.request.headers.get('cookie')?.split(';').some(part => part.trim().startsWith(`${key}=`)) ?? false;
207
- if (mapArg.name === 'http.request.uri.args')
208
- return ctx.url.searchParams.has(String(keyValue));
262
+ arg.kind === 'BoolLiteral') {
263
+ return known(literalValue(arg));
209
264
  }
210
- return null;
211
- }
265
+ // Inline lists, list references, and predicates are not values. They are
266
+ // unknown rather than nil, which functions such as coalesce() would skip.
267
+ pushWarning(ctx.warnings, nonValueArgumentWarning(arg));
268
+ return unavailable(nonValueArgumentSource(arg));
269
+ }
270
+ function nonValueArgumentWarning(arg) {
271
+ if (arg.kind === 'ListRef')
272
+ return `list '$${arg.name}' can only be used with the in operator`;
273
+ if (arg.kind === 'SetLiteral')
274
+ return 'inline lists can only be used with the in operator';
275
+ return `'${arg.raw}' cannot be used as a function argument value`;
276
+ }
277
+ function nonValueArgumentSource(arg) {
278
+ if (arg.kind === 'ListRef')
279
+ return `list '$${arg.name}'`;
280
+ if (arg.kind === 'SetLiteral')
281
+ return 'an inline list';
282
+ return `'${arg.raw}'`;
283
+ }
284
+ /** Returns nil (null) for a nil collection or value, as Cloudflare documents. */
212
285
  function evaluateHasValue(collection, value) {
213
286
  if (collection === null || value === null)
214
287
  return null;
@@ -216,20 +289,33 @@ function evaluateHasValue(collection, value) {
216
289
  return collection.some(item => String(item) === String(value));
217
290
  return String(collection) === String(value);
218
291
  }
219
- function concatValues(values) {
220
- if (values.some(Array.isArray)) {
221
- const result = [];
222
- for (const value of values) {
223
- if (Array.isArray(value))
224
- result.push(...value);
225
- else if (typeof value === 'string' || typeof value === 'number')
226
- result.push(value);
227
- }
228
- return toCfArray(result);
292
+ /** A nil source or affix never matches. */
293
+ function matchesAffix(name, value, affix) {
294
+ if (value === null || affix === null)
295
+ return false;
296
+ return name === 'starts_with'
297
+ ? String(value).startsWith(String(affix))
298
+ : String(value).endsWith(String(affix));
299
+ }
300
+ function concatValues(values, argumentTypes) {
301
+ if (values.length < 2)
302
+ return null;
303
+ const expectedType = argumentTypes[0];
304
+ if (expectedType &&
305
+ argumentTypes.slice(1).some(type => compareRuleExpressionDataTypes(expectedType, type) === 'different'))
306
+ return null;
307
+ const presentValues = values.filter(value => value !== null);
308
+ const firstValue = presentValues[0];
309
+ if (firstValue === undefined)
310
+ return null;
311
+ if (Array.isArray(firstValue)) {
312
+ if (!presentValues.every((value) => Array.isArray(value)))
313
+ return null;
314
+ return presentValues.flat();
229
315
  }
230
- if (values.some(value => value === null))
316
+ if (typeof firstValue !== 'string' || !presentValues.every(value => typeof value === 'string'))
231
317
  return null;
232
- return values.map(value => String(value)).join('');
318
+ return presentValues.join('');
233
319
  }
234
320
  function lengthOfValue(value) {
235
321
  if (value === null)
@@ -239,10 +325,8 @@ function lengthOfValue(value) {
239
325
  return String(value).length;
240
326
  }
241
327
  function mapStringValue(value, map) {
242
- if (value === null)
328
+ if (value === null || Array.isArray(value))
243
329
  return null;
244
- if (Array.isArray(value))
245
- return value.map(item => map(String(item)));
246
330
  return map(String(value));
247
331
  }
248
332
  function encodeBase64Value(value, flagsValue) {
@@ -283,34 +367,44 @@ function joinValues(items, separator) {
283
367
  return null;
284
368
  return items.map(item => String(item)).join(String(separator));
285
369
  }
286
- function lookupJsonValue(args, ctx, kind) {
287
- const source = evaluateArgValue(args[0], ctx);
288
- if (source === null)
289
- return null;
370
+ /**
371
+ * Reads keys only while the JSON value can still be traversed, so a missing
372
+ * source or path is nil whatever the remaining keys are.
373
+ */
374
+ function lookupJsonValue(kind, argumentCount, argument) {
375
+ const source = argument(0);
376
+ if (isUnknown(source) || source.value === null)
377
+ return source;
290
378
  let current;
291
379
  try {
292
- current = JSON.parse(String(source));
380
+ current = JSON.parse(String(source.value));
293
381
  }
294
382
  catch {
295
- return null;
383
+ return known(null);
296
384
  }
297
- for (const arg of args.slice(1)) {
298
- const key = evaluateArgValue(arg, ctx);
299
- if (key === null)
300
- return null;
301
- if (Array.isArray(current) && typeof key === 'number') {
302
- current = current[key];
303
- }
304
- else if (current && typeof current === 'object') {
305
- current = current[String(key)];
306
- }
307
- else {
308
- return null;
309
- }
385
+ for (let index = 1; index < argumentCount; index++) {
386
+ if (!current || typeof current !== 'object')
387
+ return known(null);
388
+ const key = argument(index);
389
+ if (isUnknown(key) || key.value === null)
390
+ return key;
391
+ current = jsonMember(current, key.value);
310
392
  }
311
393
  if (kind === 'integer')
312
- return typeof current === 'number' && Number.isInteger(current) ? current : null;
313
- return typeof current === 'string' ? current : null;
394
+ return known(typeof current === 'number' && Number.isInteger(current) ? current : null);
395
+ return known(typeof current === 'string' ? current : null);
396
+ }
397
+ /**
398
+ * An array element by integer index, or an object member by key. Other
399
+ * JavaScript properties, such as an array's `length` or an inherited
400
+ * `toString`, are not JSON data.
401
+ */
402
+ function jsonMember(container, key) {
403
+ if (Array.isArray(container)) {
404
+ return typeof key === 'number' ? container[key] : undefined;
405
+ }
406
+ const name = String(key);
407
+ return Object.hasOwn(container, name) ? container[name] : undefined;
314
408
  }
315
409
  function regexReplace(sourceValue, patternValue, replacementValue) {
316
410
  if (sourceValue === null || patternValue === null || replacementValue === null)
@@ -509,10 +603,14 @@ function expandIpv6(address) {
509
603
  }
510
604
  return head.length === 8 ? head : null;
511
605
  }
512
- function warnUnreliableFunction(ctx, name) {
606
+ /** A function result this evaluator cannot reproduce is unknown. */
607
+ function unreliableFunction(ctx, name) {
513
608
  const reason = getUnreliableRuleExpressionFunctionReason(name);
514
- if (!reason)
515
- return;
516
- pushWarning(ctx.warnings, `function '${name}' cannot be evaluated reliably: ${reason}`);
609
+ if (reason)
610
+ pushWarning(ctx.warnings, `function '${name}' cannot be evaluated reliably: ${reason}`);
611
+ return unavailable(functionSource(name));
612
+ }
613
+ function functionSource(name) {
614
+ return `function '${name}'`;
517
615
  }
518
616
  //# sourceMappingURL=functions.js.map