@libreflare/worker-runtime 0.8.3 → 0.9.1

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 (136) hide show
  1. package/README.md +230 -23
  2. package/dist/log-handler.d.ts.map +1 -1
  3. package/dist/log-handler.js +12 -6
  4. package/dist/log-handler.js.map +1 -1
  5. package/dist/rule-evaluator/access-values.d.ts +19 -6
  6. package/dist/rule-evaluator/access-values.d.ts.map +1 -1
  7. package/dist/rule-evaluator/access-values.js +33 -8
  8. package/dist/rule-evaluator/access-values.js.map +1 -1
  9. package/dist/rule-evaluator/analysis.d.ts +49 -17
  10. package/dist/rule-evaluator/analysis.d.ts.map +1 -1
  11. package/dist/rule-evaluator/analysis.js +39 -41
  12. package/dist/rule-evaluator/analysis.js.map +1 -1
  13. package/dist/rule-evaluator/ast.d.ts +31 -18
  14. package/dist/rule-evaluator/ast.d.ts.map +1 -1
  15. package/dist/rule-evaluator/ast.js +3 -4
  16. package/dist/rule-evaluator/ast.js.map +1 -1
  17. package/dist/rule-evaluator/constants.d.ts +1 -1
  18. package/dist/rule-evaluator/constants.d.ts.map +1 -1
  19. package/dist/rule-evaluator/constants.js +3 -0
  20. package/dist/rule-evaluator/constants.js.map +1 -1
  21. package/dist/rule-evaluator/country-codes.generated.js +1 -1
  22. package/dist/rule-evaluator/custom-lists.d.ts +0 -6
  23. package/dist/rule-evaluator/custom-lists.d.ts.map +1 -1
  24. package/dist/rule-evaluator/custom-lists.js +119 -91
  25. package/dist/rule-evaluator/custom-lists.js.map +1 -1
  26. package/dist/rule-evaluator/diagnostics.d.ts +1 -1
  27. package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
  28. package/dist/rule-evaluator/diagnostics.js +17 -0
  29. package/dist/rule-evaluator/diagnostics.js.map +1 -1
  30. package/dist/rule-evaluator/engine-observations.generated.d.ts +20 -0
  31. package/dist/rule-evaluator/engine-observations.generated.d.ts.map +1 -1
  32. package/dist/rule-evaluator/engine-observations.generated.js +5 -0
  33. package/dist/rule-evaluator/engine-observations.generated.js.map +1 -1
  34. package/dist/rule-evaluator/evaluator.d.ts +4 -2
  35. package/dist/rule-evaluator/evaluator.d.ts.map +1 -1
  36. package/dist/rule-evaluator/evaluator.js +5 -4
  37. package/dist/rule-evaluator/evaluator.js.map +1 -1
  38. package/dist/rule-evaluator/explain.d.ts +2 -1
  39. package/dist/rule-evaluator/explain.d.ts.map +1 -1
  40. package/dist/rule-evaluator/explain.js +49 -7
  41. package/dist/rule-evaluator/explain.js.map +1 -1
  42. package/dist/rule-evaluator/field-descriptions.generated.d.ts +13 -0
  43. package/dist/rule-evaluator/field-descriptions.generated.d.ts.map +1 -1
  44. package/dist/rule-evaluator/field-descriptions.generated.js +33 -0
  45. package/dist/rule-evaluator/field-descriptions.generated.js.map +1 -1
  46. package/dist/rule-evaluator/fields.d.ts +13 -1
  47. package/dist/rule-evaluator/fields.d.ts.map +1 -1
  48. package/dist/rule-evaluator/fields.js +71 -17
  49. package/dist/rule-evaluator/fields.js.map +1 -1
  50. package/dist/rule-evaluator/function-descriptions.d.ts +2 -0
  51. package/dist/rule-evaluator/function-descriptions.d.ts.map +1 -1
  52. package/dist/rule-evaluator/function-descriptions.generated.d.ts +66 -10
  53. package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
  54. package/dist/rule-evaluator/function-descriptions.generated.js +129 -11
  55. package/dist/rule-evaluator/function-descriptions.generated.js.map +1 -1
  56. package/dist/rule-evaluator/function-descriptions.js.map +1 -1
  57. package/dist/rule-evaluator/function-signature-validation.d.ts +2 -0
  58. package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
  59. package/dist/rule-evaluator/function-signature-validation.js +169 -19
  60. package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
  61. package/dist/rule-evaluator/functions.d.ts +24 -1
  62. package/dist/rule-evaluator/functions.d.ts.map +1 -1
  63. package/dist/rule-evaluator/functions.js +423 -95
  64. package/dist/rule-evaluator/functions.js.map +1 -1
  65. package/dist/rule-evaluator/ip-literals.d.ts +56 -0
  66. package/dist/rule-evaluator/ip-literals.d.ts.map +1 -0
  67. package/dist/rule-evaluator/ip-literals.js +162 -0
  68. package/dist/rule-evaluator/ip-literals.js.map +1 -0
  69. package/dist/rule-evaluator/log-sample.d.ts.map +1 -1
  70. package/dist/rule-evaluator/log-sample.js +14 -2
  71. package/dist/rule-evaluator/log-sample.js.map +1 -1
  72. package/dist/rule-evaluator/match-chain.d.ts +2 -1
  73. package/dist/rule-evaluator/match-chain.d.ts.map +1 -1
  74. package/dist/rule-evaluator/match-chain.js +12 -17
  75. package/dist/rule-evaluator/match-chain.js.map +1 -1
  76. package/dist/rule-evaluator/minifier.d.ts +1 -1
  77. package/dist/rule-evaluator/minifier.d.ts.map +1 -1
  78. package/dist/rule-evaluator/minifier.js +15 -14
  79. package/dist/rule-evaluator/minifier.js.map +1 -1
  80. package/dist/rule-evaluator/normalizer.d.ts +1 -1
  81. package/dist/rule-evaluator/normalizer.d.ts.map +1 -1
  82. package/dist/rule-evaluator/normalizer.js +4 -5
  83. package/dist/rule-evaluator/normalizer.js.map +1 -1
  84. package/dist/rule-evaluator/operators.d.ts +4 -0
  85. package/dist/rule-evaluator/operators.d.ts.map +1 -1
  86. package/dist/rule-evaluator/operators.js +26 -98
  87. package/dist/rule-evaluator/operators.js.map +1 -1
  88. package/dist/rule-evaluator/outcome.d.ts +2 -0
  89. package/dist/rule-evaluator/outcome.d.ts.map +1 -1
  90. package/dist/rule-evaluator/outcome.js +0 -6
  91. package/dist/rule-evaluator/outcome.js.map +1 -1
  92. package/dist/rule-evaluator/parse-cache.d.ts +8 -3
  93. package/dist/rule-evaluator/parse-cache.d.ts.map +1 -1
  94. package/dist/rule-evaluator/parse-cache.js +9 -8
  95. package/dist/rule-evaluator/parse-cache.js.map +1 -1
  96. package/dist/rule-evaluator/parser.d.ts +155 -18
  97. package/dist/rule-evaluator/parser.d.ts.map +1 -1
  98. package/dist/rule-evaluator/parser.js +478 -81
  99. package/dist/rule-evaluator/parser.js.map +1 -1
  100. package/dist/rule-evaluator/quantifier.d.ts +96 -2
  101. package/dist/rule-evaluator/quantifier.d.ts.map +1 -1
  102. package/dist/rule-evaluator/quantifier.js +263 -22
  103. package/dist/rule-evaluator/quantifier.js.map +1 -1
  104. package/dist/rule-evaluator/query-args.d.ts +23 -0
  105. package/dist/rule-evaluator/query-args.d.ts.map +1 -0
  106. package/dist/rule-evaluator/query-args.js +46 -0
  107. package/dist/rule-evaluator/query-args.js.map +1 -0
  108. package/dist/rule-evaluator/rule-language-types.d.ts +28 -17
  109. package/dist/rule-evaluator/rule-language-types.d.ts.map +1 -1
  110. package/dist/rule-evaluator/rule-language-types.js +117 -42
  111. package/dist/rule-evaluator/rule-language-types.js.map +1 -1
  112. package/dist/rule-evaluator/string-literals.d.ts +20 -0
  113. package/dist/rule-evaluator/string-literals.d.ts.map +1 -0
  114. package/dist/rule-evaluator/string-literals.js +44 -0
  115. package/dist/rule-evaluator/string-literals.js.map +1 -0
  116. package/dist/rule-evaluator/tokenizer.d.ts +34 -5
  117. package/dist/rule-evaluator/tokenizer.d.ts.map +1 -1
  118. package/dist/rule-evaluator/tokenizer.js +320 -74
  119. package/dist/rule-evaluator/tokenizer.js.map +1 -1
  120. package/dist/rule-evaluator/transformation.d.ts +2 -2
  121. package/dist/rule-evaluator/transformation.d.ts.map +1 -1
  122. package/dist/rule-evaluator/transformation.js +4 -5
  123. package/dist/rule-evaluator/transformation.js.map +1 -1
  124. package/dist/rule-evaluator/validation.d.ts.map +1 -1
  125. package/dist/rule-evaluator/validation.js +261 -122
  126. package/dist/rule-evaluator/validation.js.map +1 -1
  127. package/dist/rule-evaluator.d.ts +3 -1
  128. package/dist/rule-evaluator.d.ts.map +1 -1
  129. package/dist/rule-evaluator.js +2 -0
  130. package/dist/rule-evaluator.js.map +1 -1
  131. package/dist/runtime-config.d.ts.map +1 -1
  132. package/dist/runtime-config.js +6 -4
  133. package/dist/runtime-config.js.map +1 -1
  134. package/dist/tools/explain-rule-miss.js +4 -6
  135. package/dist/tools/explain-rule-miss.js.map +1 -1
  136. package/package.json +3 -3
@@ -6,9 +6,10 @@ import { resolveBoolField, resolveFieldNode } from './fields.js';
6
6
  import { hashInRange } from './hash-in-range.js';
7
7
  import { applyOp, compareOperands, findMatchingSetMember, literalValue, wildcardToRegex } from './operators.js';
8
8
  import { andOutcome, incomparable, isUnknown, known, negateOutcome, orOutcome, outcomeValue, unavailable, valueOutcome, xorOutcome, } from './outcome.js';
9
- import { extractQuantifierPredicate } from './quantifier.js';
9
+ import { conditionArray, extractQuantifierPredicate, givesNilForNilArgument, keepsPlacesWhenMapped, quantifierPredicateConditions, readQuantifierPredicate, unalignedArray, } from './quantifier.js';
10
+ import { removeQueryArgs } from './query-args.js';
10
11
  import { urlDecode } from './url-decode.js';
11
- import { collectionElementDataType, compareRuleExpressionDataTypes, formatRuleExpressionDataType, evaluatedValueType, inferFunctionInvocation, } from './rule-language-types.js';
12
+ import { collectionElementDataType, compareRuleExpressionDataTypes, formatRuleExpressionDataType, evaluatedValueType, inferFunctionInvocation, isArrayConditionArgument, } from './rule-language-types.js';
12
13
  const UNRELIABLE_FUNCTION_REASONS = {
13
14
  bit_slice: 'packet bit slicing is not available in Worker request context',
14
15
  is_jwt_present: 'Cloudflare API JWT token configurations are not available in Worker request context',
@@ -34,7 +35,8 @@ function evaluateRuntimeOperand(node, ctx) {
34
35
  * Narrows a value to a rule-language value. Only coalesce(), has_key(), and
35
36
  * postfix access read maps, and validation rejects maps anywhere else, so a
36
37
  * map here is unknown. So is a partly known array, which only any(), all(),
37
- * mapped functions and postfix access can read in part.
38
+ * has_value(), len(), concat(), mapped functions and postfix access read in
39
+ * part.
38
40
  */
39
41
  function ruleValue(evaluated) {
40
42
  if (isUnknown(evaluated))
@@ -82,28 +84,23 @@ export function evaluateComparison(node, ctx) {
82
84
  }
83
85
  return { outcome, ...operands };
84
86
  }
85
- /** Evaluates the values an any()/all() collection yields, which can be partly known. */
87
+ /**
88
+ * The values an any()/all() collection yields, which can be partly known.
89
+ * Explain shows them, and the match chain looks among them for the set
90
+ * member a match found.
91
+ */
86
92
  export function evaluateCollection(fieldArg, ctx) {
87
93
  const evaluated = evaluateRuntimeOperand(fieldArg, ctx);
88
- if (isUnknown(evaluated))
89
- return evaluated;
90
- const { value } = evaluated;
91
- if (value instanceof RuleMapValue)
92
- return unavailable('a map value');
93
- if (value instanceof PartialArrayValue) {
94
- const { values, unknown } = value.knownValues();
95
- return known({ values: collectionValues(values), unknown });
96
- }
97
- if (Array.isArray(value))
98
- return known({ values: collectionValues(value) });
99
- if (value === null)
100
- return known({ values: [] });
101
- if (typeof value === 'number')
102
- return known({ values: [value] });
103
- return known({ values: [String(value)] });
94
+ const array = isUnknown(evaluated) ? evaluated : arrayElements(evaluated.value);
95
+ if (isUnknown(array))
96
+ return array;
97
+ const { elements, more } = array.value;
98
+ const values = elements.flatMap(element => !isUnknownElement(element) && isCollectionValue(element.value) ? [element.value] : []);
99
+ const unknown = elements.find(isUnknownElement) ?? more;
100
+ return known(unknown ? { values, unknown } : { values });
104
101
  }
105
- function collectionValues(values) {
106
- return values.filter((item) => typeof item === 'string' || typeof item === 'number');
102
+ function isCollectionValue(value) {
103
+ return typeof value === 'string' || typeof value === 'number';
107
104
  }
108
105
  export function findMatchedSetMemberForFunc(node, ctx) {
109
106
  if (node.name !== 'any' && node.name !== 'all')
@@ -135,48 +132,299 @@ export function evaluateFuncPredicate(node, ctx) {
135
132
  const evaluated = evaluateFuncValue(node, ctx);
136
133
  return isUnknown(evaluated) ? evaluated : evaluated.value === true;
137
134
  }
135
+ // A single comparison is a predicate with one condition; see evaluatePairedQuantifier().
138
136
  function evaluateQuantifier(node, ctx) {
139
- const quantifier = extractQuantifierPredicate(node);
140
- if (!quantifier)
141
- return false;
142
- const collection = evaluateCollection(quantifier.source, ctx);
143
- if (isUnknown(collection))
144
- return collection;
145
- const compare = comparatorFor(node, quantifier, ctx);
146
- const outcomes = collection.value.values.map((value) => {
147
- const outcome = compare(value);
148
- return quantifier.negated ? negateOutcome(outcome) : outcome;
149
- });
150
- const combine = node.name === 'any' ? orOutcome : andOutcome;
151
- const outcome = combine(outcomes);
152
- // A known value settles any() when it matches and all() when it does not; otherwise the unknown values count too.
153
- const { unknown } = collection.value;
154
- if (!unknown || outcome === (node.name === 'any'))
155
- return outcome;
156
- return combine([outcome, unknown()]);
137
+ const reading = readQuantifierPredicate(node);
138
+ return reading ? evaluatePairedQuantifier(node, reading, ctx).outcome : false;
139
+ }
140
+ /** A value's elements, read as an array: nil has none, a scalar is one, and a map's are unknown. */
141
+ function arrayElements(value) {
142
+ if (value instanceof RuleMapValue)
143
+ return unavailable('a map value');
144
+ if (value instanceof PartialArrayValue)
145
+ return known({ elements: value.elements, more: value.more });
146
+ if (value === null)
147
+ return known({ elements: [] });
148
+ return known({ elements: (Array.isArray(value) ? value : [value]).map(element => known(element)) });
149
+ }
150
+ const NO_PAIRS = { arrays: new Map(), certain: 0, end: 0 };
151
+ /**
152
+ * Evaluates the collections of a predicate's conditions; see PairedArrays.
153
+ * An empty one leaves no pairs, whatever the others hold, so the ones after
154
+ * it are not read. `valueCall` is a quantifier's predicate read as a value,
155
+ * which is no array when it gives nil.
156
+ */
157
+ function pairArrays(owner, predicate, ctx, valueCall) {
158
+ const arrays = new Map();
159
+ let certain = Infinity;
160
+ let end = Infinity;
161
+ let longest = 0;
162
+ let firstMore;
163
+ let shortestMore;
164
+ for (const { node: condition } of quantifierPredicateConditions(predicate)) {
165
+ // Conditions that validation accepts have a result for each element at each comparison and call (see
166
+ // isArrayCondition()), so their kind tells them.
167
+ if (condition.kind !== 'Comparison' && condition.kind !== 'Func')
168
+ continue;
169
+ const { result: evaluated, warnings } = collectWarnings(ctx, () => evaluateRuntimeOperand(conditionArray(condition), ctx));
170
+ // A call read as a value that gives nil is no array, while a condition over nil has no results.
171
+ if (condition === valueCall && !isUnknown(evaluated) && evaluated.value === null) {
172
+ giveWarnings(ctx, warnings);
173
+ return { ...NO_PAIRS, nilCall: valueCall };
174
+ }
175
+ const array = pairedArray(owner, condition, evaluated, warnings, ctx);
176
+ if (array.length === 0 && !array.more)
177
+ return NO_PAIRS;
178
+ arrays.set(condition, array);
179
+ if (array.length < certain) {
180
+ certain = array.length;
181
+ shortestMore = array.more;
182
+ }
183
+ longest = Math.max(longest, array.length);
184
+ if (array.more)
185
+ firstMore ??= array.more;
186
+ else
187
+ end = Math.min(end, array.length);
188
+ }
189
+ // Validation rejects a predicate that compares no collection.
190
+ if (arrays.size === 0)
191
+ return NO_PAIRS;
192
+ const tail = end === Infinity ? firstMore : undefined;
193
+ if (end === Infinity)
194
+ end = longest;
195
+ // A collection that may hold more has its known elements at positions it cannot tell, unless every
196
+ // collection describes the same items.
197
+ if (firstMore && !describeSameItems(arrays, certain)) {
198
+ for (const array of arrays.values()) {
199
+ if (array.more)
200
+ array.elements = Array(array.length).fill(array.more);
201
+ }
202
+ }
203
+ return { arrays, certain, end, shortestMore, tail };
204
+ }
205
+ /**
206
+ * Evaluates any() or all() as Cloudflare does, over the pairs of its
207
+ * predicate's collections; see PairedArrays. An unknown element is read only
208
+ * when no known one settles the result.
209
+ */
210
+ export function evaluatePairedQuantifier(node, reading, ctx) {
211
+ const settling = node.name === 'any';
212
+ const { predicate } = reading;
213
+ const { arrays, certain, end, shortestMore, tail, nilCall } = pairArrays(node, predicate, ctx, reading.kind === 'value' ? reading.predicate : undefined);
214
+ // A call read as a value that gives nil is no array, which neither any() nor all() holds for; see
215
+ // QuantifierPredicateReading.
216
+ if (nilCall)
217
+ return { outcome: false, paired: 0, mayLackSome: false, mayHaveMore: false, nilCall };
218
+ const result = (outcome) => ({ outcome, paired: end, mayLackSome: end > certain, mayHaveMore: tail !== undefined });
219
+ // The unknown outcomes of known elements, from every position, and the first outcome that reads an unknown
220
+ // element, which is combined after them, so that an unknown comparison value, which applies at every
221
+ // element, names the cause before one element does.
222
+ let unknowns;
223
+ let pending;
224
+ for (let index = 0; index < end; index++) {
225
+ let outcome = pairedOutcome(predicate, index, arrays);
226
+ if (index >= certain) {
227
+ // The shortest collection may end before this position, so it may hold no pair. It may hold more, or
228
+ // the pairs would end at `certain`. One that settles the result settles it only if the pair is there.
229
+ if (outcome === settling)
230
+ outcome = shortestMore;
231
+ }
232
+ else if (outcome === settling) {
233
+ return result(outcome);
234
+ }
235
+ if (typeof outcome === 'function')
236
+ pending ??= outcome;
237
+ else if (isUnknown(outcome))
238
+ (unknowns ??= []).push(outcome);
239
+ }
240
+ pending ??= tail;
241
+ // Reading an unknown element warns, so only the first is read. Only an unresolved list's result can match
242
+ // or miss while unknown, and a list holds IP addresses, which no array does, so the others change nothing.
243
+ if (pending)
244
+ (unknowns ??= []).push(pending());
245
+ const combine = settling ? orOutcome : andOutcome;
246
+ return result(unknowns ? combine(unknowns) : !settling);
247
+ }
248
+ /**
249
+ * Evaluates a function argument read as a condition with a result for each
250
+ * element: the array of its results, at the pairs of its collections (see
251
+ * PairedArrays), with none over nil. An unknown result keeps its place, and
252
+ * when the shortest collection may hold more, so may the array, which lists
253
+ * the results that may follow when it knows them all.
254
+ */
255
+ function evaluateConditionArray(node, ctx) {
256
+ const pairing = pairArrays(node, node, ctx);
257
+ const { arrays, certain, end, tail } = pairing;
258
+ // Past `certain`, the shortest collection may end at any position, so a result there may be missing, and
259
+ // unless more may follow `end`, those are the only results that may follow.
260
+ const count = tail ? certain : end;
261
+ const results = [];
262
+ for (let index = 0; index < count; index++)
263
+ results.push(resultElement(node, index, arrays, ctx));
264
+ return known(PartialArrayValue.from(results.slice(0, certain), moreResults(pairing), tail ? undefined : results.slice(certain)));
265
+ }
266
+ /** The number of results evaluateConditionArray() gives, which reads none of them. */
267
+ function countConditionResults(node, ctx) {
268
+ const pairing = pairArrays(node, node, ctx);
269
+ return moreResults(pairing)?.() ?? known(pairing.certain);
270
+ }
271
+ /** Why a condition argument may have more results than `certain`: the shortest collection may hold more. */
272
+ function moreResults({ certain, end, shortestMore, tail }) {
273
+ return certain < end || tail ? shortestMore : undefined;
274
+ }
275
+ /**
276
+ * The result at an index as an element of the array of results. One that is
277
+ * not known settles nothing, and tells why only when read, as an unknown
278
+ * element does.
279
+ */
280
+ function resultElement(node, index, arrays, ctx) {
281
+ const { result: outcome, warnings } = collectWarnings(ctx, () => pairedOutcome(node, index, arrays));
282
+ if (typeof outcome !== 'boolean') {
283
+ return deferWarnings(ctx, warnings, () => outcomeValue(typeof outcome === 'function' ? outcome() : outcome));
284
+ }
285
+ giveWarnings(ctx, warnings);
286
+ return known(outcome);
287
+ }
288
+ /**
289
+ * Whether a predicate's collections describe the same item at each index:
290
+ * they come from one list (see pairedArrayList()), and each holds `length`
291
+ * elements. An element dropped, as a mapped call's nil result, or added, as
292
+ * a Set-Cookie value repeated past a cut header list, changes the length.
293
+ */
294
+ function describeSameItems(arrays, length) {
295
+ for (const array of arrays.values()) {
296
+ if (array.length !== length)
297
+ return false;
298
+ }
299
+ return !unalignedArray([...arrays.keys()].map(conditionArray));
300
+ }
301
+ /** A condition's array, from its evaluated collection and the warnings evaluating it gave. */
302
+ function pairedArray(owner, condition, evaluated, warnings, ctx) {
303
+ // A call's result holds at an element where it is true.
304
+ const compare = condition.kind === 'Comparison' ? comparatorFor(owner, condition, ctx) : (value) => value === true;
305
+ if (!isUnknown(evaluated) && Array.isArray(evaluated.value)) {
306
+ giveWarnings(ctx, warnings);
307
+ return { values: evaluated.value, elements: [], length: evaluated.value.length, compare };
308
+ }
309
+ const array = isUnknown(evaluated) ? evaluated : arrayElements(evaluated.value);
310
+ // A collection unknown whole tells why only when read, since the other collections may settle the result.
311
+ if (isUnknown(array))
312
+ return { values: undefined, elements: [], length: 0, more: deferWarnings(ctx, warnings, () => array), compare };
313
+ giveWarnings(ctx, warnings);
314
+ const { elements, more } = array.value;
315
+ return { values: undefined, elements, length: elements.length, more, compare };
316
+ }
317
+ /**
318
+ * Runs `compute` with warnings of its own, to give when its result is read:
319
+ * each message it gave, even one given before, which the warnings, keeping
320
+ * each message once, would not tell apart.
321
+ */
322
+ function collectWarnings(ctx, compute) {
323
+ const outer = ctx.warnings;
324
+ ctx.warnings = new Set();
325
+ try {
326
+ const result = compute();
327
+ return { result, warnings: [...ctx.warnings] };
328
+ }
329
+ finally {
330
+ ctx.warnings = outer;
331
+ }
332
+ }
333
+ function giveWarnings(ctx, warnings) {
334
+ for (const warning of warnings)
335
+ ctx.warnings.add(warning);
336
+ }
337
+ /** An unknown value that gives its warnings only when read, as an unknown element does. */
338
+ function deferWarnings(ctx, warnings, read) {
339
+ return () => {
340
+ giveWarnings(ctx, warnings);
341
+ return read();
342
+ };
343
+ }
344
+ /** The outcome of a predicate at an index, which a collection that may hold more can lack. */
345
+ function pairedOutcome(node, index, arrays) {
346
+ switch (node.kind) {
347
+ case 'Comparison':
348
+ case 'Func':
349
+ return elementOutcome(arrays.get(node), index);
350
+ case 'Not': {
351
+ const operand = pairedOutcome(node.operand, index, arrays);
352
+ return typeof operand === 'function' ? () => negateOutcome(operand()) : negateOutcome(operand);
353
+ }
354
+ case 'And':
355
+ return combinePairedOutcomes(node.operands, false, andOutcome, index, arrays);
356
+ case 'Or':
357
+ return combinePairedOutcomes(node.operands, true, orOutcome, index, arrays);
358
+ case 'Xor':
359
+ return combinePairedOutcomes(node.operands, undefined, xorOutcome, index, arrays);
360
+ case 'BoolField':
361
+ case 'Invalid':
362
+ // Validation rejects these where conditions are combined over each element.
363
+ return false;
364
+ default:
365
+ return unhandledNode(node);
366
+ }
367
+ }
368
+ /** A condition's outcome at an index of its collection. */
369
+ function elementOutcome(array, index) {
370
+ // A collection known whole holds no more, so it reaches every position read.
371
+ if (array.values)
372
+ return array.compare(array.values[index]);
373
+ const element = array.elements[index] ?? array.more;
374
+ return isUnknownElement(element) ? element : array.compare(element.value);
375
+ }
376
+ /** Combines operands at an index, stopping at the first known one that decides the result, if any does. */
377
+ function combinePairedOutcomes(operands, deciding, combine, index, arrays) {
378
+ const outcomes = [];
379
+ let pending;
380
+ for (const operand of operands) {
381
+ const outcome = pairedOutcome(operand, index, arrays);
382
+ if (outcome === deciding)
383
+ return outcome;
384
+ if (typeof outcome === 'function')
385
+ pending ??= outcome;
386
+ else
387
+ outcomes.push(outcome);
388
+ }
389
+ if (!pending)
390
+ return combine(outcomes);
391
+ // Only the first unknown element is read; see evaluatePairedQuantifier().
392
+ const read = pending;
393
+ return () => {
394
+ const unknown = read();
395
+ const combined = combine([...outcomes, unknown]);
396
+ // No known operand decides the result, so with an unknown one it stays unknown.
397
+ return isUnknown(combined) ? combined : unknown;
398
+ };
157
399
  }
158
400
  /**
159
- * Returns a comparison of collection values against the quantifier's
160
- * right-hand value. A dynamic value is resolved once, when the first value is
161
- * compared, so an empty collection settles any()/all() without reading it. An
401
+ * Returns a comparison of collection values against a quantifier
402
+ * comparison's right-hand value. A dynamic value is resolved once, when the
403
+ * first value is compared, so an empty collection settles any()/all() without
404
+ * reading it, and each comparison gives the warnings resolving it gave, which
405
+ * a result over each element keeps until read (see resultElement()). An
162
406
  * unknown value, or values Cloudflare would not compare, make the comparison
163
407
  * unknown.
164
408
  */
165
- function comparatorFor(node, quantifier, ctx) {
166
- const { op, value: right } = quantifier;
409
+ function comparatorFor(owner, comparison, ctx) {
410
+ const { op, right } = comparison;
411
+ if (!right)
412
+ return () => false;
167
413
  if (right.kind === 'ListRef' || right.kind === 'SetLiteral')
168
414
  return left => applyOp(op, left, right, ctx.customLists);
169
- const elementType = collectionElementDataType(evaluatedValueType(quantifier.source))
415
+ const elementType = collectionElementDataType(evaluatedValueType(comparison.left))
170
416
  ?? { kind: 'unknown' };
171
417
  const rightType = evaluatedValueType(right);
172
- let operand;
418
+ let resolved;
173
419
  return (left) => {
174
- operand ??= isDynamicValueNode(right) ? evaluateOperand(right, ctx) : known(literalValue(right));
420
+ resolved ??= collectWarnings(ctx, () => isDynamicValueNode(right) ? evaluateOperand(right, ctx) : known(literalValue(right)));
421
+ giveWarnings(ctx, resolved.warnings);
422
+ const operand = resolved.result;
175
423
  if (isUnknown(operand))
176
424
  return operand;
177
425
  const outcome = compareOperands(op, { value: left, type: elementType }, { value: operand.value, type: rightType }, ctx.warnings);
178
426
  if (isUnknown(outcome) && outcome.cause.kind === 'incomparable') {
179
- ctx.warnings.add(`comparison in '${node.raw}' cannot be evaluated: ${outcome.cause.reason}`);
427
+ ctx.warnings.add(`comparison in '${owner.raw}' cannot be evaluated: ${outcome.cause.reason}`);
180
428
  }
181
429
  return outcome;
182
430
  };
@@ -194,16 +442,38 @@ export function evaluateFuncValue(node, ctx) {
194
442
  return evaluated;
195
443
  return applyRuntimeAccessPath(evaluated.value, node.accessPath);
196
444
  }
197
- function evaluateDirectFuncValue(node, ctx, invocation, firstArgumentValue) {
445
+ /**
446
+ * Evaluates a call on its arguments, or one that maps on one element:
447
+ * `element` is then its first argument, and `later` keeps the arguments
448
+ * after it, read once for every element.
449
+ */
450
+ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
198
451
  const { name, args } = node;
199
- const runtimeArgument = (index) => index === 0 && firstArgumentValue !== undefined
200
- ? known(firstArgumentValue)
201
- : evaluateArgValue(args[index], ctx);
452
+ // Each argument is evaluated once, as concat() reads them all before the general path below does.
453
+ const read = later ?? [];
454
+ const runtimeArgument = (index) => {
455
+ if (later && index === 0)
456
+ return known(element);
457
+ return read[index] ??= evaluateArgValue(args[index], ctx);
458
+ };
202
459
  const argument = (index) => ruleValue(runtimeArgument(index));
203
460
  switch (name) {
204
461
  case 'all':
205
462
  case 'any':
206
463
  return outcomeValue(evaluateQuantifier(node, ctx));
464
+ case 'concat': {
465
+ const parts = [];
466
+ for (let index = 0; index < args.length; index++) {
467
+ const part = runtimeArgument(index);
468
+ if (isUnknown(part))
469
+ return part;
470
+ parts.push(part.value);
471
+ }
472
+ // An array known in part keeps its known elements, as any() and all() read them.
473
+ if (parts.some(part => part instanceof PartialArrayValue))
474
+ return concatElements(parts, invocation.argumentTypes);
475
+ break;
476
+ }
207
477
  case 'coalesce':
208
478
  // Arguments after the first present value are never read.
209
479
  for (let index = 0; index < args.length; index++) {
@@ -229,19 +499,24 @@ function evaluateDirectFuncValue(node, ctx, invocation, firstArgumentValue) {
229
499
  if (isUnknown(collection))
230
500
  return collection;
231
501
  // A partly known array's known elements can settle it, as they do any().
232
- const partial = collection.value instanceof PartialArrayValue ? collection.value.knownValues() : undefined;
233
- const values = partial ? known(partial.values) : ruleValue(collection);
502
+ const partial = collection.value instanceof PartialArrayValue ? collection.value : undefined;
503
+ const values = partial ? known(partial.knownValues().values) : ruleValue(collection);
234
504
  if (isUnknown(values))
235
505
  return values;
236
506
  const value = argument(1);
237
507
  if (isUnknown(value))
238
508
  return value;
239
509
  const result = evaluateHasValue(values.value, value.value);
240
- return result === false && partial ? partial.unknown() : known(result);
510
+ if (result !== false || !partial)
511
+ return known(result);
512
+ const unknown = partial.unknownMatch(element => evaluateHasValue(element, value.value) === true);
513
+ return unknown ? unknown() : known(false);
241
514
  }
242
515
  case 'hash_in_range':
243
516
  return hashInRangeValue(ctx, args, invocation.argumentTypes[2] ?? undefined, argument);
244
517
  case 'len': {
518
+ if (isArrayConditionArgument(args[0]))
519
+ return countConditionResults(args[0], ctx);
245
520
  const source = runtimeArgument(0);
246
521
  if (isUnknown(source))
247
522
  return source;
@@ -295,8 +570,7 @@ function canonicalResult(value) {
295
570
  }
296
571
  /**
297
572
  * Computes a function result from its argument values, or undefined for a
298
- * function this evaluator does not implement. A function in
299
- * NEVER_NIL_FUNCTIONS must not give nil.
573
+ * function this evaluator does not implement.
300
574
  */
301
575
  function functionResult(name, values, invocation) {
302
576
  // An omitted optional argument is null, which functions treat as absent.
@@ -325,13 +599,17 @@ function functionResult(name, values, invocation) {
325
599
  case 'remove_bytes':
326
600
  return removeBytes(at(0), at(1));
327
601
  case 'remove_query_args':
328
- return removeQueryArgs(at(0), values.slice(1));
602
+ return removeQueryArgsValue(at(0), values.slice(1));
329
603
  case 'split':
330
604
  return splitValue(at(0), at(1), at(2));
331
605
  case 'substring':
332
606
  return substringValue(at(0), at(1), at(2));
333
607
  case 'to_string':
334
608
  return toStringValue(at(0), invocation.argumentTypes[0] ?? undefined);
609
+ case 'trim':
610
+ case 'trim_end':
611
+ case 'trim_start':
612
+ return trimBytes(name, at(0), at(1));
335
613
  case 'upper':
336
614
  return mapStringValue(at(0), value => value.replace(/[a-z]+/g, letters => letters.toUpperCase()));
337
615
  case 'url_decode':
@@ -344,23 +622,32 @@ function functionResult(name, values, invocation) {
344
622
  }
345
623
  function evaluateFuncArray(node, ctx, invocation) {
346
624
  const source = evaluateArgValue(node.args[0], ctx);
347
- if (isUnknown(source))
625
+ // Over nil, such as a missing header's values, the call gives nil, not an empty array.
626
+ if (!isUnknown(source) && source.value === null)
348
627
  return source;
349
- const { value } = source;
350
- if (value instanceof RuleMapValue)
351
- return unavailable('a map value');
352
- if (value === null)
353
- return known([]);
354
- const elements = value instanceof PartialArrayValue ? value.elements : (Array.isArray(value) ? value : [value]).map(item => known(item));
355
- const more = value instanceof PartialArrayValue ? value.more : undefined;
356
- let keepsPlaces = NEVER_NIL_FUNCTIONS.has(node.name);
628
+ const array = isUnknown(source) ? source : arrayElements(source.value);
629
+ if (isUnknown(array))
630
+ return array;
631
+ const { elements, more } = array.value;
632
+ const later = [];
633
+ // A nil later argument gives every element nil, unknown ones too, so the call gives an empty array.
634
+ if ((elements.length > 0 || more) && givesNilForNilArgument(node.name)) {
635
+ for (let index = 1; index < node.args.length; index++) {
636
+ const value = (later[index] = evaluateArgValue(node.args[index], ctx));
637
+ if (isUnknown(value))
638
+ return value;
639
+ if (value.value === null)
640
+ return known([]);
641
+ }
642
+ }
643
+ let keepsPlaces = keepsPlacesWhenMapped(node.name);
357
644
  const results = [];
358
645
  for (const element of elements) {
359
646
  if (isUnknownElement(element)) {
360
647
  results.push(element);
361
648
  continue;
362
649
  }
363
- const result = ruleValue(evaluateDirectFuncValue(node, ctx, invocation, element.value));
650
+ const result = ruleValue(evaluateDirectFuncValue(node, ctx, invocation, later, element.value));
364
651
  if (isUnknown(result))
365
652
  return result;
366
653
  if (result.value !== null)
@@ -375,18 +662,6 @@ function evaluateFuncArray(node, ctx, invocation) {
375
662
  const knownResults = results.filter(result => !isUnknownElement(result));
376
663
  return known(PartialArrayValue.from(knownResults, results.find(isUnknownElement) ?? more));
377
664
  }
378
- /**
379
- * Functions that can map over an array and give every value they accept a
380
- * result, never nil. An unknown element, a header value or a map key's
381
- * values, is never nil either, so it keeps its place.
382
- */
383
- const NEVER_NIL_FUNCTIONS = new Set([
384
- 'encode_base64',
385
- 'len',
386
- 'lower',
387
- 'upper',
388
- 'url_decode',
389
- ]);
390
665
  function evaluateArgValue(arg, ctx) {
391
666
  // An omitted optional argument is null, which functions treat as absent.
392
667
  if (!arg || typeof arg !== 'object' || !('kind' in arg))
@@ -407,6 +682,8 @@ function evaluateArgValue(arg, ctx) {
407
682
  ctx.warnings.add(nonValueArgumentWarning(arg));
408
683
  return unavailable(nonValueArgumentSource(arg));
409
684
  }
685
+ if (isArrayConditionArgument(arg))
686
+ return evaluateConditionArray(arg, ctx);
410
687
  return outcomeValue(evaluateConditionArgument(arg, ctx));
411
688
  }
412
689
  /**
@@ -467,20 +744,16 @@ function evaluateHasValue(collection, value) {
467
744
  return collection.some(item => String(item) === String(value));
468
745
  return String(collection) === String(value);
469
746
  }
470
- /** A nil source or affix never matches. */
747
+ /** Nil for a nil source or affix, which drops the element of a mapped call. */
471
748
  function matchesAffix(name, value, affix) {
472
749
  if (value === null || affix === null)
473
- return false;
750
+ return null;
474
751
  return name === 'starts_with'
475
752
  ? String(value).startsWith(String(affix))
476
753
  : String(value).endsWith(String(affix));
477
754
  }
478
755
  function concatValues(values, argumentTypes) {
479
- if (values.length < 2)
480
- return null;
481
- const expectedType = argumentTypes[0];
482
- if (expectedType &&
483
- argumentTypes.slice(1).some(type => type !== null && compareRuleExpressionDataTypes(expectedType, type) === 'different'))
756
+ if (values.length < 2 || concatTypesDiffer(argumentTypes))
484
757
  return null;
485
758
  const presentValues = values.filter(value => value !== null);
486
759
  const firstValue = presentValues[0];
@@ -495,6 +768,48 @@ function concatValues(values, argumentTypes) {
495
768
  return null;
496
769
  return presentValues.join('');
497
770
  }
771
+ function concatTypesDiffer(argumentTypes) {
772
+ const expectedType = argumentTypes[0];
773
+ return !!expectedType &&
774
+ argumentTypes.slice(1).some(type => type !== null && compareRuleExpressionDataTypes(expectedType, type) === 'different');
775
+ }
776
+ /**
777
+ * concat() over arrays some of which are known only in part: the result
778
+ * holds each one's elements, an unknown one in its place, and may hold more
779
+ * where one may, which leaves every position unknown, as PartialArrayValue
780
+ * says. What more it may be carries over where each such part lists it. A
781
+ * value that is no array gives nil, as in concatValues(); a map is unknown,
782
+ * as in ruleValue().
783
+ */
784
+ function concatElements(parts, argumentTypes) {
785
+ if (parts.length < 2 || concatTypesDiffer(argumentTypes))
786
+ return known(null);
787
+ const elements = [];
788
+ let more;
789
+ let optional = [];
790
+ for (const part of parts) {
791
+ if (part instanceof RuleMapValue)
792
+ return unavailable('a map value');
793
+ if (part instanceof PartialArrayValue) {
794
+ elements.push(...part.elements);
795
+ if (!part.more)
796
+ continue;
797
+ more ??= part.more;
798
+ if (part.optional)
799
+ optional?.push(...part.optional);
800
+ else
801
+ optional = undefined;
802
+ }
803
+ else if (Array.isArray(part)) {
804
+ for (const value of part)
805
+ elements.push(known(value));
806
+ }
807
+ else if (part !== null) {
808
+ return known(null);
809
+ }
810
+ }
811
+ return known(PartialArrayValue.from(elements, more, optional));
812
+ }
498
813
  /** Cloudflare counts the bytes of a string. */
499
814
  function lengthOfValue(value) {
500
815
  if (value === null)
@@ -681,16 +996,11 @@ function removeBytes(sourceValue, removeValue) {
681
996
  const removed = new Set(textToBytes(String(removeValue)));
682
997
  return bytesToText(textToBytes(String(sourceValue)).filter(byte => !removed.has(byte)));
683
998
  }
684
- function removeQueryArgs(sourceValue, argValues) {
999
+ function removeQueryArgsValue(sourceValue, argValues) {
685
1000
  if (sourceValue === null)
686
1001
  return null;
687
1002
  const remove = new Set(argValues.filter((value) => value !== null).map(value => String(value)));
688
- const params = new URLSearchParams(String(sourceValue));
689
- for (const key of [...params.keys()]) {
690
- if (remove.has(key))
691
- params.delete(key);
692
- }
693
- return params.toString();
1003
+ return removeQueryArgs(String(sourceValue), remove);
694
1004
  }
695
1005
  function splitValue(sourceValue, separatorValue, limitValue) {
696
1006
  if (sourceValue === null || separatorValue === null || limitValue === null)
@@ -720,6 +1030,24 @@ function normalizeByteIndex(length, index) {
720
1030
  return Math.max(length + index, 0);
721
1031
  return Math.min(index, length);
722
1032
  }
1033
+ /** The ASCII whitespace that trim(), trim_start() and trim_end() remove without a byte set. */
1034
+ const DEFAULT_TRIM_BYTES = new Set([0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20]);
1035
+ /** Removes the listed bytes from one or both ends, as Cloudflare does, so a result can split a character. */
1036
+ function trimBytes(name, sourceValue, setValue) {
1037
+ if (sourceValue === null)
1038
+ return null;
1039
+ const trimmed = setValue === null ? DEFAULT_TRIM_BYTES : new Set(textToBytes(String(setValue)));
1040
+ const bytes = textToBytes(String(sourceValue));
1041
+ let start = 0;
1042
+ let end = bytes.length;
1043
+ if (name !== 'trim_end')
1044
+ while (start < end && trimmed.has(bytes[start]))
1045
+ start++;
1046
+ if (name !== 'trim_start')
1047
+ while (end > start && trimmed.has(bytes[end - 1]))
1048
+ end--;
1049
+ return bytesToText(bytes.subarray(start, end));
1050
+ }
723
1051
  function urlDecodeValue(sourceValue, optionsValue) {
724
1052
  if (sourceValue === null)
725
1053
  return null;