fastly.js 0.9.1 → 0.9.2

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.
package/dist/index.js CHANGED
@@ -1536,14 +1536,269 @@ function collectCallStatements(statements) {
1536
1536
  return calls;
1537
1537
  }
1538
1538
 
1539
- // src/vcl-strings.ts
1539
+ // src/vcl-regex.ts
1540
1540
  var utf8Encoder = new TextEncoder;
1541
- var utf8Decoder = new TextDecoder;
1541
+ var utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
1542
+ var ASCII = /^[\x00-\x7f]*$/;
1543
+ function toBytes(s) {
1544
+ if (ASCII.test(s))
1545
+ return s;
1546
+ const bytes = utf8Encoder.encode(s);
1547
+ let out = "";
1548
+ for (let i = 0;i < bytes.length; i++)
1549
+ out += String.fromCharCode(bytes[i]);
1550
+ return out;
1551
+ }
1552
+ function fromBytes(s) {
1553
+ if (ASCII.test(s))
1554
+ return s;
1555
+ const bytes = new Uint8Array(s.length);
1556
+ for (let i = 0;i < s.length; i++)
1557
+ bytes[i] = s.charCodeAt(i);
1558
+ return utf8Decoder.decode(bytes);
1559
+ }
1560
+ var DIGIT = [[48, 57]];
1561
+ var UPPER = [[65, 90]];
1562
+ var LOWER = [[97, 122]];
1563
+ var ALPHA = [...UPPER, ...LOWER];
1564
+ var ALNUM = [...DIGIT, ...ALPHA];
1565
+ var WORD = [...ALNUM, [95, 95]];
1566
+ var BLANK = [
1567
+ [9, 9],
1568
+ [32, 32]
1569
+ ];
1570
+ var SPACE = [
1571
+ [9, 13],
1572
+ [32, 32]
1573
+ ];
1574
+ var SETS = {
1575
+ d: DIGIT,
1576
+ w: WORD,
1577
+ s: SPACE,
1578
+ h: [...BLANK, [160, 160]],
1579
+ v: [
1580
+ [10, 13],
1581
+ [133, 133]
1582
+ ]
1583
+ };
1584
+ var POSIX = {
1585
+ alpha: ALPHA,
1586
+ digit: DIGIT,
1587
+ alnum: ALNUM,
1588
+ upper: UPPER,
1589
+ lower: LOWER,
1590
+ space: SPACE,
1591
+ blank: BLANK,
1592
+ punct: [
1593
+ [33, 47],
1594
+ [58, 64],
1595
+ [91, 96],
1596
+ [123, 126]
1597
+ ],
1598
+ xdigit: [...DIGIT, [65, 70], [97, 102]],
1599
+ cntrl: [
1600
+ [0, 31],
1601
+ [127, 127]
1602
+ ],
1603
+ print: [[32, 126]],
1604
+ graph: [[33, 126]],
1605
+ word: WORD,
1606
+ ascii: [[0, 127]]
1607
+ };
1608
+ var ANCHORS = {
1609
+ A: "^",
1610
+ z: "$",
1611
+ Z: "(?=\\n?$)",
1612
+ b: "\\b",
1613
+ B: "\\B",
1614
+ R: "(?:\\r\\n|[\\n\\x0b\\f\\r\\x85])"
1615
+ };
1616
+ var SIMPLE_ESCAPES = {
1617
+ n: 10,
1618
+ r: 13,
1619
+ t: 9,
1620
+ f: 12,
1621
+ e: 27,
1622
+ a: 7,
1623
+ b: 8
1624
+ };
1625
+ function complement(ranges) {
1626
+ const out = [];
1627
+ let next = 0;
1628
+ for (const [lo, hi] of [...ranges].sort((a, b) => a[0] - b[0])) {
1629
+ if (lo > next)
1630
+ out.push([next, lo - 1]);
1631
+ next = Math.max(next, hi + 1);
1632
+ }
1633
+ if (next <= 255)
1634
+ out.push([next, 255]);
1635
+ return out;
1636
+ }
1637
+ function withOtherCase(ranges) {
1638
+ const out = [...ranges];
1639
+ for (const [lo, hi] of ranges) {
1640
+ for (const [a, z, shift] of [
1641
+ [65, 90, 32],
1642
+ [97, 122, -32]
1643
+ ]) {
1644
+ const l = Math.max(lo, a);
1645
+ const h = Math.min(hi, z);
1646
+ if (l <= h)
1647
+ out.push([l + shift, h + shift]);
1648
+ }
1649
+ }
1650
+ return out;
1651
+ }
1652
+ function classSource(ranges, negate, caseless) {
1653
+ const hex = (c) => `\\x${c.toString(16).padStart(2, "0")}`;
1654
+ const body = (caseless ? withOtherCase(ranges) : ranges).map(([lo, hi]) => lo === hi ? hex(lo) : `${hex(lo)}-${hex(hi)}`).join("");
1655
+ return `[${negate ? "^" : ""}${body}]`;
1656
+ }
1657
+ var isSingleChar = (r) => r.length === 1 && r[0][0] === r[0][1];
1658
+ function escapeRanges(p, i) {
1659
+ const c = p[i];
1660
+ const set = SETS[c.toLowerCase()];
1661
+ if (set)
1662
+ return [c === c.toLowerCase() ? set : complement(set), i + 1];
1663
+ let code = SIMPLE_ESCAPES[c];
1664
+ let next = i + 1;
1665
+ const braced = /^x\{([0-9a-fA-F]+)\}/.exec(p.slice(i));
1666
+ if (braced) {
1667
+ code = parseInt(braced[1], 16);
1668
+ next = i + braced[0].length;
1669
+ } else if (c === "x" && p[i + 1] !== "{" || c === "0") {
1670
+ const digits = (c === "x" ? /^[0-9a-f]{0,2}/i : /^[0-7]{0,2}/).exec(p.slice(i + 1))[0];
1671
+ code = digits ? parseInt(digits, c === "x" ? 16 : 8) : 0;
1672
+ next += digits.length;
1673
+ } else if (!/[a-z0-9]/i.test(c)) {
1674
+ code = c.charCodeAt(0);
1675
+ }
1676
+ if (code === undefined || code > 255) {
1677
+ throw new Error(`Unsupported regex escape \\${c}`);
1678
+ }
1679
+ return [[[code, code]], next];
1680
+ }
1681
+ function classItem(p, i) {
1682
+ return p[i] === "\\" ? escapeRanges(p, i + 1) : [[[p.charCodeAt(i), p.charCodeAt(i)]], i + 1];
1683
+ }
1684
+ function classAt(p, i, caseless) {
1685
+ const negate = p[i] === "^";
1686
+ if (negate)
1687
+ i++;
1688
+ const ranges = [];
1689
+ do {
1690
+ if (i >= p.length)
1691
+ throw new Error("Missing ] in regex character class");
1692
+ const posix = /^\[:(\^?)([a-z]+):\]/.exec(p.slice(i));
1693
+ if (posix) {
1694
+ const name = caseless && (posix[2] === "upper" || posix[2] === "lower") ? "alpha" : posix[2];
1695
+ const set = POSIX[name];
1696
+ if (!set)
1697
+ throw new Error(`Unknown POSIX class ${posix[0]}`);
1698
+ ranges.push(...posix[1] ? complement(set) : set);
1699
+ i += posix[0].length;
1700
+ continue;
1701
+ }
1702
+ let item;
1703
+ [item, i] = classItem(p, i);
1704
+ if (p[i] === "-" && p[i + 1] !== "]" && i + 1 < p.length) {
1705
+ const [end, next] = classItem(p, i + 1);
1706
+ if (!isSingleChar(item) || !isSingleChar(end) || item[0][0] > end[0][0]) {
1707
+ throw new Error("Invalid range in regex character class");
1708
+ }
1709
+ item = [[item[0][0], end[0][0]]];
1710
+ i = next;
1711
+ }
1712
+ ranges.push(...item);
1713
+ } while (p[i] !== "]");
1714
+ return [classSource(ranges, negate, caseless), i + 1];
1715
+ }
1716
+ function translate(p) {
1717
+ let out = "";
1718
+ let opts = "";
1719
+ const saved = [];
1720
+ let i = 0;
1721
+ while (i < p.length) {
1722
+ const c = p[i++];
1723
+ let m;
1724
+ if (c === "[") {
1725
+ let cls;
1726
+ [cls, i] = classAt(p, i, opts.includes("i"));
1727
+ out += cls;
1728
+ } else if (c === "(") {
1729
+ saved.push(opts);
1730
+ const rest = p.slice(i);
1731
+ if (m = /^\?#[^)]*\)/.exec(rest)) {
1732
+ saved.pop();
1733
+ } else if (m = /^\?P=(\w+)\)/.exec(rest)) {
1734
+ saved.pop();
1735
+ out += `\\k<${m[1]}>`;
1736
+ } else if (m = /^\?(?:P?<(\w+)>|'(\w+)')/.exec(rest)) {
1737
+ out += `(?<${m[1] ?? m[2]}>`;
1738
+ } else if (m = /^(?:\?[:=!]|\?<[=!]|(?!\?))/.exec(rest)) {
1739
+ out += `(${m[0]}`;
1740
+ } else if (m = /^\?([a-zA-Z]*)(?:-([a-zA-Z]*))?([:)])/.exec(rest)) {
1741
+ const [, on = "", off = "", end] = m;
1742
+ for (const f of on + off) {
1743
+ if (!"ims".includes(f))
1744
+ throw new Error(`Unsupported regex option (?${f})`);
1745
+ }
1746
+ if (end === ")")
1747
+ saved.pop();
1748
+ else
1749
+ out += "(?:";
1750
+ opts = [...opts + on].filter((f) => !off.includes(f)).join("");
1751
+ } else {
1752
+ throw new Error(`Unsupported regex group (${rest.slice(0, 2)}`);
1753
+ }
1754
+ i += m[0].length;
1755
+ } else if (c === ")") {
1756
+ opts = saved.pop() ?? opts;
1757
+ out += ")";
1758
+ } else if (c === ".") {
1759
+ out += opts.includes("s") ? "[\\s\\S]" : "[^\\n]";
1760
+ } else if (c === "^") {
1761
+ out += opts.includes("m") ? "(?:^|(?<=\\n)(?=[\\s\\S]))" : "^";
1762
+ } else if (c === "$") {
1763
+ out += opts.includes("m") ? "(?=\\n|$)" : "(?=\\n?$)";
1764
+ } else if (c !== "\\") {
1765
+ out += opts.includes("i") && /[a-z]/i.test(c) ? `[${c.toLowerCase()}${c.toUpperCase()}]` : c;
1766
+ } else if (p[i] === undefined) {
1767
+ throw new Error("Regex ends with a \\");
1768
+ } else if (ANCHORS[p[i]] !== undefined) {
1769
+ out += ANCHORS[p[i++]];
1770
+ } else if (m = /^(?:[1-9]\d*|k<\w+>)/.exec(p.slice(i))) {
1771
+ out += `(?:\\${m[0]})`;
1772
+ i += m[0].length;
1773
+ } else {
1774
+ let ranges;
1775
+ [ranges, i] = escapeRanges(p, i);
1776
+ out += classSource(ranges, false, opts.includes("i"));
1777
+ }
1778
+ }
1779
+ return out;
1780
+ }
1781
+ var cache = new Map;
1782
+ function compileRegex(pattern, flags = "") {
1783
+ const key = `${flags}/${pattern}`;
1784
+ let re = cache.get(key);
1785
+ if (re === undefined) {
1786
+ re = new RegExp(translate(toBytes(pattern)), flags);
1787
+ if (cache.size >= 1000)
1788
+ cache.clear();
1789
+ cache.set(key, re);
1790
+ }
1791
+ return re;
1792
+ }
1793
+
1794
+ // src/vcl-strings.ts
1795
+ var utf8Encoder2 = new TextEncoder;
1796
+ var utf8Decoder2 = new TextDecoder;
1542
1797
  function utf8Bytes(s) {
1543
- return utf8Encoder.encode(s);
1798
+ return utf8Encoder2.encode(s);
1544
1799
  }
1545
1800
  function decodeBytes(bytes) {
1546
- return utf8Decoder.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
1801
+ return utf8Decoder2.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
1547
1802
  }
1548
1803
  function isAlnumByte(b) {
1549
1804
  return b >= 65 && b <= 90 || b >= 97 && b <= 122 || b >= 48 && b <= 57;
@@ -1918,33 +2173,34 @@ function expandReplacement(_input, replacement, match) {
1918
2173
  }
1919
2174
  function regsub(str, pattern, replacement) {
1920
2175
  try {
1921
- const s = String(str);
1922
- const re = new RegExp(pattern);
1923
- const match = re.exec(s);
2176
+ const s = toBytes(String(str));
2177
+ const match = compileRegex(String(pattern)).exec(s);
1924
2178
  if (!match)
1925
- return s;
1926
- return s.slice(0, match.index) + expandReplacement(s, replacement, match) + s.slice(match.index + match[0].length);
2179
+ return String(str);
2180
+ return fromBytes(s.slice(0, match.index) + expandReplacement(s, toBytes(String(replacement)), match) + s.slice(match.index + match[0].length));
1927
2181
  } catch {
1928
2182
  return str;
1929
2183
  }
1930
2184
  }
1931
2185
  function regsuball(str, pattern, replacement) {
1932
2186
  try {
1933
- const s = String(str);
1934
- const re = new RegExp(pattern, "g");
2187
+ const s = toBytes(String(str));
2188
+ const re = compileRegex(String(pattern), "g");
2189
+ re.lastIndex = 0;
2190
+ const sub = toBytes(String(replacement));
1935
2191
  let result = "";
1936
2192
  let lastEnd = 0;
1937
2193
  let match;
1938
2194
  while ((match = re.exec(s)) !== null) {
1939
2195
  result += s.slice(lastEnd, match.index);
1940
- result += expandReplacement(s, replacement, match);
2196
+ result += expandReplacement(s, sub, match);
1941
2197
  lastEnd = match.index + match[0].length;
1942
2198
  if (match[0].length === 0) {
1943
2199
  re.lastIndex++;
1944
2200
  }
1945
2201
  }
1946
2202
  result += s.slice(lastEnd);
1947
- return result;
2203
+ return fromBytes(result);
1948
2204
  } catch {
1949
2205
  return str;
1950
2206
  }
@@ -3267,6 +3523,21 @@ function fastlyHash(key, seed, from, to) {
3267
3523
  return null;
3268
3524
  }
3269
3525
  var MAX_RTIME_SECONDS = 9223372036.854776;
3526
+ function urlComponents(url) {
3527
+ const pathEnd = url.search(/[?#]/);
3528
+ const path = pathEnd < 0 ? url : url.substring(0, pathEnd);
3529
+ const qs = url[pathEnd] === "?" ? url.substring(pathEnd + 1).split("#")[0] : "";
3530
+ const lastSlash = path.lastIndexOf("/");
3531
+ const basename2 = path.substring(lastSlash + 1);
3532
+ const dot = basename2.lastIndexOf(".");
3533
+ return {
3534
+ path,
3535
+ qs,
3536
+ dirname: lastSlash > 0 ? path.substring(0, lastSlash) : "/",
3537
+ basename: basename2,
3538
+ ext: dot >= 0 ? basename2.substring(dot + 1) : ""
3539
+ };
3540
+ }
3270
3541
  function serializeHeaders(headers) {
3271
3542
  if (!headers)
3272
3543
  return "";
@@ -4759,11 +5030,7 @@ class VCLCompiler {
4759
5030
  return raw === undefined ? VCLString.notset() : firstHeaderFragment(raw);
4760
5031
  }
4761
5032
  if (parts.length === 3 && idPart0 === "re" && idPart1 === "group") {
4762
- const groupNumber = parseInt(idPart2, 10);
4763
- if (!Number.isNaN(groupNumber) && context.re?.groups?.[groupNumber] !== undefined) {
4764
- return context.re.groups[groupNumber];
4765
- }
4766
- return VCLString.notset();
5033
+ return context.re?.groups?.[idPart2] ?? VCLString.notset();
4767
5034
  }
4768
5035
  if (parts.length >= 2 && idPart0 === "var") {
4769
5036
  const varName = parts.slice(1).join(".");
@@ -4787,35 +5054,16 @@ class VCLCompiler {
4787
5054
  return context.obj.response ?? "";
4788
5055
  if (name === "req.url")
4789
5056
  return context.req.url;
4790
- if (name === "req.url.path") {
4791
- const url = context.req.url || "";
4792
- const qIdx = url.indexOf("?");
4793
- return qIdx >= 0 ? url.substring(0, qIdx) : url;
4794
- }
4795
- if (name === "req.url.qs") {
4796
- const url = context.req.url || "";
4797
- const qIdx = url.indexOf("?");
4798
- return qIdx >= 0 ? url.substring(qIdx + 1) : "";
4799
- }
4800
- if (name === "req.url.basename") {
4801
- const path = this.resolveVariable("req.url.path", context);
4802
- if (path === "")
4803
- return ".";
4804
- const lastSlash = path.lastIndexOf("/");
4805
- return lastSlash >= 0 ? path.substring(lastSlash + 1) : path;
4806
- }
4807
- if (name === "req.url.dirname") {
4808
- const path = this.resolveVariable("req.url.path", context);
4809
- if (path === "")
4810
- return ".";
4811
- const lastSlash = path.lastIndexOf("/");
4812
- return lastSlash >= 0 ? path.substring(0, lastSlash + 1) : "/";
4813
- }
4814
- if (name === "req.url.ext") {
4815
- const basename2 = this.resolveVariable("req.url.basename", context);
4816
- const dotIdx = basename2.lastIndexOf(".");
4817
- return dotIdx >= 0 ? basename2.substring(dotIdx + 1) : "";
4818
- }
5057
+ if (name === "req.url.path")
5058
+ return urlComponents(context.req.url).path;
5059
+ if (name === "req.url.qs")
5060
+ return urlComponents(context.req.url).qs;
5061
+ if (name === "req.url.basename")
5062
+ return urlComponents(context.req.url).basename;
5063
+ if (name === "req.url.dirname")
5064
+ return urlComponents(context.req.url).dirname;
5065
+ if (name === "req.url.ext")
5066
+ return urlComponents(context.req.url).ext;
4819
5067
  if (name === "req.method" || name === "req.request")
4820
5068
  return context.req.method;
4821
5069
  if (name === "req.backend")
@@ -4923,35 +5171,16 @@ class VCLCompiler {
4923
5171
  return context.bereq.method;
4924
5172
  if (name === "bereq.proto")
4925
5173
  return ctx.bereq?.proto || "HTTP/1.1";
4926
- if (name === "bereq.url.path") {
4927
- const url = context.bereq.url || "";
4928
- const qIdx = url.indexOf("?");
4929
- return qIdx >= 0 ? url.substring(0, qIdx) : url;
4930
- }
4931
- if (name === "bereq.url.qs") {
4932
- const url = context.bereq.url || "";
4933
- const qIdx = url.indexOf("?");
4934
- return qIdx >= 0 ? url.substring(qIdx + 1) : "";
4935
- }
4936
- if (name === "bereq.url.basename") {
4937
- const path = this.resolveVariable("bereq.url.path", context);
4938
- if (path === "")
4939
- return ".";
4940
- const lastSlash = path.lastIndexOf("/");
4941
- return lastSlash >= 0 ? path.substring(lastSlash + 1) : path;
4942
- }
4943
- if (name === "bereq.url.dirname") {
4944
- const path = this.resolveVariable("bereq.url.path", context);
4945
- if (path === "")
4946
- return ".";
4947
- const lastSlash = path.lastIndexOf("/");
4948
- return lastSlash >= 0 ? path.substring(0, lastSlash + 1) : "/";
4949
- }
4950
- if (name === "bereq.url.ext") {
4951
- const basename2 = this.resolveVariable("bereq.url.basename", context);
4952
- const dotIdx = basename2.lastIndexOf(".");
4953
- return dotIdx >= 0 ? basename2.substring(dotIdx + 1) : "";
4954
- }
5174
+ if (name === "bereq.url.path")
5175
+ return urlComponents(context.bereq.url).path;
5176
+ if (name === "bereq.url.qs")
5177
+ return urlComponents(context.bereq.url).qs;
5178
+ if (name === "bereq.url.basename")
5179
+ return urlComponents(context.bereq.url).basename;
5180
+ if (name === "bereq.url.dirname")
5181
+ return urlComponents(context.bereq.url).dirname;
5182
+ if (name === "bereq.url.ext")
5183
+ return urlComponents(context.bereq.url).ext;
4955
5184
  if (name === "bereq.headers")
4956
5185
  return serializeHeaders(context.bereq.http);
4957
5186
  if (name === "bereq.max_reuse_idle_time")
@@ -5524,13 +5753,20 @@ class VCLCompiler {
5524
5753
  }
5525
5754
  regexMatch(left, right, context, negate) {
5526
5755
  try {
5527
- const regex = right instanceof RegExp ? right : new RegExp(String(right));
5528
- const match = String(left).match(regex);
5756
+ const regex = right instanceof RegExp ? right : compileRegex(String(right));
5757
+ const match = regex.exec(toBytes(String(left)));
5758
+ context.re = undefined;
5529
5759
  if (match) {
5530
- const groups = {};
5760
+ const groups = Object.create(null);
5531
5761
  match.forEach((val, i) => {
5532
- groups[i] = val ?? "";
5762
+ if (val !== undefined)
5763
+ groups[i] = fromBytes(val);
5533
5764
  });
5765
+ for (const name in match.groups) {
5766
+ const val = match.groups[name];
5767
+ if (val !== undefined)
5768
+ groups[name] = fromBytes(val);
5769
+ }
5534
5770
  context.re = { groups };
5535
5771
  return !negate;
5536
5772
  }
@@ -8771,13 +9007,13 @@ function globToRegExp(pattern) {
8771
9007
  var MATCHER_CACHE_MAX = 1000;
8772
9008
  var GLOB_MATCHER_CACHE = new Map;
8773
9009
  var REGEX_MATCHER_CACHE = new Map;
8774
- function cached(cache, pattern, build) {
8775
- let fn = cache.get(pattern);
9010
+ function cached(cache2, pattern, build) {
9011
+ let fn = cache2.get(pattern);
8776
9012
  if (fn === undefined) {
8777
9013
  fn = build(pattern);
8778
- if (cache.size >= MATCHER_CACHE_MAX)
8779
- cache.clear();
8780
- cache.set(pattern, fn);
9014
+ if (cache2.size >= MATCHER_CACHE_MAX)
9015
+ cache2.clear();
9016
+ cache2.set(pattern, fn);
8781
9017
  }
8782
9018
  return fn;
8783
9019
  }
@@ -8790,30 +9026,11 @@ function globMatcher(pattern) {
8790
9026
  return re.test(name);
8791
9027
  };
8792
9028
  }
8793
- function pcreToRegExp(pattern) {
8794
- let p = String(pattern);
8795
- let flags = "";
8796
- for (;; ) {
8797
- const m = /^\(\?([a-zA-Z]+)\)/.exec(p);
8798
- if (!m)
8799
- break;
8800
- for (const ch of m[1]) {
8801
- if (ch === "i" || ch === "m" || ch === "s") {
8802
- if (!flags.includes(ch))
8803
- flags += ch;
8804
- } else {
8805
- throw new Error(`Unsupported inline regex flag: ${ch}`);
8806
- }
8807
- }
8808
- p = p.substring(m[0].length);
8809
- }
8810
- return new RegExp(p, `${flags}g`);
8811
- }
8812
9029
  function regexMatcher(pattern) {
8813
- const re = pcreToRegExp(pattern);
9030
+ const re = compileRegex(pattern, "g");
8814
9031
  return (name) => {
8815
9032
  re.lastIndex = 0;
8816
- for (const m of name.matchAll(re)) {
9033
+ for (const m of toBytes(name).matchAll(re)) {
8817
9034
  if (m[0].length > 0)
8818
9035
  return true;
8819
9036
  }
@@ -9256,7 +9473,7 @@ function createTableModule() {
9256
9473
  if (value === undefined)
9257
9474
  return null;
9258
9475
  try {
9259
- return new RegExp(String(value));
9476
+ return compileRegex(String(value));
9260
9477
  } catch {
9261
9478
  return null;
9262
9479
  }
@@ -9588,22 +9805,8 @@ function createVCLContext(platform = getPlatform()) {
9588
9805
  suffixof: (str, suffix) => String(str).endsWith(String(suffix)),
9589
9806
  replace: (str, search, replacement) => String(str).replace(String(search), String(replacement)),
9590
9807
  replaceall: (str, search, replacement) => String(str).split(String(search)).join(String(replacement)),
9591
- regsub: (str, regex, replacement) => {
9592
- try {
9593
- return String(str).replace(new RegExp(regex), replacement);
9594
- } catch (e) {
9595
- logError(`Invalid regex: ${regex}`, e);
9596
- return str;
9597
- }
9598
- },
9599
- regsuball: (str, regex, replacement) => {
9600
- try {
9601
- return String(str).replace(new RegExp(regex, "g"), replacement);
9602
- } catch (e) {
9603
- logError(`Invalid regex: ${regex}`, e);
9604
- return str;
9605
- }
9606
- },
9808
+ regsub,
9809
+ regsuball,
9607
9810
  integer: (value) => parseInt(String(value), 10) || 0,
9608
9811
  real: (value) => parseFloat(String(value)) || 0,
9609
9812
  math: {
@@ -10017,7 +10220,7 @@ Connection: close\r
10017
10220
  },
10018
10221
  lookup_regex: (tableName, key, defaultValue = "") => {
10019
10222
  const table = context.tables[tableName];
10020
- const defaultRegex = () => defaultValue ? new RegExp(defaultValue) : /(?:)/;
10223
+ const defaultRegex = () => defaultValue ? compileRegex(defaultValue) : /(?:)/;
10021
10224
  if (!table || !(key in table.entries))
10022
10225
  return defaultRegex();
10023
10226
  const value = table.entries[key];
@@ -10025,7 +10228,7 @@ Connection: close\r
10025
10228
  return value;
10026
10229
  if (typeof value === "string") {
10027
10230
  try {
10028
- return new RegExp(value);
10231
+ return compileRegex(value);
10029
10232
  } catch (e) {
10030
10233
  logError(`Invalid regex pattern: ${value}`, e);
10031
10234
  return defaultRegex();
@@ -10250,7 +10453,7 @@ function loadVCL(filePath) {
10250
10453
  var DEFAULT_TTL = 300;
10251
10454
  var DEFAULT_GRACE = 3600;
10252
10455
  var DEFAULT_STALE_WHILE_REVALIDATE = 10;
10253
- function toBytes(body) {
10456
+ function toBytes2(body) {
10254
10457
  if (typeof body === "string")
10255
10458
  return new TextEncoder().encode(body);
10256
10459
  if (body instanceof ArrayBuffer)
@@ -10260,13 +10463,51 @@ function toBytes(body) {
10260
10463
  function computeCacheKey(context) {
10261
10464
  return context.hashData && context.hashData.length > 0 ? context.hashData.join(":") : `${context.req.url}:${context.req.http.host || ""}`;
10262
10465
  }
10466
+ var DROPPED_ON_PASS = new Set([
10467
+ "alt-svc",
10468
+ "connection",
10469
+ "fastly-dsr-request",
10470
+ "fastly-shield-rp",
10471
+ "keep-alive",
10472
+ "te",
10473
+ "trailer",
10474
+ "upgrade"
10475
+ ]);
10476
+ var DROPPED_ON_POST_MISS = new Set([
10477
+ ...DROPPED_ON_PASS,
10478
+ "accept-ranges",
10479
+ "cache-control",
10480
+ "cdn-cache-control",
10481
+ "content-range",
10482
+ "fastly-cache-control",
10483
+ "proxy-authenticate",
10484
+ "proxy-authorization",
10485
+ "range"
10486
+ ]);
10487
+ var DROPPED_ON_MISS = new Set([
10488
+ ...DROPPED_ON_POST_MISS,
10489
+ "content-length",
10490
+ "if-modified-since",
10491
+ "if-none-match",
10492
+ "if-range",
10493
+ "transfer-encoding"
10494
+ ]);
10495
+ function initBackendRequest(context, mode) {
10496
+ const post = context.req.method === "POST";
10497
+ const dropped = mode === "pass" ? DROPPED_ON_PASS : post ? DROPPED_ON_POST_MISS : DROPPED_ON_MISS;
10498
+ context.bereq = {
10499
+ url: context.req.url,
10500
+ method: mode === "miss" && !post ? "GET" : context.req.method,
10501
+ http: Object.fromEntries(Object.entries(context.req.http).filter(([name]) => !dropped.has(name.toLowerCase())))
10502
+ };
10503
+ }
10263
10504
  function errorResult(context, key, restarts) {
10264
10505
  return {
10265
10506
  response: {
10266
10507
  status: context.obj.status || 500,
10267
10508
  statusText: "",
10268
10509
  headers: { ...context.obj.http },
10269
- body: toBytes(context.obj.response ?? "")
10510
+ body: toBytes2(context.obj.response ?? "")
10270
10511
  },
10271
10512
  action: "error",
10272
10513
  restarts,
@@ -10289,7 +10530,7 @@ async function runPipeline(opts) {
10289
10530
  }
10290
10531
  }
10291
10532
  async function runPass(opts) {
10292
- const { subroutines, context, cache, getBackendResponse } = opts;
10533
+ const { subroutines, context, cache: cache2, getBackendResponse } = opts;
10293
10534
  const now = () => context.platform.now();
10294
10535
  context.hashData = [];
10295
10536
  context.beresp.backend = undefined;
@@ -10323,7 +10564,7 @@ async function runPass(opts) {
10323
10564
  if (action === "lookup") {
10324
10565
  executeVCL(subroutines, "vcl_hash", context);
10325
10566
  key = computeCacheKey(context);
10326
- const cached2 = cache.get(key);
10567
+ const cached2 = cache2.get(key);
10327
10568
  if (cached2) {
10328
10569
  const at = now();
10329
10570
  const isFresh = at < cached2.expires;
@@ -10344,7 +10585,7 @@ async function runPass(opts) {
10344
10585
  return "restart";
10345
10586
  executeVCL(subroutines, "vcl_log", context);
10346
10587
  if (isStale)
10347
- cache.delete(key);
10588
+ cache2.delete(key);
10348
10589
  return {
10349
10590
  response: {
10350
10591
  status: context.resp.status,
@@ -10358,15 +10599,22 @@ async function runPass(opts) {
10358
10599
  };
10359
10600
  }
10360
10601
  } else {
10361
- cache.delete(key);
10602
+ cache2.delete(key);
10603
+ initBackendRequest(context, "miss");
10362
10604
  action = executeVCL(subroutines, "vcl_miss", context) || "fetch";
10363
10605
  }
10364
10606
  } else {
10607
+ initBackendRequest(context, "miss");
10365
10608
  action = executeVCL(subroutines, "vcl_miss", context) || "fetch";
10366
10609
  }
10367
- } else if (action === "pass") {
10610
+ }
10611
+ if (action === "pass") {
10612
+ key = "";
10613
+ initBackendRequest(context, "pass");
10368
10614
  action = executeVCL(subroutines, "vcl_pass", context) || "fetch";
10369
10615
  }
10616
+ if (action === "error")
10617
+ return errorResult(context, key, restarts);
10370
10618
  const passing = key === "";
10371
10619
  let backendResponse;
10372
10620
  try {
@@ -10411,7 +10659,7 @@ async function runPass(opts) {
10411
10659
  context.beresp.grace = DEFAULT_GRACE;
10412
10660
  context.beresp.stale_while_revalidate = DEFAULT_STALE_WHILE_REVALIDATE;
10413
10661
  }
10414
- const body = toBytes(backendResponse.body);
10662
+ const body = toBytes2(backendResponse.body);
10415
10663
  context.resp.status = context.beresp.status;
10416
10664
  context.resp.statusText = context.beresp.statusText;
10417
10665
  context.resp.http = { ...context.beresp.http };
@@ -10424,7 +10672,7 @@ async function runPass(opts) {
10424
10672
  const ttlMs = context.beresp.ttl * 1000;
10425
10673
  const graceMs = (context.beresp.grace || 0) * 1000;
10426
10674
  const swrMs = (context.beresp.stale_while_revalidate || 0) * 1000;
10427
- cache.set(key, {
10675
+ cache2.set(key, {
10428
10676
  resp: {
10429
10677
  status: context.resp.status,
10430
10678
  statusText: context.resp.statusText,