@libreflare/worker-runtime 0.10.5 → 0.10.7

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 (77) hide show
  1. package/README.md +86 -31
  2. package/dist/rule-evaluator/access-values.d.ts +27 -3
  3. package/dist/rule-evaluator/access-values.d.ts.map +1 -1
  4. package/dist/rule-evaluator/access-values.js +30 -9
  5. package/dist/rule-evaluator/access-values.js.map +1 -1
  6. package/dist/rule-evaluator/byte-strings.d.ts +6 -0
  7. package/dist/rule-evaluator/byte-strings.d.ts.map +1 -1
  8. package/dist/rule-evaluator/byte-strings.js +8 -0
  9. package/dist/rule-evaluator/byte-strings.js.map +1 -1
  10. package/dist/rule-evaluator/constants.d.ts +1 -1
  11. package/dist/rule-evaluator/constants.d.ts.map +1 -1
  12. package/dist/rule-evaluator/constants.js +5 -0
  13. package/dist/rule-evaluator/constants.js.map +1 -1
  14. package/dist/rule-evaluator/country-codes.generated.js +1 -1
  15. package/dist/rule-evaluator/diagnostics.d.ts +1 -1
  16. package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
  17. package/dist/rule-evaluator/diagnostics.js +5 -0
  18. package/dist/rule-evaluator/diagnostics.js.map +1 -1
  19. package/dist/rule-evaluator/edge-evaluation.d.ts +1 -1
  20. package/dist/rule-evaluator/edge-evaluation.d.ts.map +1 -1
  21. package/dist/rule-evaluator/edge-field-gaps.d.ts +30 -8
  22. package/dist/rule-evaluator/edge-field-gaps.d.ts.map +1 -1
  23. package/dist/rule-evaluator/edge-field-gaps.js +141 -16
  24. package/dist/rule-evaluator/edge-field-gaps.js.map +1 -1
  25. package/dist/rule-evaluator/edge-record.d.ts +3 -2
  26. package/dist/rule-evaluator/edge-record.d.ts.map +1 -1
  27. package/dist/rule-evaluator/edge-record.js +93 -21
  28. package/dist/rule-evaluator/edge-record.js.map +1 -1
  29. package/dist/rule-evaluator/engine-observations.generated.d.ts +38 -1
  30. package/dist/rule-evaluator/engine-observations.generated.d.ts.map +1 -1
  31. package/dist/rule-evaluator/engine-observations.generated.js +19 -2
  32. package/dist/rule-evaluator/engine-observations.generated.js.map +1 -1
  33. package/dist/rule-evaluator/explain.d.ts.map +1 -1
  34. package/dist/rule-evaluator/explain.js +45 -19
  35. package/dist/rule-evaluator/explain.js.map +1 -1
  36. package/dist/rule-evaluator/function-descriptions.d.ts +2 -0
  37. package/dist/rule-evaluator/function-descriptions.d.ts.map +1 -1
  38. package/dist/rule-evaluator/function-descriptions.generated.d.ts +131 -15
  39. package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
  40. package/dist/rule-evaluator/function-descriptions.generated.js +1173 -341
  41. package/dist/rule-evaluator/function-descriptions.generated.js.map +1 -1
  42. package/dist/rule-evaluator/function-descriptions.js.map +1 -1
  43. package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
  44. package/dist/rule-evaluator/function-signature-validation.js +33 -3
  45. package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
  46. package/dist/rule-evaluator/functions.d.ts +17 -4
  47. package/dist/rule-evaluator/functions.d.ts.map +1 -1
  48. package/dist/rule-evaluator/functions.js +181 -38
  49. package/dist/rule-evaluator/functions.js.map +1 -1
  50. package/dist/rule-evaluator/minifier.d.ts +9 -0
  51. package/dist/rule-evaluator/minifier.d.ts.map +1 -1
  52. package/dist/rule-evaluator/minifier.js +23 -0
  53. package/dist/rule-evaluator/minifier.js.map +1 -1
  54. package/dist/rule-evaluator/operators.d.ts.map +1 -1
  55. package/dist/rule-evaluator/operators.js +15 -6
  56. package/dist/rule-evaluator/operators.js.map +1 -1
  57. package/dist/rule-evaluator/parse-cache.d.ts +3 -1
  58. package/dist/rule-evaluator/parse-cache.d.ts.map +1 -1
  59. package/dist/rule-evaluator/parse-cache.js +4 -0
  60. package/dist/rule-evaluator/parse-cache.js.map +1 -1
  61. package/dist/rule-evaluator/parser.d.ts +7 -1
  62. package/dist/rule-evaluator/parser.d.ts.map +1 -1
  63. package/dist/rule-evaluator/parser.js +14 -0
  64. package/dist/rule-evaluator/parser.js.map +1 -1
  65. package/dist/rule-evaluator/quantifier.d.ts +2 -0
  66. package/dist/rule-evaluator/quantifier.d.ts.map +1 -1
  67. package/dist/rule-evaluator/quantifier.js +18 -9
  68. package/dist/rule-evaluator/quantifier.js.map +1 -1
  69. package/dist/rule-evaluator/validation.d.ts +1 -0
  70. package/dist/rule-evaluator/validation.d.ts.map +1 -1
  71. package/dist/rule-evaluator/validation.js +103 -19
  72. package/dist/rule-evaluator/validation.js.map +1 -1
  73. package/dist/rule-evaluator/wildcard.d.ts +2 -0
  74. package/dist/rule-evaluator/wildcard.d.ts.map +1 -1
  75. package/dist/rule-evaluator/wildcard.js +7 -8
  76. package/dist/rule-evaluator/wildcard.js.map +1 -1
  77. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { EQUALITY_ORDERING_OPERATORS, isConditionArgument, isDynamicValueNode, isExpressionNode, unhandledNode, } from './ast.js';
2
2
  import { applyRuntimeAccessPath, inPlaceOf, isUnknownElement, listedElement, OptionalElement, PartialArrayValue, RuleMapValue, } from './access-values.js';
3
- import { byteLength, bytesToText, canonicalText, textToBytes } from './byte-strings.js';
3
+ import { asciiLowerCase, byteLength, bytesToText, canonicalText, textToBytes } from './byte-strings.js';
4
4
  import { formatIpAddress, ipAddressOctets } from './custom-lists.js';
5
5
  import { resolveBoolField, resolveFieldNode } from './fields.js';
6
6
  import { hashInRange } from './hash-in-range.js';
@@ -10,7 +10,7 @@ import { conditionArray, extractQuantifierPredicate, givesNilForNilArgument, kee
10
10
  import { removeQueryArgs } from './query-args.js';
11
11
  import { expandReplacement, MAX_REPLACEMENT_REFERENCES, measureReplacement } from './replacement.js';
12
12
  import { urlDecode } from './url-decode.js';
13
- import { compileWildcard, wildcardCaptures } from './wildcard.js';
13
+ import { compileWildcard, wildcardCaptures, wildcardPatternText } from './wildcard.js';
14
14
  import { collectionElementDataType, compareRuleExpressionDataTypes, formatRuleExpressionDataType, evaluatedValueType, inferFunctionInvocation, isArrayConditionArgument, } from './rule-language-types.js';
15
15
  /**
16
16
  * The most a call's result holds, over all its elements when it maps; see
@@ -32,7 +32,10 @@ const TOO_LARGE = Symbol('too large');
32
32
  const MAX_JOINED_SIZE = MAX_RESULT_SIZE * 3;
33
33
  const UNRELIABLE_FUNCTION_REASONS = {
34
34
  bit_slice: 'packet bit slicing is not available in Worker request context',
35
+ hmac_md5: 'synchronous HMAC-MD5 is not available in this evaluator',
36
+ hmac_sha1: 'synchronous HMAC-SHA-1 is not available in this evaluator',
35
37
  hmac_sha256: 'synchronous HMAC-SHA-256 is not available in this evaluator',
38
+ hmac_sha512: 'synchronous HMAC-SHA-512 is not available in this evaluator',
36
39
  is_jwt_present: 'Cloudflare API JWT token configurations are not available in Worker request context',
37
40
  is_jwt_valid: 'Cloudflare API JWT token configurations are not available in Worker request context',
38
41
  is_timed_hmac_valid_v0: 'synchronous HMAC validation is not available in this evaluator',
@@ -40,6 +43,7 @@ const UNRELIABLE_FUNCTION_REASONS = {
40
43
  sha1: 'synchronous SHA-1 hashing is not available in this evaluator',
41
44
  sha256: 'synchronous SHA-256 hashing is not available in this evaluator',
42
45
  sha512: 'synchronous SHA-512 hashing is not available in this evaluator',
46
+ sign_sigv4_hmac_sha256: 'synchronous SigV4 signing is not available in this evaluator',
43
47
  uuidv4: 'Cloudflare uuidv4() derives randomness from the source bytes and cannot be reproduced exactly here',
44
48
  };
45
49
  export function getUnreliableRuleExpressionFunctionReason(name) {
@@ -120,7 +124,7 @@ export function evaluateCollection(fieldArg, ctx) {
120
124
  return array;
121
125
  if (!(array.value instanceof PartialArrayValue))
122
126
  return known({ values: array.value.filter(isCollectionValue) });
123
- const { elements, more, shortest } = array.value;
127
+ const { elements, more, shortest, excludes } = array.value;
124
128
  const values = array.value.knownValues();
125
129
  const optional = elements.flatMap(listed => listed instanceof OptionalElement && !isUnknownElement(listed.element) ? [listed.element.value] : []);
126
130
  return known({
@@ -129,8 +133,27 @@ export function evaluateCollection(fieldArg, ctx) {
129
133
  optional: optional.filter(isCollectionValue),
130
134
  mayHoldUnknown: more !== undefined || values.length + optional.length < elements.length,
131
135
  mayBeEmpty: shortest === 0,
136
+ ...excludes ? { unknownMayBe: unknownMayBe(array.value, excludes) } : {},
132
137
  });
133
138
  }
139
+ /**
140
+ * Whether an element a partly known array does not know may be a value, by
141
+ * what each surely is not in every reading of an edge record. The members a
142
+ * chain may name stand for every reading, and reading what a record leaves
143
+ * open only to name them would make eitherWay() try readings that cannot
144
+ * change the outcome, past its limit too.
145
+ */
146
+ function unknownMayBe(array, excludes) {
147
+ let unknown;
148
+ return value => (unknown ??= unknownIndexes(array)).some(index => !excludes(index, value, true));
149
+ }
150
+ /** The indexes of the elements a partly known array does not know, and the first past those it lists, when it may hold more. */
151
+ function unknownIndexes(array) {
152
+ const unknown = array.elements.flatMap((listed, index) => isUnknownElement(listedElement(listed)) ? [index] : []);
153
+ if (array.more)
154
+ unknown.push(array.elements.length);
155
+ return unknown;
156
+ }
134
157
  function isCollectionValue(value) {
135
158
  return typeof value === 'string' || typeof value === 'number';
136
159
  }
@@ -164,9 +187,10 @@ export function findMatchedSetMemberForFunc(node, ctx) {
164
187
  * matched first, as its chain entry names the first element's, or null for
165
188
  * none: the one findMatchedSetMemberForFunc() finds in a known array. Over an
166
189
  * array with unknown elements, every member a value can match first, as an
167
- * unknown element may come first and hold any value; those the known
168
- * elements match come first. Over an unknown array, every such member. An
169
- * `all()` over an array that may be empty may also name none.
190
+ * unknown element may come first and hold any value but those it surely is
191
+ * not; those the known elements match come first. Over an unknown array,
192
+ * every such member. An `all()` over an array that may be empty may also
193
+ * name none.
170
194
  */
171
195
  export function possibleSetMembersForFunc(node, ctx) {
172
196
  const quantifier = setQuantifier(node);
@@ -186,8 +210,11 @@ export function possibleSetMembersForFunc(node, ctx) {
186
210
  if (!collection.value.unknown)
187
211
  return [null];
188
212
  }
189
- for (const member of reachableSetMembers(quantifier.list))
190
- members.add(member);
213
+ const mayBe = isUnknown(collection) ? undefined : collection.value.unknownMayBe;
214
+ for (const member of reachableSetMembers(quantifier.list)) {
215
+ if (!mayBe || member.type !== 'string' || mayBe(member.value))
216
+ members.add(member);
217
+ }
191
218
  if (node.name === 'all' && (isUnknown(collection) || collection.value.mayBeEmpty))
192
219
  members.add(null);
193
220
  return [...members];
@@ -258,7 +285,7 @@ function pairArrays(owner, predicate, ctx, valueCall, source) {
258
285
  return { ...NO_PAIRS, nilCall: valueCall };
259
286
  }
260
287
  const compare = condition.kind === 'Comparison' ? comparatorFor(owner, condition, ctx) : isTrueValue;
261
- const array = pairedArray(evaluated, warnings, compare, ctx);
288
+ const array = pairedArray(evaluated, warnings, compare, ctx, condition.kind === 'Comparison' ? condition : undefined);
262
289
  if (array.length === 0 && !array.more)
263
290
  return NO_PAIRS;
264
291
  arrays.set(condition, array);
@@ -292,6 +319,8 @@ function pairArrays(owner, predicate, ctx, valueCall, source) {
292
319
  continue;
293
320
  const last = more ? -1 : array.length - 1;
294
321
  array.elements = array.elements.map((listed, index) => index < leading || index === last ? listed : unknownLength);
322
+ // What an element surely is not tells of its place, which these no longer keep.
323
+ array.excludes = undefined;
295
324
  }
296
325
  const { shortest: certain, unknownLength } = shortest;
297
326
  return { arrays, end, missing: index => index < certain ? undefined : unknownLength, tail, tailFrom: end };
@@ -333,7 +362,10 @@ export function evaluatePairedQuantifier(node, reading, ctx) {
333
362
  else if (isUnknown(outcome))
334
363
  (unknowns ??= []).push(outcome);
335
364
  }
336
- pending ??= tail;
365
+ // Pairs past those listed may be none, so they settle nothing, but where their elements surely are not what
366
+ // would settle it, they leave it as it is.
367
+ if (tail && pairedOutcome(predicate, end, arrays) !== !settling)
368
+ pending ??= tail;
337
369
  // Reading an unknown element warns, so only the first is read. Only an unresolved list's result can match
338
370
  // or miss while unknown, and a list holds IP addresses, which no array does, so the others change nothing.
339
371
  if (pending)
@@ -431,21 +463,48 @@ function describeSameItems(arrays, source) {
431
463
  function isTrueValue(value) {
432
464
  return value === true;
433
465
  }
434
- /** A condition's array, or a PairedSource's, from its evaluated collection and the warnings evaluating it gave. */
435
- function pairedArray(evaluated, warnings, compare, ctx) {
466
+ /**
467
+ * A condition's array, or a PairedSource's, from its evaluated collection and
468
+ * the warnings evaluating it gave. A comparison's can be settled at an
469
+ * element it does not know; see excludedOutcome().
470
+ */
471
+ function pairedArray(evaluated, warnings, compare, ctx, comparison) {
436
472
  const array = isUnknown(evaluated) ? evaluated : arrayValue(evaluated.value);
437
473
  if (isUnknown(array)) {
438
474
  // A collection unknown whole tells why only when read, since the other collections may settle the result.
439
475
  const more = deferWarnings(ctx, warnings, () => array);
440
- return { values: undefined, elements: [], length: 0, shortest: 0, more, unknownLength: more, compare };
476
+ return { values: undefined, elements: [], length: 0, shortest: 0, more, moreFrom: undefined, leading: undefined, unknownLength: more, compare, excludes: undefined, comparison: undefined };
441
477
  }
442
478
  giveWarnings(ctx, warnings);
443
479
  if (!(array.value instanceof PartialArrayValue)) {
444
480
  const { length } = array.value;
445
- return { values: array.value, elements: [], length, shortest: length, compare };
481
+ return { values: array.value, elements: [], length, shortest: length, more: undefined, moreFrom: undefined, leading: undefined, unknownLength: undefined, compare, excludes: undefined, comparison: undefined };
482
+ }
483
+ const { elements, shortest, more, moreFrom, leading, unknownLength, excludes } = array.value;
484
+ return { values: undefined, elements, length: elements.length, shortest, more, moreFrom, leading, unknownLength, compare, excludes: comparison && excludes, comparison };
485
+ }
486
+ /**
487
+ * A comparison's outcome at an element known only by what it surely is not,
488
+ * where that settles it: `eq` and `ne` with a string it is not, `wildcard`
489
+ * and `strict wildcard` with a pattern without `*` whose text it is not, and
490
+ * `in` an inline list of strings it is none of. See PartialArrayValue.excludes.
491
+ */
492
+ function excludedOutcome({ excludes, comparison }, index) {
493
+ if (!excludes || !comparison)
494
+ return undefined;
495
+ const { op, right } = comparison;
496
+ if (right?.kind === 'StringLiteral') {
497
+ if (op === 'eq' || op === 'ne')
498
+ return excludes(index, right.value) ? op === 'ne' : undefined;
499
+ if (op !== 'wildcard' && op !== 'strict_wildcard')
500
+ return undefined;
501
+ // A pattern without `*` matches only its text, in any case or, strict, as written.
502
+ const text = wildcardPatternText(right.value);
503
+ return text !== undefined && excludes(index, text) ? false : undefined;
446
504
  }
447
- const { elements, shortest, more, moreFrom, leading, unknownLength } = array.value;
448
- return { values: undefined, elements, length: elements.length, shortest, more, moreFrom, leading, unknownLength, compare };
505
+ if (op !== 'in' || right?.kind !== 'SetLiteral')
506
+ return undefined;
507
+ return right.elements.every(member => member.type === 'string' && excludes(index, member.value)) ? false : undefined;
449
508
  }
450
509
  /**
451
510
  * Runs `compute` with warnings of its own, to give when its result is read:
@@ -467,6 +526,16 @@ function giveWarnings(ctx, warnings) {
467
526
  for (const warning of warnings)
468
527
  ctx.warnings.add(warning);
469
528
  }
529
+ /** Takes from ctx, into `into`, the warnings it was given after its first `given`. */
530
+ function takeWarnings(ctx, given, into) {
531
+ let index = 0;
532
+ for (const warning of ctx.warnings) {
533
+ if (index++ < given)
534
+ continue;
535
+ into.add(warning);
536
+ ctx.warnings.delete(warning);
537
+ }
538
+ }
470
539
  /** An unknown value that gives its warnings only when read, as an unknown element does. */
471
540
  function deferWarnings(ctx, warnings, read) {
472
541
  return () => {
@@ -504,7 +573,7 @@ function elementOutcome(array, index) {
504
573
  if (array.values)
505
574
  return array.compare(array.values[index]);
506
575
  const element = elementAt(array, index);
507
- return isUnknownElement(element) ? element : array.compare(element.value);
576
+ return isUnknownElement(element) ? excludedOutcome(array, index) ?? element : array.compare(element.value);
508
577
  }
509
578
  /** The element at an index of a collection known in part, unknown where it lists none. */
510
579
  function elementAt(array, index) {
@@ -543,7 +612,7 @@ function combinePairedOutcomes(operands, deciding, combine, index, arrays) {
543
612
  * unknown value, or values Cloudflare would not compare, make the comparison
544
613
  * unknown.
545
614
  */
546
- function comparatorFor(owner, comparison, ctx) {
615
+ export function comparatorFor(owner, comparison, ctx) {
547
616
  const { op, right } = comparison;
548
617
  if (!right)
549
618
  return () => false;
@@ -675,7 +744,7 @@ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
675
744
  const result = evaluateHasValue(values.value, value.value);
676
745
  if (result !== false || !partial)
677
746
  return known(result);
678
- const unknown = partial.unknownMatch(element => evaluateHasValue(element, value.value) === true);
747
+ const unknown = partial.unknownMatch(element => evaluateHasValue(element, value.value) === true, value.value);
679
748
  return unknown ? unknown() : known(false);
680
749
  }
681
750
  case 'hash_in_range':
@@ -696,8 +765,19 @@ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
696
765
  return lookupJsonValue('integer', args.length, argument);
697
766
  case 'lookup_json_string':
698
767
  return lookupJsonValue('string', args.length, argument);
699
- case 'bit_slice':
768
+ case 'hmac_md5':
769
+ case 'hmac_sha1':
700
770
  case 'hmac_sha256':
771
+ case 'hmac_sha512': {
772
+ // A nil message or key gives nil, as Cloudflare documents, so the other one's warnings do not apply.
773
+ const { result: values, warnings } = collectWarnings(ctx, () => [argument(0), argument(1)]);
774
+ const nil = values.find(value => !isUnknown(value) && value.value === null);
775
+ if (nil)
776
+ return nil;
777
+ giveWarnings(ctx, warnings);
778
+ return unreliableFunction(ctx, name);
779
+ }
780
+ case 'bit_slice':
701
781
  case 'is_jwt_present':
702
782
  case 'is_jwt_valid':
703
783
  case 'is_timed_hmac_valid_v0':
@@ -705,6 +785,7 @@ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
705
785
  case 'sha1':
706
786
  case 'sha256':
707
787
  case 'sha512':
788
+ case 'sign_sigv4_hmac_sha256':
708
789
  case 'uuidv4':
709
790
  return unreliableFunction(ctx, name);
710
791
  }
@@ -763,11 +844,13 @@ function functionResult(name, values, invocation) {
763
844
  case 'ends_with':
764
845
  case 'starts_with':
765
846
  return matchesAffix(name, at(0), at(1));
847
+ case 'format_date':
848
+ return formatDate(at(0), at(1));
766
849
  case 'join':
767
850
  return joinValues(at(0), at(1));
768
851
  case 'lower':
769
852
  // Cloudflare converts ASCII letters only.
770
- return mapStringValue(at(0), value => value.replace(/[A-Z]+/g, letters => letters.toLowerCase()));
853
+ return mapStringValue(at(0), asciiLowerCase);
771
854
  case 'regex_replace':
772
855
  return regexReplace(at(0), at(1), at(2));
773
856
  case 'remove_bytes':
@@ -817,25 +900,17 @@ function evaluateFuncArray(node, ctx, invocation) {
817
900
  return known([]);
818
901
  }
819
902
  }
820
- // What a nil second argument gives is not known, so neither is the array's length; see NEVER_NIL_FUNCTIONS.
821
- if ((elements.length > 0 || more) && node.name === 'hmac_sha256') {
822
- const value = (later[1] = evaluateArgValue(node.args[1], ctx));
823
- if (isUnknown(value))
824
- return value;
825
- if (value.value === null)
826
- return unreliableFunction(ctx, node.name);
827
- }
828
903
  let keepsPlaces = keepsPlacesWhenMapped(node.name);
829
904
  const tooLarge = () => tooLargeResult(ctx, node.name);
830
905
  const evaluate = (element) => {
831
906
  const direct = evaluateDirectFuncValue(node, ctx, invocation, later, element);
832
907
  return direct === TOO_LARGE ? direct : ruleValue(direct);
833
908
  };
834
- // Elements it may lack leave the others their whole budget, and those with an unknown result warn only when
835
- // read. The first may have read a later argument for all, so they share their warnings.
909
+ // Elements it may lack leave the others their whole budget. Those, and unknown results kept in place, warn only
910
+ // when read. The first may have read a later argument for all, so they share their warnings.
836
911
  let size = 0;
837
912
  let optionalSize = 0;
838
- let optionalWarnings;
913
+ let deferredWarnings;
839
914
  let resultsFrom = 0;
840
915
  const results = [];
841
916
  for (let index = 0; index < elements.length; index++) {
@@ -852,18 +927,22 @@ function evaluateFuncArray(node, ctx, invocation) {
852
927
  if (optional) {
853
928
  const collected = collectWarnings(ctx, () => evaluate(element.value));
854
929
  evaluated = collected.result;
855
- optionalWarnings ??= new Set();
930
+ deferredWarnings ??= new Set();
856
931
  for (const warning of collected.warnings)
857
- optionalWarnings.add(warning);
932
+ deferredWarnings.add(warning);
858
933
  }
859
934
  else {
935
+ const given = ctx.warnings.size;
860
936
  evaluated = evaluate(element.value);
937
+ if (keepsPlaces && evaluated !== TOO_LARGE && isUnknown(evaluated))
938
+ takeWarnings(ctx, given, (deferredWarnings ??= new Set()));
861
939
  }
862
940
  if (evaluated !== TOO_LARGE) {
863
941
  if (isUnknown(evaluated)) {
864
942
  const unknown = evaluated;
865
- result = deferWarnings(ctx, optionalWarnings ?? [], () => unknown);
866
- if (!optional)
943
+ result = deferWarnings(ctx, deferredWarnings ?? [], () => unknown);
944
+ // A function that gives every element a result keeps an unknown one in place; otherwise the call is unknown.
945
+ if (!optional && !keepsPlaces)
867
946
  return result();
868
947
  }
869
948
  else if (evaluated.value === null) {
@@ -883,8 +962,11 @@ function evaluateFuncArray(node, ctx, invocation) {
883
962
  if (index < moreFrom)
884
963
  resultsFrom = results.length;
885
964
  }
886
- if (keepsPlaces)
887
- return known(PartialArrayValue.from(results, more, resultsFrom));
965
+ if (keepsPlaces) {
966
+ // Changing only the case of letters, the call keeps in each place what the element there surely is not.
967
+ const excludes = (node.name === 'lower' || node.name === 'upper') && value instanceof PartialArrayValue ? value.excludes : undefined;
968
+ return known(PartialArrayValue.from(results, more, resultsFrom, excludes));
969
+ }
888
970
  // An unknown element may give nil, which drops it.
889
971
  const droppable = results.map(listed => {
890
972
  const element = listedElement(listed);
@@ -1192,6 +1274,67 @@ function encodeHexValue(value) {
1192
1274
  }
1193
1275
  return bytesToText(digits);
1194
1276
  }
1277
+ const SECONDS_PER_DAY = 86400;
1278
+ /** The first and last seconds of the years format_date() formats, -999999 to 999999; it gives nil outside them. */
1279
+ const MIN_DATE_TIMESTAMP = daysFromCivil(-999999, 1, 1) * SECONDS_PER_DAY;
1280
+ const MAX_DATE_TIMESTAMP = daysFromCivil(1000000, 1, 1) * SECONDS_PER_DAY - 1;
1281
+ /**
1282
+ * Formats Unix seconds as UTC text in the proleptic Gregorian calendar. A
1283
+ * year outside 0 to 9999 has a sign, and every year has at least four digits.
1284
+ * Validation leaves only the directives Cloudflare supports.
1285
+ */
1286
+ function formatDate(timestampValue, formatValue) {
1287
+ if (typeof timestampValue !== 'number' || typeof formatValue !== 'string')
1288
+ return null;
1289
+ if (timestampValue < MIN_DATE_TIMESTAMP || timestampValue > MAX_DATE_TIMESTAMP)
1290
+ return null;
1291
+ const days = Math.floor(timestampValue / SECONDS_PER_DAY);
1292
+ const seconds = timestampValue - days * SECONDS_PER_DAY;
1293
+ const [year, month, day] = civilFromDays(days);
1294
+ const twoDigits = (value) => String(value).padStart(2, '0');
1295
+ const yearText = year >= 0 && year <= 9999
1296
+ ? String(year).padStart(4, '0')
1297
+ : `${year < 0 ? '-' : '+'}${String(Math.abs(year)).padStart(4, '0')}`;
1298
+ return formatValue.replace(/%([YmdHMS%])/g, (_directive, letter) => {
1299
+ switch (letter) {
1300
+ case 'Y':
1301
+ return yearText;
1302
+ case 'm':
1303
+ return twoDigits(month);
1304
+ case 'd':
1305
+ return twoDigits(day);
1306
+ case 'H':
1307
+ return twoDigits(Math.floor(seconds / 3600));
1308
+ case 'M':
1309
+ return twoDigits(Math.floor(seconds / 60) % 60);
1310
+ case 'S':
1311
+ return twoDigits(seconds % 60);
1312
+ default:
1313
+ return '%';
1314
+ }
1315
+ });
1316
+ }
1317
+ /** The days from 1970-01-01 to a date; see https://howardhinnant.github.io/date_algorithms.html. */
1318
+ function daysFromCivil(year, month, day) {
1319
+ const shiftedYear = month <= 2 ? year - 1 : year;
1320
+ const era = Math.floor(shiftedYear / 400);
1321
+ const yearOfEra = shiftedYear - era * 400;
1322
+ const dayOfYear = Math.floor((153 * (month > 2 ? month - 3 : month + 9) + 2) / 5) + day - 1;
1323
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
1324
+ return era * 146097 + dayOfEra - 719468;
1325
+ }
1326
+ /** The year, month and day of a count of days from 1970-01-01; the inverse of daysFromCivil(). */
1327
+ function civilFromDays(days) {
1328
+ const shifted = days + 719468;
1329
+ const era = Math.floor(shifted / 146097);
1330
+ const dayOfEra = shifted - era * 146097;
1331
+ const yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36524) - Math.floor(dayOfEra / 146096)) / 365);
1332
+ const dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
1333
+ const monthIndex = Math.floor((5 * dayOfYear + 2) / 153);
1334
+ const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1;
1335
+ const month = monthIndex < 10 ? monthIndex + 3 : monthIndex - 9;
1336
+ return [yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day];
1337
+ }
1195
1338
  /**
1196
1339
  * Decodes standard Base64 as Cloudflare does, observed with live requests: it
1197
1340
  * skips whitespace and takes input with or without padding. Other input is