@pack/hydrogen 2.0.0-beta.2 → 2.0.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.
package/dist/index.js CHANGED
@@ -4,9 +4,16 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __getProtoOf = Object.getPrototypeOf;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
7
10
  var __commonJS = (cb, mod) => function __require() {
8
11
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
12
  };
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
10
17
  var __copyProps = (to, from, except, desc) => {
11
18
  if (from && typeof from === "object" || typeof from === "function") {
12
19
  for (let key of __getOwnPropNames(from))
@@ -23,6 +30,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
30
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
31
  mod
25
32
  ));
33
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
34
 
27
35
  // ../../node_modules/ua-parser-js/src/ua-parser.js
28
36
  var require_ua_parser = __commonJS({
@@ -1309,15 +1317,15 @@ var require_ua_parser = __commonJS({
1309
1317
  }
1310
1318
  });
1311
1319
 
1312
- // ../../node_modules/cookie/index.js
1320
+ // node_modules/cookie/index.js
1313
1321
  var require_cookie = __commonJS({
1314
- "../../node_modules/cookie/index.js"(exports) {
1322
+ "node_modules/cookie/index.js"(exports) {
1315
1323
  "use strict";
1316
- exports.parse = parse;
1317
- exports.serialize = serialize;
1324
+ exports.parse = parse2;
1325
+ exports.serialize = serialize2;
1318
1326
  var __toString = Object.prototype.toString;
1319
1327
  var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
1320
- function parse(str, options) {
1328
+ function parse2(str, options) {
1321
1329
  if (typeof str !== "string") {
1322
1330
  throw new TypeError("argument str must be a string");
1323
1331
  }
@@ -1349,7 +1357,7 @@ var require_cookie = __commonJS({
1349
1357
  }
1350
1358
  return obj;
1351
1359
  }
1352
- function serialize(name, val, options) {
1360
+ function serialize2(name, val, options) {
1353
1361
  var opt = options || {};
1354
1362
  var enc = opt.encode || encode;
1355
1363
  if (typeof enc !== "function") {
@@ -1454,147 +1462,3020 @@ var require_cookie = __commonJS({
1454
1462
  }
1455
1463
  });
1456
1464
 
1457
- // ../packlytics/dist/utils/get-packlytics-id.js
1458
- function sha256(ascii) {
1459
- function rightRotate(value, amount) {
1460
- return value >>> amount | value << 32 - amount;
1461
- }
1462
- const mathPow = Math.pow;
1463
- const maxWord = mathPow(2, 32);
1464
- const lengthProperty = "length";
1465
- let i, j;
1466
- let result = "";
1467
- const words = [];
1468
- const asciiBitLength = ascii[lengthProperty] * 8;
1469
- let hash = sha256.h = sha256.h || [];
1470
- const k = sha256.k = sha256.k || [];
1471
- let primeCounter = k[lengthProperty];
1472
- const isComposite = {};
1473
- for (let candidate = 2; primeCounter < 64; candidate++) {
1474
- if (!isComposite[candidate]) {
1475
- for (i = 0; i < 313; i += candidate) {
1476
- isComposite[i] = candidate;
1465
+ // ../../node_modules/ms/index.js
1466
+ var require_ms = __commonJS({
1467
+ "../../node_modules/ms/index.js"(exports, module) {
1468
+ "use strict";
1469
+ var s = 1e3;
1470
+ var m = s * 60;
1471
+ var h = m * 60;
1472
+ var d = h * 24;
1473
+ var w = d * 7;
1474
+ var y = d * 365.25;
1475
+ module.exports = function(val, options) {
1476
+ options = options || {};
1477
+ var type = typeof val;
1478
+ if (type === "string" && val.length > 0) {
1479
+ return parse2(val);
1480
+ } else if (type === "number" && isFinite(val)) {
1481
+ return options.long ? fmtLong(val) : fmtShort(val);
1477
1482
  }
1478
- hash[primeCounter] = mathPow(candidate, 0.5) * maxWord | 0;
1479
- k[primeCounter++] = mathPow(candidate, 1 / 3) * maxWord | 0;
1483
+ throw new Error(
1484
+ "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
1485
+ );
1486
+ };
1487
+ function parse2(str) {
1488
+ str = String(str);
1489
+ if (str.length > 100) {
1490
+ return;
1491
+ }
1492
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
1493
+ str
1494
+ );
1495
+ if (!match) {
1496
+ return;
1497
+ }
1498
+ var n = parseFloat(match[1]);
1499
+ var type = (match[2] || "ms").toLowerCase();
1500
+ switch (type) {
1501
+ case "years":
1502
+ case "year":
1503
+ case "yrs":
1504
+ case "yr":
1505
+ case "y":
1506
+ return n * y;
1507
+ case "weeks":
1508
+ case "week":
1509
+ case "w":
1510
+ return n * w;
1511
+ case "days":
1512
+ case "day":
1513
+ case "d":
1514
+ return n * d;
1515
+ case "hours":
1516
+ case "hour":
1517
+ case "hrs":
1518
+ case "hr":
1519
+ case "h":
1520
+ return n * h;
1521
+ case "minutes":
1522
+ case "minute":
1523
+ case "mins":
1524
+ case "min":
1525
+ case "m":
1526
+ return n * m;
1527
+ case "seconds":
1528
+ case "second":
1529
+ case "secs":
1530
+ case "sec":
1531
+ case "s":
1532
+ return n * s;
1533
+ case "milliseconds":
1534
+ case "millisecond":
1535
+ case "msecs":
1536
+ case "msec":
1537
+ case "ms":
1538
+ return n;
1539
+ default:
1540
+ return void 0;
1541
+ }
1542
+ }
1543
+ function fmtShort(ms) {
1544
+ var msAbs = Math.abs(ms);
1545
+ if (msAbs >= d) {
1546
+ return Math.round(ms / d) + "d";
1547
+ }
1548
+ if (msAbs >= h) {
1549
+ return Math.round(ms / h) + "h";
1550
+ }
1551
+ if (msAbs >= m) {
1552
+ return Math.round(ms / m) + "m";
1553
+ }
1554
+ if (msAbs >= s) {
1555
+ return Math.round(ms / s) + "s";
1556
+ }
1557
+ return ms + "ms";
1558
+ }
1559
+ function fmtLong(ms) {
1560
+ var msAbs = Math.abs(ms);
1561
+ if (msAbs >= d) {
1562
+ return plural(ms, msAbs, d, "day");
1563
+ }
1564
+ if (msAbs >= h) {
1565
+ return plural(ms, msAbs, h, "hour");
1566
+ }
1567
+ if (msAbs >= m) {
1568
+ return plural(ms, msAbs, m, "minute");
1569
+ }
1570
+ if (msAbs >= s) {
1571
+ return plural(ms, msAbs, s, "second");
1572
+ }
1573
+ return ms + " ms";
1574
+ }
1575
+ function plural(ms, msAbs, n, name) {
1576
+ var isPlural = msAbs >= n * 1.5;
1577
+ return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
1480
1578
  }
1481
1579
  }
1482
- ascii += "\x80";
1483
- while (ascii[lengthProperty] % 64 - 56)
1484
- ascii += "\0";
1485
- for (i = 0; i < ascii[lengthProperty]; i++) {
1486
- j = ascii.charCodeAt(i);
1487
- if (j >> 8)
1488
- return;
1489
- words[i >> 2] |= j << (3 - i) % 4 * 8;
1580
+ });
1581
+
1582
+ // ../../node_modules/debug/src/common.js
1583
+ var require_common = __commonJS({
1584
+ "../../node_modules/debug/src/common.js"(exports, module) {
1585
+ "use strict";
1586
+ function setup(env) {
1587
+ createDebug5.debug = createDebug5;
1588
+ createDebug5.default = createDebug5;
1589
+ createDebug5.coerce = coerce;
1590
+ createDebug5.disable = disable;
1591
+ createDebug5.enable = enable;
1592
+ createDebug5.enabled = enabled;
1593
+ createDebug5.humanize = require_ms();
1594
+ createDebug5.destroy = destroy;
1595
+ Object.keys(env).forEach((key) => {
1596
+ createDebug5[key] = env[key];
1597
+ });
1598
+ createDebug5.names = [];
1599
+ createDebug5.skips = [];
1600
+ createDebug5.formatters = {};
1601
+ function selectColor(namespace) {
1602
+ let hash2 = 0;
1603
+ for (let i = 0; i < namespace.length; i++) {
1604
+ hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i);
1605
+ hash2 |= 0;
1606
+ }
1607
+ return createDebug5.colors[Math.abs(hash2) % createDebug5.colors.length];
1608
+ }
1609
+ createDebug5.selectColor = selectColor;
1610
+ function createDebug5(namespace) {
1611
+ let prevTime;
1612
+ let enableOverride = null;
1613
+ let namespacesCache;
1614
+ let enabledCache;
1615
+ function debug5(...args) {
1616
+ if (!debug5.enabled) {
1617
+ return;
1618
+ }
1619
+ const self2 = debug5;
1620
+ const curr = Number(/* @__PURE__ */ new Date());
1621
+ const ms = curr - (prevTime || curr);
1622
+ self2.diff = ms;
1623
+ self2.prev = prevTime;
1624
+ self2.curr = curr;
1625
+ prevTime = curr;
1626
+ args[0] = createDebug5.coerce(args[0]);
1627
+ if (typeof args[0] !== "string") {
1628
+ args.unshift("%O");
1629
+ }
1630
+ let index = 0;
1631
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
1632
+ if (match === "%%") {
1633
+ return "%";
1634
+ }
1635
+ index++;
1636
+ const formatter = createDebug5.formatters[format];
1637
+ if (typeof formatter === "function") {
1638
+ const val = args[index];
1639
+ match = formatter.call(self2, val);
1640
+ args.splice(index, 1);
1641
+ index--;
1642
+ }
1643
+ return match;
1644
+ });
1645
+ createDebug5.formatArgs.call(self2, args);
1646
+ const logFn = self2.log || createDebug5.log;
1647
+ logFn.apply(self2, args);
1648
+ }
1649
+ debug5.namespace = namespace;
1650
+ debug5.useColors = createDebug5.useColors();
1651
+ debug5.color = createDebug5.selectColor(namespace);
1652
+ debug5.extend = extend;
1653
+ debug5.destroy = createDebug5.destroy;
1654
+ Object.defineProperty(debug5, "enabled", {
1655
+ enumerable: true,
1656
+ configurable: false,
1657
+ get: () => {
1658
+ if (enableOverride !== null) {
1659
+ return enableOverride;
1660
+ }
1661
+ if (namespacesCache !== createDebug5.namespaces) {
1662
+ namespacesCache = createDebug5.namespaces;
1663
+ enabledCache = createDebug5.enabled(namespace);
1664
+ }
1665
+ return enabledCache;
1666
+ },
1667
+ set: (v) => {
1668
+ enableOverride = v;
1669
+ }
1670
+ });
1671
+ if (typeof createDebug5.init === "function") {
1672
+ createDebug5.init(debug5);
1673
+ }
1674
+ return debug5;
1675
+ }
1676
+ function extend(namespace, delimiter) {
1677
+ const newDebug = createDebug5(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
1678
+ newDebug.log = this.log;
1679
+ return newDebug;
1680
+ }
1681
+ function enable(namespaces) {
1682
+ createDebug5.save(namespaces);
1683
+ createDebug5.namespaces = namespaces;
1684
+ createDebug5.names = [];
1685
+ createDebug5.skips = [];
1686
+ const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
1687
+ for (const ns of split) {
1688
+ if (ns[0] === "-") {
1689
+ createDebug5.skips.push(ns.slice(1));
1690
+ } else {
1691
+ createDebug5.names.push(ns);
1692
+ }
1693
+ }
1694
+ }
1695
+ function matchesTemplate(search, template) {
1696
+ let searchIndex = 0;
1697
+ let templateIndex = 0;
1698
+ let starIndex = -1;
1699
+ let matchIndex = 0;
1700
+ while (searchIndex < search.length) {
1701
+ if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
1702
+ if (template[templateIndex] === "*") {
1703
+ starIndex = templateIndex;
1704
+ matchIndex = searchIndex;
1705
+ templateIndex++;
1706
+ } else {
1707
+ searchIndex++;
1708
+ templateIndex++;
1709
+ }
1710
+ } else if (starIndex !== -1) {
1711
+ templateIndex = starIndex + 1;
1712
+ matchIndex++;
1713
+ searchIndex = matchIndex;
1714
+ } else {
1715
+ return false;
1716
+ }
1717
+ }
1718
+ while (templateIndex < template.length && template[templateIndex] === "*") {
1719
+ templateIndex++;
1720
+ }
1721
+ return templateIndex === template.length;
1722
+ }
1723
+ function disable() {
1724
+ const namespaces = [
1725
+ ...createDebug5.names,
1726
+ ...createDebug5.skips.map((namespace) => "-" + namespace)
1727
+ ].join(",");
1728
+ createDebug5.enable("");
1729
+ return namespaces;
1730
+ }
1731
+ function enabled(name) {
1732
+ for (const skip of createDebug5.skips) {
1733
+ if (matchesTemplate(name, skip)) {
1734
+ return false;
1735
+ }
1736
+ }
1737
+ for (const ns of createDebug5.names) {
1738
+ if (matchesTemplate(name, ns)) {
1739
+ return true;
1740
+ }
1741
+ }
1742
+ return false;
1743
+ }
1744
+ function coerce(val) {
1745
+ if (val instanceof Error) {
1746
+ return val.stack || val.message;
1747
+ }
1748
+ return val;
1749
+ }
1750
+ function destroy() {
1751
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
1752
+ }
1753
+ createDebug5.enable(createDebug5.load());
1754
+ return createDebug5;
1755
+ }
1756
+ module.exports = setup;
1490
1757
  }
1491
- words[words[lengthProperty]] = asciiBitLength / maxWord | 0;
1492
- words[words[lengthProperty]] = asciiBitLength;
1493
- for (j = 0; j < words[lengthProperty]; ) {
1494
- const w = words.slice(j, j += 16);
1495
- const oldHash = hash;
1496
- hash = hash.slice(0, 8);
1497
- for (i = 0; i < 64; i++) {
1498
- const i2 = i + j;
1499
- const w15 = w[i - 15], w2 = w[i - 2];
1500
- const a = hash[0], e = hash[4];
1501
- const temp1 = hash[7] + (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) + // S1
1502
- (e & hash[5] ^ ~e & hash[6]) + // ch
1503
- k[i] + // Expand the message schedule if needed
1504
- (w[i] = i < 16 ? w[i] : w[i - 16] + (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ w15 >>> 3) + // s0
1505
- w[i - 7] + (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ w2 >>> 10) | // s1
1506
- 0);
1507
- const temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) + // S0
1508
- (a & hash[1] ^ a & hash[2] ^ hash[1] & hash[2]);
1509
- hash = [temp1 + temp2 | 0].concat(hash);
1510
- hash[4] = hash[4] + temp1 | 0;
1758
+ });
1759
+
1760
+ // ../../node_modules/debug/src/browser.js
1761
+ var require_browser = __commonJS({
1762
+ "../../node_modules/debug/src/browser.js"(exports, module) {
1763
+ "use strict";
1764
+ exports.formatArgs = formatArgs;
1765
+ exports.save = save;
1766
+ exports.load = load;
1767
+ exports.useColors = useColors;
1768
+ exports.storage = localstorage();
1769
+ exports.destroy = /* @__PURE__ */ (() => {
1770
+ let warned = false;
1771
+ return () => {
1772
+ if (!warned) {
1773
+ warned = true;
1774
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
1775
+ }
1776
+ };
1777
+ })();
1778
+ exports.colors = [
1779
+ "#0000CC",
1780
+ "#0000FF",
1781
+ "#0033CC",
1782
+ "#0033FF",
1783
+ "#0066CC",
1784
+ "#0066FF",
1785
+ "#0099CC",
1786
+ "#0099FF",
1787
+ "#00CC00",
1788
+ "#00CC33",
1789
+ "#00CC66",
1790
+ "#00CC99",
1791
+ "#00CCCC",
1792
+ "#00CCFF",
1793
+ "#3300CC",
1794
+ "#3300FF",
1795
+ "#3333CC",
1796
+ "#3333FF",
1797
+ "#3366CC",
1798
+ "#3366FF",
1799
+ "#3399CC",
1800
+ "#3399FF",
1801
+ "#33CC00",
1802
+ "#33CC33",
1803
+ "#33CC66",
1804
+ "#33CC99",
1805
+ "#33CCCC",
1806
+ "#33CCFF",
1807
+ "#6600CC",
1808
+ "#6600FF",
1809
+ "#6633CC",
1810
+ "#6633FF",
1811
+ "#66CC00",
1812
+ "#66CC33",
1813
+ "#9900CC",
1814
+ "#9900FF",
1815
+ "#9933CC",
1816
+ "#9933FF",
1817
+ "#99CC00",
1818
+ "#99CC33",
1819
+ "#CC0000",
1820
+ "#CC0033",
1821
+ "#CC0066",
1822
+ "#CC0099",
1823
+ "#CC00CC",
1824
+ "#CC00FF",
1825
+ "#CC3300",
1826
+ "#CC3333",
1827
+ "#CC3366",
1828
+ "#CC3399",
1829
+ "#CC33CC",
1830
+ "#CC33FF",
1831
+ "#CC6600",
1832
+ "#CC6633",
1833
+ "#CC9900",
1834
+ "#CC9933",
1835
+ "#CCCC00",
1836
+ "#CCCC33",
1837
+ "#FF0000",
1838
+ "#FF0033",
1839
+ "#FF0066",
1840
+ "#FF0099",
1841
+ "#FF00CC",
1842
+ "#FF00FF",
1843
+ "#FF3300",
1844
+ "#FF3333",
1845
+ "#FF3366",
1846
+ "#FF3399",
1847
+ "#FF33CC",
1848
+ "#FF33FF",
1849
+ "#FF6600",
1850
+ "#FF6633",
1851
+ "#FF9900",
1852
+ "#FF9933",
1853
+ "#FFCC00",
1854
+ "#FFCC33"
1855
+ ];
1856
+ function useColors() {
1857
+ if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
1858
+ return true;
1859
+ }
1860
+ if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
1861
+ return false;
1862
+ }
1863
+ let m;
1864
+ return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
1865
+ typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
1866
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
1867
+ typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
1868
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
1511
1869
  }
1512
- for (i = 0; i < 8; i++) {
1513
- hash[i] = hash[i] + oldHash[i] | 0;
1870
+ function formatArgs(args) {
1871
+ args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
1872
+ if (!this.useColors) {
1873
+ return;
1874
+ }
1875
+ const c = "color: " + this.color;
1876
+ args.splice(1, 0, c, "color: inherit");
1877
+ let index = 0;
1878
+ let lastC = 0;
1879
+ args[0].replace(/%[a-zA-Z%]/g, (match) => {
1880
+ if (match === "%%") {
1881
+ return;
1882
+ }
1883
+ index++;
1884
+ if (match === "%c") {
1885
+ lastC = index;
1886
+ }
1887
+ });
1888
+ args.splice(lastC, 0, c);
1889
+ }
1890
+ exports.log = console.debug || console.log || (() => {
1891
+ });
1892
+ function save(namespaces) {
1893
+ try {
1894
+ if (namespaces) {
1895
+ exports.storage.setItem("debug", namespaces);
1896
+ } else {
1897
+ exports.storage.removeItem("debug");
1898
+ }
1899
+ } catch (error) {
1900
+ }
1901
+ }
1902
+ function load() {
1903
+ let r;
1904
+ try {
1905
+ r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
1906
+ } catch (error) {
1907
+ }
1908
+ if (!r && typeof process !== "undefined" && "env" in process) {
1909
+ r = process.env.DEBUG;
1910
+ }
1911
+ return r;
1912
+ }
1913
+ function localstorage() {
1914
+ try {
1915
+ return localStorage;
1916
+ } catch (error) {
1917
+ }
1514
1918
  }
1919
+ module.exports = require_common()(exports);
1920
+ var { formatters } = module.exports;
1921
+ formatters.j = function(v) {
1922
+ try {
1923
+ return JSON.stringify(v);
1924
+ } catch (error) {
1925
+ return "[UnexpectedJSONParseError]: " + error.message;
1926
+ }
1927
+ };
1515
1928
  }
1516
- for (i = 0; i < 8; i++) {
1517
- for (j = 3; j + 1; j--) {
1518
- const b = hash[i] >> j * 8 & 255;
1519
- result += (b < 16 ? 0 : "") + b.toString(16);
1929
+ });
1930
+
1931
+ // ../../node_modules/curriable/dist/curriable.js
1932
+ var require_curriable = __commonJS({
1933
+ "../../node_modules/curriable/dist/curriable.js"(exports, module) {
1934
+ "use strict";
1935
+ (function(global, factory) {
1936
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = global || self, factory(global.curriable = {}));
1937
+ })(exports, function(exports2) {
1938
+ "use strict";
1939
+ var __ = typeof Symbol === "function" ? Symbol("curriable placeholder") : 60881;
1940
+ function getCurried(fn, arity) {
1941
+ function _curried(args) {
1942
+ return function() {
1943
+ var length = args.length;
1944
+ var newArgs = arguments;
1945
+ var newArgsLength = newArgs.length;
1946
+ var combined = [];
1947
+ var newArgsIndex = 0;
1948
+ var remaining = arity;
1949
+ var value;
1950
+ if (length) {
1951
+ var index = -1;
1952
+ while (++index < length) {
1953
+ combined[index] = value = args[index] === __ && newArgsIndex < newArgsLength ? newArgs[newArgsIndex++] : args[index];
1954
+ if (value !== __) {
1955
+ --remaining;
1956
+ }
1957
+ }
1958
+ }
1959
+ if (newArgsIndex < newArgsLength) {
1960
+ while (newArgsIndex < newArgsLength) {
1961
+ combined[combined.length] = value = newArgs[newArgsIndex];
1962
+ if (value !== __ && newArgsIndex < arity) {
1963
+ --remaining;
1964
+ }
1965
+ ++newArgsIndex;
1966
+ }
1967
+ }
1968
+ return remaining > 0 ? _curried(combined) : fn.apply(this, combined);
1969
+ };
1970
+ }
1971
+ return _curried([]);
1972
+ }
1973
+ function curry2(fn, arityOverride) {
1974
+ var arity = typeof arityOverride === "number" ? arityOverride : fn.length;
1975
+ var curried = getCurried(fn, arity);
1976
+ curried.arity = arity;
1977
+ curried.fn = fn;
1978
+ return curried;
1979
+ }
1980
+ curry2.__ = __;
1981
+ function isPlaceholder(value) {
1982
+ return value === __;
1983
+ }
1984
+ curry2.isPlaceholder = isPlaceholder;
1985
+ function uncurry(curried) {
1986
+ return curried.fn;
1987
+ }
1988
+ curry2.uncurry = uncurry;
1989
+ exports2.__ = __;
1990
+ exports2.curry = curry2;
1991
+ exports2.default = curry2;
1992
+ exports2.isPlaceholder = isPlaceholder;
1993
+ exports2.uncurry = uncurry;
1994
+ Object.defineProperty(exports2, "__esModule", { value: true });
1995
+ });
1996
+ }
1997
+ });
1998
+
1999
+ // ../../node_modules/hash-it/es/constants.js
2000
+ var _SELF_TAGS, _TOSTRING_TAGS, _TYPEDARRAY_TAGS, _UNPARSEABLE_TAGS, HAS_BUFFER_FROM_SUPPORT, HAS_UINT16ARRAY_SUPPORT, HTML_ELEMENT_REGEXP, SVG_ELEMENT_REGEXP, OBJECT_CLASSES, OBJECT_CLASS_MAP, OBJECT_CLASS_TYPE_MAP, ITERABLE_TAGS, PRIMITIVE_TAGS, SELF_TAGS, TOSTRING_TAGS, TYPEDARRAY_TAGS, UNPARSEABLE_TAGS;
2001
+ var init_constants = __esm({
2002
+ "../../node_modules/hash-it/es/constants.js"() {
2003
+ "use strict";
2004
+ HAS_BUFFER_FROM_SUPPORT = typeof Buffer !== "undefined" && typeof Buffer.from === "function";
2005
+ HAS_UINT16ARRAY_SUPPORT = typeof Uint16Array === "function";
2006
+ HTML_ELEMENT_REGEXP = /\[object (HTML(.*)Element)\]/;
2007
+ SVG_ELEMENT_REGEXP = /\[object (SVG(.*)Element)\]/;
2008
+ OBJECT_CLASSES = ["Arguments", "Array", "ArrayBuffer", "Boolean", "DataView", "Date", "DocumentFragment", "Error", "Event", "Float32Array", "Float64Array", "Function", "Generator", "GeneratorFunction", "HTMLElement", "Int8Array", "Int16Array", "Int32Array", "Map", "Null", "Number", "Object", "Promise", "RegExp", "Set", "String", "Symbol", "Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "Undefined", "WeakMap", "WeakSet", "Window"];
2009
+ OBJECT_CLASS_MAP = OBJECT_CLASSES.reduce(function(objectClasses, type) {
2010
+ objectClasses["[object " + type + "]"] = type;
2011
+ return objectClasses;
2012
+ }, {});
2013
+ OBJECT_CLASS_TYPE_MAP = Object.keys(OBJECT_CLASS_MAP).reduce(function(objectClassTypes, objectClass) {
2014
+ objectClassTypes[OBJECT_CLASS_MAP[objectClass].toUpperCase()] = objectClass;
2015
+ return objectClassTypes;
2016
+ }, {});
2017
+ ITERABLE_TAGS = {
2018
+ "[object Map]": true,
2019
+ "[object Set]": true
2020
+ };
2021
+ PRIMITIVE_TAGS = {
2022
+ boolean: true,
2023
+ function: true,
2024
+ number: true,
2025
+ string: true,
2026
+ undefined: true
2027
+ };
2028
+ SELF_TAGS = (_SELF_TAGS = {}, _SELF_TAGS[OBJECT_CLASS_TYPE_MAP.ARGUMENTS] = true, _SELF_TAGS[OBJECT_CLASS_TYPE_MAP.ARRAY] = true, _SELF_TAGS);
2029
+ TOSTRING_TAGS = (_TOSTRING_TAGS = {}, _TOSTRING_TAGS[OBJECT_CLASS_TYPE_MAP.REGEXP] = true, _TOSTRING_TAGS[OBJECT_CLASS_TYPE_MAP.SYMBOL] = true, _TOSTRING_TAGS);
2030
+ TYPEDARRAY_TAGS = (_TYPEDARRAY_TAGS = {}, _TYPEDARRAY_TAGS[OBJECT_CLASS_TYPE_MAP.FLOAT32ARRAY] = true, _TYPEDARRAY_TAGS[OBJECT_CLASS_TYPE_MAP.FLOAT64ARRAY] = true, _TYPEDARRAY_TAGS[OBJECT_CLASS_TYPE_MAP.INT8ARRAY] = true, _TYPEDARRAY_TAGS[OBJECT_CLASS_TYPE_MAP.INT16ARRAY] = true, _TYPEDARRAY_TAGS[OBJECT_CLASS_TYPE_MAP.INT32ARRAY] = true, _TYPEDARRAY_TAGS[OBJECT_CLASS_TYPE_MAP.UINT8ARRAY] = true, _TYPEDARRAY_TAGS[OBJECT_CLASS_TYPE_MAP.UINT8CLAMPEDARRAY] = true, _TYPEDARRAY_TAGS[OBJECT_CLASS_TYPE_MAP.UINT16ARRAY] = true, _TYPEDARRAY_TAGS[OBJECT_CLASS_TYPE_MAP.UINT32ARRAY] = true, _TYPEDARRAY_TAGS);
2031
+ UNPARSEABLE_TAGS = (_UNPARSEABLE_TAGS = {}, _UNPARSEABLE_TAGS[OBJECT_CLASS_TYPE_MAP.GENERATOR] = true, _UNPARSEABLE_TAGS[OBJECT_CLASS_TYPE_MAP.PROMISE] = true, _UNPARSEABLE_TAGS[OBJECT_CLASS_TYPE_MAP.WEAKMAP] = true, _UNPARSEABLE_TAGS[OBJECT_CLASS_TYPE_MAP.WEAKSET] = true, _UNPARSEABLE_TAGS);
2032
+ }
2033
+ });
2034
+
2035
+ // ../../node_modules/hash-it/es/utils.js
2036
+ function getFunctionName(fn) {
2037
+ return fn.name || (fn.toString().match(FUNCTION_NAME_REGEX) || [])[1] || "anonymous";
2038
+ }
2039
+ function getIntegerHashValue(string) {
2040
+ var index = string.length, hashA = 5381, hashB = 52711, charCode;
2041
+ while (index--) {
2042
+ charCode = string.charCodeAt(index);
2043
+ hashA = hashA * 33 ^ charCode;
2044
+ hashB = hashB * 33 ^ charCode;
2045
+ }
2046
+ return (hashA >>> 0) * 4096 + (hashB >>> 0);
2047
+ }
2048
+ function getSortedEvent(event) {
2049
+ return {
2050
+ bubbles: event.bubbles,
2051
+ cancelBubble: event.cancelBubble,
2052
+ cancelable: event.cancelable,
2053
+ composed: event.composed,
2054
+ currentTarget: event.currentTarget,
2055
+ defaultPrevented: event.defaultPrevented,
2056
+ eventPhase: event.eventPhase,
2057
+ isTrusted: event.isTrusted,
2058
+ returnValue: event.returnValue,
2059
+ target: event.target,
2060
+ type: event.type
2061
+ };
2062
+ }
2063
+ function shouldSort(valueA, valueB) {
2064
+ return valueA > valueB;
2065
+ }
2066
+ function shouldSortPair(pairA, pairB) {
2067
+ return pairA[0] > pairB[0];
2068
+ }
2069
+ function sort(array, fn) {
2070
+ var subIndex, value;
2071
+ for (var index = 0; index < array.length; ++index) {
2072
+ value = array[index];
2073
+ for (subIndex = index - 1; ~subIndex && fn(array[subIndex], value); --subIndex) {
2074
+ array[subIndex + 1] = array[subIndex];
1520
2075
  }
2076
+ array[subIndex + 1] = value;
1521
2077
  }
1522
- return result;
2078
+ return array;
1523
2079
  }
1524
- function createHash(data) {
1525
- const hash = sha256(data);
1526
- return [
1527
- hash?.substring(0, 8),
1528
- hash?.substring(8, 12),
1529
- hash?.substring(12, 16),
1530
- hash?.substring(16, 20),
1531
- hash?.substring(20, 32)
1532
- ].join("-");
2080
+ function getSortedIterable(iterable, cache, keys2) {
2081
+ var isMap = typeof iterable.get === "function";
2082
+ var entries = [];
2083
+ if (isMap) {
2084
+ iterable.forEach(function(value, key) {
2085
+ entries.push([
2086
+ // eslint-disable-next-line no-use-before-define
2087
+ stringify(key, cache, keys2),
2088
+ // eslint-disable-next-line no-use-before-define
2089
+ stringify(value, cache, keys2)
2090
+ ]);
2091
+ });
2092
+ sort(entries, shouldSortPair);
2093
+ } else {
2094
+ iterable.forEach(function(value) {
2095
+ entries.push(stringify(value, cache, keys2));
2096
+ });
2097
+ sort(entries, shouldSort);
2098
+ }
2099
+ var _final = getFunctionName(iterable.constructor) + "|[";
2100
+ for (var index = 0, length = entries.length, entry; index < length; ++index) {
2101
+ entry = entries[index];
2102
+ _final += (index ? "," : "") + (isMap ? "[" + entry[0] + "," + entry[1] + "]" : entry);
2103
+ }
2104
+ return _final + "]";
1533
2105
  }
1534
- function getPacklyticsId(data, secret) {
1535
- const currentDate = /* @__PURE__ */ new Date();
1536
- const formattedDate = currentDate.toLocaleDateString("en-US");
1537
- const salt = sha256(formattedDate + secret);
1538
- return createHash(data + salt);
2106
+ function getSortedObject(object) {
2107
+ var objectKeys = sort(keys(object), shouldSort);
2108
+ var newObject = {};
2109
+ var key;
2110
+ for (var index = 0; index < objectKeys.length; ++index) {
2111
+ key = objectKeys[index];
2112
+ newObject[key] = object[key];
2113
+ }
2114
+ return newObject;
1539
2115
  }
1540
-
1541
- // ../../node_modules/intl-parse-accept-language/dist/intl-parse-accept-language.esm.js
1542
- var defaultValidate = function defaultValidate2(locale) {
1543
- return locale;
1544
- };
1545
- var parseAcceptLanguage = function parseAcceptLanguage2(languageHeaderValue, options) {
1546
- if (options === void 0) {
1547
- options = {};
2116
+ function getStringifiedArrayBufferFallback(buffer) {
2117
+ return String.fromCharCode.apply(null, new Uint16Array(buffer));
2118
+ }
2119
+ function getStringifiedArrayBufferModern(buffer) {
2120
+ return Buffer.from(buffer).toString("utf8");
2121
+ }
2122
+ function getStringifiedArrayBufferNoSupport() {
2123
+ return "";
2124
+ }
2125
+ function getStringifiedDocumentFragment(fragment) {
2126
+ var children = fragment.children;
2127
+ var innerHTML = "";
2128
+ for (var index = 0; index < children.length; ++index) {
2129
+ innerHTML += children[index].outerHTML;
1548
2130
  }
1549
- if (!languageHeaderValue) return [];
1550
- var _options = options, _options$ignoreWildca = _options.ignoreWildcard, ignoreWildcard = _options$ignoreWildca === void 0 ? true : _options$ignoreWildca, _options$validate = _options.validate, validate = _options$validate === void 0 ? defaultValidate : _options$validate;
1551
- return languageHeaderValue.split(",").map(function(lang) {
1552
- var _lang$split = lang.split(";"), locale = _lang$split[0], _lang$split$ = _lang$split[1], q = _lang$split$ === void 0 ? "q=1" : _lang$split$;
1553
- var trimmedLocale = locale.trim();
1554
- var numQ = Number(q.replace(/q ?=/, ""));
1555
- if (isNaN(numQ)) return [0, trimmedLocale];
1556
- return [numQ, trimmedLocale];
1557
- }).sort(function(_ref, _ref2) {
1558
- var q1 = _ref[0];
1559
- var q2 = _ref2[0];
1560
- return q2 - q1;
1561
- }).flatMap(function(_ref3) {
1562
- var locale = _ref3[1];
1563
- if (locale === "*" && ignoreWildcard) return [];
1564
- try {
1565
- return validate(locale) || [];
1566
- } catch (_unused) {
1567
- return [];
2131
+ return innerHTML;
2132
+ }
2133
+ function getCutoffIndex(array, value) {
2134
+ for (var index = 0; index < array.length; ++index) {
2135
+ if (array[index] === value) {
2136
+ return index + 1;
1568
2137
  }
1569
- });
1570
- };
1571
-
1572
- // ../packlytics/dist/utils/get-headers.js
1573
- function getHeaders(requestOrHeaders) {
1574
- if (requestOrHeaders instanceof Request) {
1575
- return requestOrHeaders.headers;
1576
2138
  }
1577
- return requestOrHeaders;
2139
+ return 0;
1578
2140
  }
1579
-
1580
- // ../packlytics/dist/utils/get-client-locales.js
1581
- function getClientLocales(requestOrHeaders) {
1582
- let headers = getHeaders(requestOrHeaders);
1583
- let acceptLanguage = headers.get("Accept-Language");
1584
- if (!acceptLanguage)
1585
- return void 0;
1586
- let locales = parseAcceptLanguage(acceptLanguage, {
1587
- validate: Intl.DateTimeFormat.supportedLocalesOf,
1588
- ignoreWildcard: true
1589
- });
1590
- if (locales.length === 0)
1591
- return void 0;
1592
- return locales;
2141
+ function getNormalizedValue(value, cache, keys2, passedTag) {
2142
+ if (passedTag === void 0) {
2143
+ var type = typeof value;
2144
+ if (type === "string" || PRIMITIVE_TAGS[type]) {
2145
+ return type + "|" + value;
2146
+ }
2147
+ if (value === null) {
2148
+ return "null|" + value;
2149
+ }
2150
+ }
2151
+ var tag = passedTag || toString.call(value);
2152
+ if (SELF_TAGS[tag]) {
2153
+ return value;
2154
+ }
2155
+ if (tag === OBJECT_CLASS_TYPE_MAP.OBJECT) {
2156
+ return getSortedObject(value);
2157
+ }
2158
+ if (TOSTRING_TAGS[tag]) {
2159
+ return OBJECT_CLASS_MAP[tag] + "|" + value.toString();
2160
+ }
2161
+ if (ITERABLE_TAGS[tag]) {
2162
+ return getSortedIterable(value, cache, keys2);
2163
+ }
2164
+ if (tag === OBJECT_CLASS_TYPE_MAP.DATE) {
2165
+ return OBJECT_CLASS_MAP[tag] + "|" + value.getTime();
2166
+ }
2167
+ if (tag === OBJECT_CLASS_TYPE_MAP.ERROR) {
2168
+ return OBJECT_CLASS_MAP[tag] + "|" + value.stack;
2169
+ }
2170
+ if (tag === OBJECT_CLASS_TYPE_MAP.EVENT) {
2171
+ return getSortedEvent(value);
2172
+ }
2173
+ if (UNPARSEABLE_TAGS[tag]) {
2174
+ return OBJECT_CLASS_MAP[tag] + "|NOT_ENUMERABLE";
2175
+ }
2176
+ if (HTML_ELEMENT_REGEXP.test(tag) || SVG_ELEMENT_REGEXP.test(tag)) {
2177
+ return tag.slice(8, -1) + "|" + value.outerHTML;
2178
+ }
2179
+ if (tag === OBJECT_CLASS_TYPE_MAP.DOCUMENTFRAGMENT) {
2180
+ return OBJECT_CLASS_MAP[tag] + "|" + getStringifiedDocumentFragment(value);
2181
+ }
2182
+ if (TYPEDARRAY_TAGS[tag]) {
2183
+ return OBJECT_CLASS_MAP[tag] + "|" + value.join(",");
2184
+ }
2185
+ if (tag === OBJECT_CLASS_TYPE_MAP.ARRAYBUFFER) {
2186
+ return OBJECT_CLASS_MAP[tag] + "|" + getStringifiedArrayBuffer(value);
2187
+ }
2188
+ if (tag === OBJECT_CLASS_TYPE_MAP.DATAVIEW) {
2189
+ return OBJECT_CLASS_MAP[tag] + "|" + getStringifiedArrayBuffer(value.buffer);
2190
+ }
2191
+ return value;
1593
2192
  }
1594
-
1595
- // ../packlytics/dist/utils/sanatize-payload.js
1596
- var sanitizePayload = (data) => {
1597
- let dataStr = JSON.stringify(data);
2193
+ function createReplacer(cache, keys2) {
2194
+ if (cache === void 0) {
2195
+ cache = [];
2196
+ }
2197
+ if (keys2 === void 0) {
2198
+ keys2 = [];
2199
+ }
2200
+ return function(key, value) {
2201
+ if (typeof value === "object") {
2202
+ if (cache.length) {
2203
+ var thisCutoff = getCutoffIndex(cache, this);
2204
+ if (thisCutoff === 0) {
2205
+ cache.push(this);
2206
+ } else {
2207
+ cache.splice(thisCutoff);
2208
+ keys2.splice(thisCutoff);
2209
+ }
2210
+ keys2.push(key);
2211
+ var valueCutoff = getCutoffIndex(cache, value);
2212
+ if (valueCutoff !== 0) {
2213
+ return "[~" + (keys2.slice(0, valueCutoff).join(".") || ".") + "]";
2214
+ }
2215
+ cache.push(value);
2216
+ } else {
2217
+ cache[0] = value;
2218
+ keys2[0] = key;
2219
+ }
2220
+ }
2221
+ if (key && this[key] instanceof Date) {
2222
+ return getNormalizedValue(this[key], cache, keys2, OBJECT_CLASS_TYPE_MAP.DATE, cache, keys2);
2223
+ }
2224
+ return getNormalizedValue(value, cache, keys2);
2225
+ };
2226
+ }
2227
+ function stringify(value, cache, keys2) {
2228
+ if (!value || typeof value !== "object") {
2229
+ return getNormalizedValue(value, cache, keys2);
2230
+ }
2231
+ var tag = toString.call(value);
2232
+ if (tag === OBJECT_CLASS_TYPE_MAP.DATE || tag === OBJECT_CLASS_TYPE_MAP.REGEXP) {
2233
+ return getNormalizedValue(value, cache, keys2, tag);
2234
+ }
2235
+ return JSON.stringify(value, createReplacer(cache, keys2));
2236
+ }
2237
+ var FUNCTION_NAME_REGEX, toString, keys, getStringifiedArrayBuffer;
2238
+ var init_utils = __esm({
2239
+ "../../node_modules/hash-it/es/utils.js"() {
2240
+ "use strict";
2241
+ init_constants();
2242
+ FUNCTION_NAME_REGEX = /^\s*function\s*([^(]*)/i;
2243
+ toString = Object.prototype.toString;
2244
+ keys = Object.keys;
2245
+ getStringifiedArrayBuffer = function() {
2246
+ if (HAS_BUFFER_FROM_SUPPORT) {
2247
+ return getStringifiedArrayBufferModern;
2248
+ }
2249
+ if (HAS_UINT16ARRAY_SUPPORT) {
2250
+ return getStringifiedArrayBufferFallback;
2251
+ }
2252
+ return getStringifiedArrayBufferNoSupport;
2253
+ }();
2254
+ }
2255
+ });
2256
+
2257
+ // ../../node_modules/hash-it/es/index.js
2258
+ var es_exports = {};
2259
+ __export(es_exports, {
2260
+ default: () => es_default,
2261
+ hash: () => hash
2262
+ });
2263
+ function hash(value) {
2264
+ return getIntegerHashValue(stringify(value));
2265
+ }
2266
+ var import_curriable, es_default;
2267
+ var init_es = __esm({
2268
+ "../../node_modules/hash-it/es/index.js"() {
2269
+ "use strict";
2270
+ import_curriable = __toESM(require_curriable());
2271
+ init_utils();
2272
+ hash.is = (0, import_curriable.curry)(function(object, otherObject) {
2273
+ return hash(object) === hash(otherObject);
2274
+ });
2275
+ hash.is.all = (0, import_curriable.curry)(function(objectBasis) {
2276
+ var isEqual = hash.is(objectBasis);
2277
+ for (var index = 1; index < arguments.length; ++index) {
2278
+ if (!isEqual(arguments[index])) {
2279
+ return false;
2280
+ }
2281
+ }
2282
+ return true;
2283
+ }, 2);
2284
+ hash.is.any = (0, import_curriable.curry)(function(objectBasis) {
2285
+ var isEqual = hash.is(objectBasis);
2286
+ for (var index = 1; index < arguments.length; index++) {
2287
+ if (isEqual(arguments[index])) {
2288
+ return true;
2289
+ }
2290
+ }
2291
+ return false;
2292
+ }, 2);
2293
+ hash.is.not = (0, import_curriable.curry)(function(object, otherObject) {
2294
+ return hash(object) !== hash(otherObject);
2295
+ });
2296
+ es_default = hash;
2297
+ }
2298
+ });
2299
+
2300
+ // ../../node_modules/json-rules-engine/dist/fact.js
2301
+ var require_fact = __commonJS({
2302
+ "../../node_modules/json-rules-engine/dist/fact.js"(exports) {
2303
+ "use strict";
2304
+ Object.defineProperty(exports, "__esModule", {
2305
+ value: true
2306
+ });
2307
+ var _createClass = /* @__PURE__ */ function() {
2308
+ function defineProperties(target, props) {
2309
+ for (var i = 0; i < props.length; i++) {
2310
+ var descriptor = props[i];
2311
+ descriptor.enumerable = descriptor.enumerable || false;
2312
+ descriptor.configurable = true;
2313
+ if ("value" in descriptor) descriptor.writable = true;
2314
+ Object.defineProperty(target, descriptor.key, descriptor);
2315
+ }
2316
+ }
2317
+ return function(Constructor, protoProps, staticProps) {
2318
+ if (protoProps) defineProperties(Constructor.prototype, protoProps);
2319
+ if (staticProps) defineProperties(Constructor, staticProps);
2320
+ return Constructor;
2321
+ };
2322
+ }();
2323
+ var _hashIt = (init_es(), __toCommonJS(es_exports));
2324
+ var _hashIt2 = _interopRequireDefault(_hashIt);
2325
+ function _interopRequireDefault(obj) {
2326
+ return obj && obj.__esModule ? obj : { default: obj };
2327
+ }
2328
+ function _classCallCheck(instance, Constructor) {
2329
+ if (!(instance instanceof Constructor)) {
2330
+ throw new TypeError("Cannot call a class as a function");
2331
+ }
2332
+ }
2333
+ var Fact = function() {
2334
+ function Fact2(id, valueOrMethod, options) {
2335
+ _classCallCheck(this, Fact2);
2336
+ this.id = id;
2337
+ var defaultOptions = { cache: true };
2338
+ if (typeof options === "undefined") {
2339
+ options = defaultOptions;
2340
+ }
2341
+ if (typeof valueOrMethod !== "function") {
2342
+ this.value = valueOrMethod;
2343
+ this.type = this.constructor.CONSTANT;
2344
+ } else {
2345
+ this.calculationMethod = valueOrMethod;
2346
+ this.type = this.constructor.DYNAMIC;
2347
+ }
2348
+ if (!this.id) throw new Error("factId required");
2349
+ if (typeof this.value === "undefined" && typeof this.calculationMethod === "undefined") {
2350
+ throw new Error("facts must have a value or method");
2351
+ }
2352
+ this.priority = parseInt(options.priority || 1, 10);
2353
+ this.options = Object.assign({}, defaultOptions, options);
2354
+ this.cacheKeyMethod = this.defaultCacheKeys;
2355
+ return this;
2356
+ }
2357
+ _createClass(Fact2, [{
2358
+ key: "isConstant",
2359
+ value: function isConstant() {
2360
+ return this.type === this.constructor.CONSTANT;
2361
+ }
2362
+ }, {
2363
+ key: "isDynamic",
2364
+ value: function isDynamic() {
2365
+ return this.type === this.constructor.DYNAMIC;
2366
+ }
2367
+ /**
2368
+ * Return the fact value, based on provided parameters
2369
+ * @param {object} params
2370
+ * @param {Almanac} almanac
2371
+ * @return {any} calculation method results
2372
+ */
2373
+ }, {
2374
+ key: "calculate",
2375
+ value: function calculate(params, almanac) {
2376
+ if (this.hasOwnProperty("value")) {
2377
+ return this.value;
2378
+ }
2379
+ return this.calculationMethod(params, almanac);
2380
+ }
2381
+ /**
2382
+ * Return a cache key (MD5 string) based on parameters
2383
+ * @param {object} obj - properties to generate a hash key from
2384
+ * @return {string} MD5 string based on the hash'd object
2385
+ */
2386
+ }, {
2387
+ key: "defaultCacheKeys",
2388
+ /**
2389
+ * Default properties to use when caching a fact
2390
+ * Assumes every fact is a pure function, whose computed value will only
2391
+ * change when input params are modified
2392
+ * @param {string} id - fact unique identifer
2393
+ * @param {object} params - parameters passed to fact calcution method
2394
+ * @return {object} id + params
2395
+ */
2396
+ value: function defaultCacheKeys(id, params) {
2397
+ return { params, id };
2398
+ }
2399
+ /**
2400
+ * Generates the fact's cache key(MD5 string)
2401
+ * Returns nothing if the fact's caching has been disabled
2402
+ * @param {object} params - parameters that would be passed to the computation method
2403
+ * @return {string} cache key
2404
+ */
2405
+ }, {
2406
+ key: "getCacheKey",
2407
+ value: function getCacheKey2(params) {
2408
+ if (this.options.cache === true) {
2409
+ var cacheProperties = this.cacheKeyMethod(this.id, params);
2410
+ var _hash = Fact2.hashFromObject(cacheProperties);
2411
+ return _hash;
2412
+ }
2413
+ }
2414
+ }], [{
2415
+ key: "hashFromObject",
2416
+ value: function hashFromObject(obj) {
2417
+ return (0, _hashIt2.default)(obj);
2418
+ }
2419
+ }]);
2420
+ return Fact2;
2421
+ }();
2422
+ Fact.CONSTANT = "CONSTANT";
2423
+ Fact.DYNAMIC = "DYNAMIC";
2424
+ exports.default = Fact;
2425
+ }
2426
+ });
2427
+
2428
+ // ../../node_modules/json-rules-engine/dist/debug.js
2429
+ var require_debug = __commonJS({
2430
+ "../../node_modules/json-rules-engine/dist/debug.js"(exports) {
2431
+ "use strict";
2432
+ Object.defineProperty(exports, "__esModule", {
2433
+ value: true
2434
+ });
2435
+ exports.default = debug5;
2436
+ function debug5(message) {
2437
+ if (typeof process !== "undefined" && process.env && process.env.DEBUG && process.env.DEBUG.match(/json-rules-engine/) || typeof window !== "undefined" && window.localStorage && window.localStorage.debug && window.localStorage.debug.match(/json-rules-engine/)) {
2438
+ console.log(message);
2439
+ }
2440
+ }
2441
+ }
2442
+ });
2443
+
2444
+ // ../../node_modules/lodash.isobjectlike/index.js
2445
+ var require_lodash = __commonJS({
2446
+ "../../node_modules/lodash.isobjectlike/index.js"(exports, module) {
2447
+ "use strict";
2448
+ function isObjectLike(value) {
2449
+ return !!value && typeof value == "object";
2450
+ }
2451
+ module.exports = isObjectLike;
2452
+ }
2453
+ });
2454
+
2455
+ // ../../node_modules/json-rules-engine/dist/condition.js
2456
+ var require_condition = __commonJS({
2457
+ "../../node_modules/json-rules-engine/dist/condition.js"(exports) {
2458
+ "use strict";
2459
+ Object.defineProperty(exports, "__esModule", {
2460
+ value: true
2461
+ });
2462
+ var _createClass = /* @__PURE__ */ function() {
2463
+ function defineProperties(target, props) {
2464
+ for (var i = 0; i < props.length; i++) {
2465
+ var descriptor = props[i];
2466
+ descriptor.enumerable = descriptor.enumerable || false;
2467
+ descriptor.configurable = true;
2468
+ if ("value" in descriptor) descriptor.writable = true;
2469
+ Object.defineProperty(target, descriptor.key, descriptor);
2470
+ }
2471
+ }
2472
+ return function(Constructor, protoProps, staticProps) {
2473
+ if (protoProps) defineProperties(Constructor.prototype, protoProps);
2474
+ if (staticProps) defineProperties(Constructor, staticProps);
2475
+ return Constructor;
2476
+ };
2477
+ }();
2478
+ var _debug = require_debug();
2479
+ var _debug2 = _interopRequireDefault(_debug);
2480
+ var _lodash = require_lodash();
2481
+ var _lodash2 = _interopRequireDefault(_lodash);
2482
+ function _interopRequireDefault(obj) {
2483
+ return obj && obj.__esModule ? obj : { default: obj };
2484
+ }
2485
+ function _classCallCheck(instance, Constructor) {
2486
+ if (!(instance instanceof Constructor)) {
2487
+ throw new TypeError("Cannot call a class as a function");
2488
+ }
2489
+ }
2490
+ var Condition = function() {
2491
+ function Condition2(properties) {
2492
+ _classCallCheck(this, Condition2);
2493
+ if (!properties) throw new Error("Condition: constructor options required");
2494
+ var booleanOperator = Condition2.booleanOperator(properties);
2495
+ Object.assign(this, properties);
2496
+ if (booleanOperator) {
2497
+ var subConditions = properties[booleanOperator];
2498
+ if (!Array.isArray(subConditions)) {
2499
+ throw new Error('"' + booleanOperator + '" must be an array');
2500
+ }
2501
+ this.operator = booleanOperator;
2502
+ this.priority = parseInt(properties.priority, 10) || 1;
2503
+ this[booleanOperator] = subConditions.map(function(c) {
2504
+ return new Condition2(c);
2505
+ });
2506
+ } else {
2507
+ if (!properties.hasOwnProperty("fact")) throw new Error('Condition: constructor "fact" property required');
2508
+ if (!properties.hasOwnProperty("operator")) throw new Error('Condition: constructor "operator" property required');
2509
+ if (!properties.hasOwnProperty("value")) throw new Error('Condition: constructor "value" property required');
2510
+ if (properties.hasOwnProperty("priority")) {
2511
+ properties.priority = parseInt(properties.priority, 10);
2512
+ }
2513
+ }
2514
+ }
2515
+ _createClass(Condition2, [{
2516
+ key: "toJSON",
2517
+ value: function toJSON() {
2518
+ var stringify2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
2519
+ var props = {};
2520
+ if (this.priority) {
2521
+ props.priority = this.priority;
2522
+ }
2523
+ var oper = Condition2.booleanOperator(this);
2524
+ if (oper) {
2525
+ props[oper] = this[oper].map(function(c) {
2526
+ return c.toJSON(stringify2);
2527
+ });
2528
+ } else {
2529
+ props.operator = this.operator;
2530
+ props.value = this.value;
2531
+ props.fact = this.fact;
2532
+ if (this.factResult !== void 0) {
2533
+ props.factResult = this.factResult;
2534
+ }
2535
+ if (this.result !== void 0) {
2536
+ props.result = this.result;
2537
+ }
2538
+ if (this.params) {
2539
+ props.params = this.params;
2540
+ }
2541
+ if (this.path) {
2542
+ props.path = this.path;
2543
+ }
2544
+ }
2545
+ if (stringify2) {
2546
+ return JSON.stringify(props);
2547
+ }
2548
+ return props;
2549
+ }
2550
+ /**
2551
+ * Interprets .value as either a primitive, or if a fact, retrieves the fact value
2552
+ */
2553
+ }, {
2554
+ key: "_getValue",
2555
+ value: function _getValue(almanac) {
2556
+ var value = this.value;
2557
+ if ((0, _lodash2.default)(value) && value.hasOwnProperty("fact")) {
2558
+ return almanac.factValue(value.fact, value.params, value.path);
2559
+ }
2560
+ return Promise.resolve(value);
2561
+ }
2562
+ /**
2563
+ * Takes the fact result and compares it to the condition 'value', using the operator
2564
+ * LHS OPER RHS
2565
+ * <fact + params + path> <operator> <value>
2566
+ *
2567
+ * @param {Almanac} almanac
2568
+ * @param {Map} operatorMap - map of available operators, keyed by operator name
2569
+ * @returns {Boolean} - evaluation result
2570
+ */
2571
+ }, {
2572
+ key: "evaluate",
2573
+ value: function evaluate(almanac, operatorMap) {
2574
+ var _this = this;
2575
+ if (!almanac) return Promise.reject(new Error("almanac required"));
2576
+ if (!operatorMap) return Promise.reject(new Error("operatorMap required"));
2577
+ if (this.isBooleanOperator()) return Promise.reject(new Error("Cannot evaluate() a boolean condition"));
2578
+ var op = operatorMap.get(this.operator);
2579
+ if (!op) return Promise.reject(new Error("Unknown operator: " + this.operator));
2580
+ return this._getValue(almanac).then(function(rightHandSideValue) {
2581
+ return almanac.factValue(_this.fact, _this.params, _this.path).then(function(leftHandSideValue) {
2582
+ var result = op.evaluate(leftHandSideValue, rightHandSideValue);
2583
+ (0, _debug2.default)("condition::evaluate <" + leftHandSideValue + " " + _this.operator + " " + rightHandSideValue + "?> (" + result + ")");
2584
+ return { result, leftHandSideValue, rightHandSideValue, operator: _this.operator };
2585
+ });
2586
+ });
2587
+ }
2588
+ /**
2589
+ * Returns the boolean operator for the condition
2590
+ * If the condition is not a boolean condition, the result will be 'undefined'
2591
+ * @return {string 'all' or 'any'}
2592
+ */
2593
+ }, {
2594
+ key: "booleanOperator",
2595
+ /**
2596
+ * Returns the condition's boolean operator
2597
+ * Instance version of Condition.isBooleanOperator
2598
+ * @returns {string,undefined} - 'any', 'all', or undefined (if not a boolean condition)
2599
+ */
2600
+ value: function booleanOperator() {
2601
+ return Condition2.booleanOperator(this);
2602
+ }
2603
+ /**
2604
+ * Whether the operator is boolean ('all', 'any')
2605
+ * @returns {Boolean}
2606
+ */
2607
+ }, {
2608
+ key: "isBooleanOperator",
2609
+ value: function isBooleanOperator() {
2610
+ return Condition2.booleanOperator(this) !== void 0;
2611
+ }
2612
+ }], [{
2613
+ key: "booleanOperator",
2614
+ value: function booleanOperator(condition) {
2615
+ if (condition.hasOwnProperty("any")) {
2616
+ return "any";
2617
+ } else if (condition.hasOwnProperty("all")) {
2618
+ return "all";
2619
+ }
2620
+ }
2621
+ }]);
2622
+ return Condition2;
2623
+ }();
2624
+ exports.default = Condition;
2625
+ }
2626
+ });
2627
+
2628
+ // ../../node_modules/clone/clone.js
2629
+ var require_clone = __commonJS({
2630
+ "../../node_modules/clone/clone.js"(exports, module) {
2631
+ "use strict";
2632
+ var clone = function() {
2633
+ "use strict";
2634
+ function _instanceof(obj, type) {
2635
+ return type != null && obj instanceof type;
2636
+ }
2637
+ var nativeMap;
2638
+ try {
2639
+ nativeMap = Map;
2640
+ } catch (_) {
2641
+ nativeMap = function() {
2642
+ };
2643
+ }
2644
+ var nativeSet;
2645
+ try {
2646
+ nativeSet = Set;
2647
+ } catch (_) {
2648
+ nativeSet = function() {
2649
+ };
2650
+ }
2651
+ var nativePromise;
2652
+ try {
2653
+ nativePromise = Promise;
2654
+ } catch (_) {
2655
+ nativePromise = function() {
2656
+ };
2657
+ }
2658
+ function clone2(parent, circular, depth, prototype, includeNonEnumerable) {
2659
+ if (typeof circular === "object") {
2660
+ depth = circular.depth;
2661
+ prototype = circular.prototype;
2662
+ includeNonEnumerable = circular.includeNonEnumerable;
2663
+ circular = circular.circular;
2664
+ }
2665
+ var allParents = [];
2666
+ var allChildren = [];
2667
+ var useBuffer = typeof Buffer != "undefined";
2668
+ if (typeof circular == "undefined")
2669
+ circular = true;
2670
+ if (typeof depth == "undefined")
2671
+ depth = Infinity;
2672
+ function _clone(parent2, depth2) {
2673
+ if (parent2 === null)
2674
+ return null;
2675
+ if (depth2 === 0)
2676
+ return parent2;
2677
+ var child;
2678
+ var proto;
2679
+ if (typeof parent2 != "object") {
2680
+ return parent2;
2681
+ }
2682
+ if (_instanceof(parent2, nativeMap)) {
2683
+ child = new nativeMap();
2684
+ } else if (_instanceof(parent2, nativeSet)) {
2685
+ child = new nativeSet();
2686
+ } else if (_instanceof(parent2, nativePromise)) {
2687
+ child = new nativePromise(function(resolve, reject) {
2688
+ parent2.then(function(value) {
2689
+ resolve(_clone(value, depth2 - 1));
2690
+ }, function(err) {
2691
+ reject(_clone(err, depth2 - 1));
2692
+ });
2693
+ });
2694
+ } else if (clone2.__isArray(parent2)) {
2695
+ child = [];
2696
+ } else if (clone2.__isRegExp(parent2)) {
2697
+ child = new RegExp(parent2.source, __getRegExpFlags(parent2));
2698
+ if (parent2.lastIndex) child.lastIndex = parent2.lastIndex;
2699
+ } else if (clone2.__isDate(parent2)) {
2700
+ child = new Date(parent2.getTime());
2701
+ } else if (useBuffer && Buffer.isBuffer(parent2)) {
2702
+ if (Buffer.allocUnsafe) {
2703
+ child = Buffer.allocUnsafe(parent2.length);
2704
+ } else {
2705
+ child = new Buffer(parent2.length);
2706
+ }
2707
+ parent2.copy(child);
2708
+ return child;
2709
+ } else if (_instanceof(parent2, Error)) {
2710
+ child = Object.create(parent2);
2711
+ } else {
2712
+ if (typeof prototype == "undefined") {
2713
+ proto = Object.getPrototypeOf(parent2);
2714
+ child = Object.create(proto);
2715
+ } else {
2716
+ child = Object.create(prototype);
2717
+ proto = prototype;
2718
+ }
2719
+ }
2720
+ if (circular) {
2721
+ var index = allParents.indexOf(parent2);
2722
+ if (index != -1) {
2723
+ return allChildren[index];
2724
+ }
2725
+ allParents.push(parent2);
2726
+ allChildren.push(child);
2727
+ }
2728
+ if (_instanceof(parent2, nativeMap)) {
2729
+ parent2.forEach(function(value, key) {
2730
+ var keyChild = _clone(key, depth2 - 1);
2731
+ var valueChild = _clone(value, depth2 - 1);
2732
+ child.set(keyChild, valueChild);
2733
+ });
2734
+ }
2735
+ if (_instanceof(parent2, nativeSet)) {
2736
+ parent2.forEach(function(value) {
2737
+ var entryChild = _clone(value, depth2 - 1);
2738
+ child.add(entryChild);
2739
+ });
2740
+ }
2741
+ for (var i in parent2) {
2742
+ var attrs;
2743
+ if (proto) {
2744
+ attrs = Object.getOwnPropertyDescriptor(proto, i);
2745
+ }
2746
+ if (attrs && attrs.set == null) {
2747
+ continue;
2748
+ }
2749
+ child[i] = _clone(parent2[i], depth2 - 1);
2750
+ }
2751
+ if (Object.getOwnPropertySymbols) {
2752
+ var symbols = Object.getOwnPropertySymbols(parent2);
2753
+ for (var i = 0; i < symbols.length; i++) {
2754
+ var symbol = symbols[i];
2755
+ var descriptor = Object.getOwnPropertyDescriptor(parent2, symbol);
2756
+ if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
2757
+ continue;
2758
+ }
2759
+ child[symbol] = _clone(parent2[symbol], depth2 - 1);
2760
+ if (!descriptor.enumerable) {
2761
+ Object.defineProperty(child, symbol, {
2762
+ enumerable: false
2763
+ });
2764
+ }
2765
+ }
2766
+ }
2767
+ if (includeNonEnumerable) {
2768
+ var allPropertyNames = Object.getOwnPropertyNames(parent2);
2769
+ for (var i = 0; i < allPropertyNames.length; i++) {
2770
+ var propertyName = allPropertyNames[i];
2771
+ var descriptor = Object.getOwnPropertyDescriptor(parent2, propertyName);
2772
+ if (descriptor && descriptor.enumerable) {
2773
+ continue;
2774
+ }
2775
+ child[propertyName] = _clone(parent2[propertyName], depth2 - 1);
2776
+ Object.defineProperty(child, propertyName, {
2777
+ enumerable: false
2778
+ });
2779
+ }
2780
+ }
2781
+ return child;
2782
+ }
2783
+ return _clone(parent, depth);
2784
+ }
2785
+ clone2.clonePrototype = function clonePrototype(parent) {
2786
+ if (parent === null)
2787
+ return null;
2788
+ var c = function() {
2789
+ };
2790
+ c.prototype = parent;
2791
+ return new c();
2792
+ };
2793
+ function __objToStr(o) {
2794
+ return Object.prototype.toString.call(o);
2795
+ }
2796
+ clone2.__objToStr = __objToStr;
2797
+ function __isDate(o) {
2798
+ return typeof o === "object" && __objToStr(o) === "[object Date]";
2799
+ }
2800
+ clone2.__isDate = __isDate;
2801
+ function __isArray(o) {
2802
+ return typeof o === "object" && __objToStr(o) === "[object Array]";
2803
+ }
2804
+ clone2.__isArray = __isArray;
2805
+ function __isRegExp(o) {
2806
+ return typeof o === "object" && __objToStr(o) === "[object RegExp]";
2807
+ }
2808
+ clone2.__isRegExp = __isRegExp;
2809
+ function __getRegExpFlags(re) {
2810
+ var flags = "";
2811
+ if (re.global) flags += "g";
2812
+ if (re.ignoreCase) flags += "i";
2813
+ if (re.multiline) flags += "m";
2814
+ return flags;
2815
+ }
2816
+ clone2.__getRegExpFlags = __getRegExpFlags;
2817
+ return clone2;
2818
+ }();
2819
+ if (typeof module === "object" && module.exports) {
2820
+ module.exports = clone;
2821
+ }
2822
+ }
2823
+ });
2824
+
2825
+ // ../../node_modules/json-rules-engine/dist/rule-result.js
2826
+ var require_rule_result = __commonJS({
2827
+ "../../node_modules/json-rules-engine/dist/rule-result.js"(exports) {
2828
+ "use strict";
2829
+ Object.defineProperty(exports, "__esModule", {
2830
+ value: true
2831
+ });
2832
+ var _createClass = /* @__PURE__ */ function() {
2833
+ function defineProperties(target, props) {
2834
+ for (var i = 0; i < props.length; i++) {
2835
+ var descriptor = props[i];
2836
+ descriptor.enumerable = descriptor.enumerable || false;
2837
+ descriptor.configurable = true;
2838
+ if ("value" in descriptor) descriptor.writable = true;
2839
+ Object.defineProperty(target, descriptor.key, descriptor);
2840
+ }
2841
+ }
2842
+ return function(Constructor, protoProps, staticProps) {
2843
+ if (protoProps) defineProperties(Constructor.prototype, protoProps);
2844
+ if (staticProps) defineProperties(Constructor, staticProps);
2845
+ return Constructor;
2846
+ };
2847
+ }();
2848
+ var _clone = require_clone();
2849
+ var _clone2 = _interopRequireDefault(_clone);
2850
+ function _interopRequireDefault(obj) {
2851
+ return obj && obj.__esModule ? obj : { default: obj };
2852
+ }
2853
+ function _classCallCheck(instance, Constructor) {
2854
+ if (!(instance instanceof Constructor)) {
2855
+ throw new TypeError("Cannot call a class as a function");
2856
+ }
2857
+ }
2858
+ var RuleResult = function() {
2859
+ function RuleResult2(conditions, event, priority, name) {
2860
+ _classCallCheck(this, RuleResult2);
2861
+ this.conditions = (0, _clone2.default)(conditions);
2862
+ this.event = (0, _clone2.default)(event);
2863
+ this.priority = (0, _clone2.default)(priority);
2864
+ this.name = (0, _clone2.default)(name);
2865
+ this.result = null;
2866
+ }
2867
+ _createClass(RuleResult2, [{
2868
+ key: "setResult",
2869
+ value: function setResult(result) {
2870
+ this.result = result;
2871
+ }
2872
+ }, {
2873
+ key: "toJSON",
2874
+ value: function toJSON() {
2875
+ var stringify2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
2876
+ var props = {
2877
+ conditions: this.conditions.toJSON(false),
2878
+ event: this.event,
2879
+ priority: this.priority,
2880
+ name: this.name,
2881
+ result: this.result
2882
+ };
2883
+ if (stringify2) {
2884
+ return JSON.stringify(props);
2885
+ }
2886
+ return props;
2887
+ }
2888
+ }]);
2889
+ return RuleResult2;
2890
+ }();
2891
+ exports.default = RuleResult;
2892
+ }
2893
+ });
2894
+
2895
+ // ../../node_modules/events/events.js
2896
+ var require_events = __commonJS({
2897
+ "../../node_modules/events/events.js"(exports, module) {
2898
+ "use strict";
2899
+ var R = typeof Reflect === "object" ? Reflect : null;
2900
+ var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) {
2901
+ return Function.prototype.apply.call(target, receiver, args);
2902
+ };
2903
+ var ReflectOwnKeys;
2904
+ if (R && typeof R.ownKeys === "function") {
2905
+ ReflectOwnKeys = R.ownKeys;
2906
+ } else if (Object.getOwnPropertySymbols) {
2907
+ ReflectOwnKeys = function ReflectOwnKeys2(target) {
2908
+ return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
2909
+ };
2910
+ } else {
2911
+ ReflectOwnKeys = function ReflectOwnKeys2(target) {
2912
+ return Object.getOwnPropertyNames(target);
2913
+ };
2914
+ }
2915
+ function ProcessEmitWarning(warning) {
2916
+ if (console && console.warn) console.warn(warning);
2917
+ }
2918
+ var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) {
2919
+ return value !== value;
2920
+ };
2921
+ function EventEmitter() {
2922
+ EventEmitter.init.call(this);
2923
+ }
2924
+ module.exports = EventEmitter;
2925
+ module.exports.once = once;
2926
+ EventEmitter.EventEmitter = EventEmitter;
2927
+ EventEmitter.prototype._events = void 0;
2928
+ EventEmitter.prototype._eventsCount = 0;
2929
+ EventEmitter.prototype._maxListeners = void 0;
2930
+ var defaultMaxListeners = 10;
2931
+ function checkListener(listener) {
2932
+ if (typeof listener !== "function") {
2933
+ throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
2934
+ }
2935
+ }
2936
+ Object.defineProperty(EventEmitter, "defaultMaxListeners", {
2937
+ enumerable: true,
2938
+ get: function() {
2939
+ return defaultMaxListeners;
2940
+ },
2941
+ set: function(arg) {
2942
+ if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) {
2943
+ throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".");
2944
+ }
2945
+ defaultMaxListeners = arg;
2946
+ }
2947
+ });
2948
+ EventEmitter.init = function() {
2949
+ if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
2950
+ this._events = /* @__PURE__ */ Object.create(null);
2951
+ this._eventsCount = 0;
2952
+ }
2953
+ this._maxListeners = this._maxListeners || void 0;
2954
+ };
2955
+ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
2956
+ if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) {
2957
+ throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + ".");
2958
+ }
2959
+ this._maxListeners = n;
2960
+ return this;
2961
+ };
2962
+ function _getMaxListeners(that) {
2963
+ if (that._maxListeners === void 0)
2964
+ return EventEmitter.defaultMaxListeners;
2965
+ return that._maxListeners;
2966
+ }
2967
+ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
2968
+ return _getMaxListeners(this);
2969
+ };
2970
+ EventEmitter.prototype.emit = function emit(type) {
2971
+ var args = [];
2972
+ for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
2973
+ var doError = type === "error";
2974
+ var events = this._events;
2975
+ if (events !== void 0)
2976
+ doError = doError && events.error === void 0;
2977
+ else if (!doError)
2978
+ return false;
2979
+ if (doError) {
2980
+ var er;
2981
+ if (args.length > 0)
2982
+ er = args[0];
2983
+ if (er instanceof Error) {
2984
+ throw er;
2985
+ }
2986
+ var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
2987
+ err.context = er;
2988
+ throw err;
2989
+ }
2990
+ var handler = events[type];
2991
+ if (handler === void 0)
2992
+ return false;
2993
+ if (typeof handler === "function") {
2994
+ ReflectApply(handler, this, args);
2995
+ } else {
2996
+ var len = handler.length;
2997
+ var listeners = arrayClone(handler, len);
2998
+ for (var i = 0; i < len; ++i)
2999
+ ReflectApply(listeners[i], this, args);
3000
+ }
3001
+ return true;
3002
+ };
3003
+ function _addListener(target, type, listener, prepend) {
3004
+ var m;
3005
+ var events;
3006
+ var existing;
3007
+ checkListener(listener);
3008
+ events = target._events;
3009
+ if (events === void 0) {
3010
+ events = target._events = /* @__PURE__ */ Object.create(null);
3011
+ target._eventsCount = 0;
3012
+ } else {
3013
+ if (events.newListener !== void 0) {
3014
+ target.emit(
3015
+ "newListener",
3016
+ type,
3017
+ listener.listener ? listener.listener : listener
3018
+ );
3019
+ events = target._events;
3020
+ }
3021
+ existing = events[type];
3022
+ }
3023
+ if (existing === void 0) {
3024
+ existing = events[type] = listener;
3025
+ ++target._eventsCount;
3026
+ } else {
3027
+ if (typeof existing === "function") {
3028
+ existing = events[type] = prepend ? [listener, existing] : [existing, listener];
3029
+ } else if (prepend) {
3030
+ existing.unshift(listener);
3031
+ } else {
3032
+ existing.push(listener);
3033
+ }
3034
+ m = _getMaxListeners(target);
3035
+ if (m > 0 && existing.length > m && !existing.warned) {
3036
+ existing.warned = true;
3037
+ var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
3038
+ w.name = "MaxListenersExceededWarning";
3039
+ w.emitter = target;
3040
+ w.type = type;
3041
+ w.count = existing.length;
3042
+ ProcessEmitWarning(w);
3043
+ }
3044
+ }
3045
+ return target;
3046
+ }
3047
+ EventEmitter.prototype.addListener = function addListener(type, listener) {
3048
+ return _addListener(this, type, listener, false);
3049
+ };
3050
+ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
3051
+ EventEmitter.prototype.prependListener = function prependListener(type, listener) {
3052
+ return _addListener(this, type, listener, true);
3053
+ };
3054
+ function onceWrapper() {
3055
+ if (!this.fired) {
3056
+ this.target.removeListener(this.type, this.wrapFn);
3057
+ this.fired = true;
3058
+ if (arguments.length === 0)
3059
+ return this.listener.call(this.target);
3060
+ return this.listener.apply(this.target, arguments);
3061
+ }
3062
+ }
3063
+ function _onceWrap(target, type, listener) {
3064
+ var state = { fired: false, wrapFn: void 0, target, type, listener };
3065
+ var wrapped = onceWrapper.bind(state);
3066
+ wrapped.listener = listener;
3067
+ state.wrapFn = wrapped;
3068
+ return wrapped;
3069
+ }
3070
+ EventEmitter.prototype.once = function once2(type, listener) {
3071
+ checkListener(listener);
3072
+ this.on(type, _onceWrap(this, type, listener));
3073
+ return this;
3074
+ };
3075
+ EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
3076
+ checkListener(listener);
3077
+ this.prependListener(type, _onceWrap(this, type, listener));
3078
+ return this;
3079
+ };
3080
+ EventEmitter.prototype.removeListener = function removeListener(type, listener) {
3081
+ var list, events, position, i, originalListener;
3082
+ checkListener(listener);
3083
+ events = this._events;
3084
+ if (events === void 0)
3085
+ return this;
3086
+ list = events[type];
3087
+ if (list === void 0)
3088
+ return this;
3089
+ if (list === listener || list.listener === listener) {
3090
+ if (--this._eventsCount === 0)
3091
+ this._events = /* @__PURE__ */ Object.create(null);
3092
+ else {
3093
+ delete events[type];
3094
+ if (events.removeListener)
3095
+ this.emit("removeListener", type, list.listener || listener);
3096
+ }
3097
+ } else if (typeof list !== "function") {
3098
+ position = -1;
3099
+ for (i = list.length - 1; i >= 0; i--) {
3100
+ if (list[i] === listener || list[i].listener === listener) {
3101
+ originalListener = list[i].listener;
3102
+ position = i;
3103
+ break;
3104
+ }
3105
+ }
3106
+ if (position < 0)
3107
+ return this;
3108
+ if (position === 0)
3109
+ list.shift();
3110
+ else {
3111
+ spliceOne(list, position);
3112
+ }
3113
+ if (list.length === 1)
3114
+ events[type] = list[0];
3115
+ if (events.removeListener !== void 0)
3116
+ this.emit("removeListener", type, originalListener || listener);
3117
+ }
3118
+ return this;
3119
+ };
3120
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
3121
+ EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
3122
+ var listeners, events, i;
3123
+ events = this._events;
3124
+ if (events === void 0)
3125
+ return this;
3126
+ if (events.removeListener === void 0) {
3127
+ if (arguments.length === 0) {
3128
+ this._events = /* @__PURE__ */ Object.create(null);
3129
+ this._eventsCount = 0;
3130
+ } else if (events[type] !== void 0) {
3131
+ if (--this._eventsCount === 0)
3132
+ this._events = /* @__PURE__ */ Object.create(null);
3133
+ else
3134
+ delete events[type];
3135
+ }
3136
+ return this;
3137
+ }
3138
+ if (arguments.length === 0) {
3139
+ var keys2 = Object.keys(events);
3140
+ var key;
3141
+ for (i = 0; i < keys2.length; ++i) {
3142
+ key = keys2[i];
3143
+ if (key === "removeListener") continue;
3144
+ this.removeAllListeners(key);
3145
+ }
3146
+ this.removeAllListeners("removeListener");
3147
+ this._events = /* @__PURE__ */ Object.create(null);
3148
+ this._eventsCount = 0;
3149
+ return this;
3150
+ }
3151
+ listeners = events[type];
3152
+ if (typeof listeners === "function") {
3153
+ this.removeListener(type, listeners);
3154
+ } else if (listeners !== void 0) {
3155
+ for (i = listeners.length - 1; i >= 0; i--) {
3156
+ this.removeListener(type, listeners[i]);
3157
+ }
3158
+ }
3159
+ return this;
3160
+ };
3161
+ function _listeners(target, type, unwrap) {
3162
+ var events = target._events;
3163
+ if (events === void 0)
3164
+ return [];
3165
+ var evlistener = events[type];
3166
+ if (evlistener === void 0)
3167
+ return [];
3168
+ if (typeof evlistener === "function")
3169
+ return unwrap ? [evlistener.listener || evlistener] : [evlistener];
3170
+ return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
3171
+ }
3172
+ EventEmitter.prototype.listeners = function listeners(type) {
3173
+ return _listeners(this, type, true);
3174
+ };
3175
+ EventEmitter.prototype.rawListeners = function rawListeners(type) {
3176
+ return _listeners(this, type, false);
3177
+ };
3178
+ EventEmitter.listenerCount = function(emitter, type) {
3179
+ if (typeof emitter.listenerCount === "function") {
3180
+ return emitter.listenerCount(type);
3181
+ } else {
3182
+ return listenerCount.call(emitter, type);
3183
+ }
3184
+ };
3185
+ EventEmitter.prototype.listenerCount = listenerCount;
3186
+ function listenerCount(type) {
3187
+ var events = this._events;
3188
+ if (events !== void 0) {
3189
+ var evlistener = events[type];
3190
+ if (typeof evlistener === "function") {
3191
+ return 1;
3192
+ } else if (evlistener !== void 0) {
3193
+ return evlistener.length;
3194
+ }
3195
+ }
3196
+ return 0;
3197
+ }
3198
+ EventEmitter.prototype.eventNames = function eventNames() {
3199
+ return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
3200
+ };
3201
+ function arrayClone(arr, n) {
3202
+ var copy = new Array(n);
3203
+ for (var i = 0; i < n; ++i)
3204
+ copy[i] = arr[i];
3205
+ return copy;
3206
+ }
3207
+ function spliceOne(list, index) {
3208
+ for (; index + 1 < list.length; index++)
3209
+ list[index] = list[index + 1];
3210
+ list.pop();
3211
+ }
3212
+ function unwrapListeners(arr) {
3213
+ var ret = new Array(arr.length);
3214
+ for (var i = 0; i < ret.length; ++i) {
3215
+ ret[i] = arr[i].listener || arr[i];
3216
+ }
3217
+ return ret;
3218
+ }
3219
+ function once(emitter, name) {
3220
+ return new Promise(function(resolve, reject) {
3221
+ function errorListener(err) {
3222
+ emitter.removeListener(name, resolver);
3223
+ reject(err);
3224
+ }
3225
+ function resolver() {
3226
+ if (typeof emitter.removeListener === "function") {
3227
+ emitter.removeListener("error", errorListener);
3228
+ }
3229
+ resolve([].slice.call(arguments));
3230
+ }
3231
+ ;
3232
+ eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
3233
+ if (name !== "error") {
3234
+ addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
3235
+ }
3236
+ });
3237
+ }
3238
+ function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
3239
+ if (typeof emitter.on === "function") {
3240
+ eventTargetAgnosticAddListener(emitter, "error", handler, flags);
3241
+ }
3242
+ }
3243
+ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
3244
+ if (typeof emitter.on === "function") {
3245
+ if (flags.once) {
3246
+ emitter.once(name, listener);
3247
+ } else {
3248
+ emitter.on(name, listener);
3249
+ }
3250
+ } else if (typeof emitter.addEventListener === "function") {
3251
+ emitter.addEventListener(name, function wrapListener(arg) {
3252
+ if (flags.once) {
3253
+ emitter.removeEventListener(name, wrapListener);
3254
+ }
3255
+ listener(arg);
3256
+ });
3257
+ } else {
3258
+ throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
3259
+ }
3260
+ }
3261
+ }
3262
+ });
3263
+
3264
+ // ../../node_modules/json-rules-engine/dist/rule.js
3265
+ var require_rule = __commonJS({
3266
+ "../../node_modules/json-rules-engine/dist/rule.js"(exports) {
3267
+ "use strict";
3268
+ Object.defineProperty(exports, "__esModule", {
3269
+ value: true
3270
+ });
3271
+ var _createClass = /* @__PURE__ */ function() {
3272
+ function defineProperties(target, props) {
3273
+ for (var i = 0; i < props.length; i++) {
3274
+ var descriptor = props[i];
3275
+ descriptor.enumerable = descriptor.enumerable || false;
3276
+ descriptor.configurable = true;
3277
+ if ("value" in descriptor) descriptor.writable = true;
3278
+ Object.defineProperty(target, descriptor.key, descriptor);
3279
+ }
3280
+ }
3281
+ return function(Constructor, protoProps, staticProps) {
3282
+ if (protoProps) defineProperties(Constructor.prototype, protoProps);
3283
+ if (staticProps) defineProperties(Constructor, staticProps);
3284
+ return Constructor;
3285
+ };
3286
+ }();
3287
+ var _condition = require_condition();
3288
+ var _condition2 = _interopRequireDefault(_condition);
3289
+ var _ruleResult = require_rule_result();
3290
+ var _ruleResult2 = _interopRequireDefault(_ruleResult);
3291
+ var _events = require_events();
3292
+ var _debug = require_debug();
3293
+ var _debug2 = _interopRequireDefault(_debug);
3294
+ function _interopRequireDefault(obj) {
3295
+ return obj && obj.__esModule ? obj : { default: obj };
3296
+ }
3297
+ function _classCallCheck(instance, Constructor) {
3298
+ if (!(instance instanceof Constructor)) {
3299
+ throw new TypeError("Cannot call a class as a function");
3300
+ }
3301
+ }
3302
+ function _possibleConstructorReturn(self2, call) {
3303
+ if (!self2) {
3304
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
3305
+ }
3306
+ return call && (typeof call === "object" || typeof call === "function") ? call : self2;
3307
+ }
3308
+ function _inherits(subClass, superClass) {
3309
+ if (typeof superClass !== "function" && superClass !== null) {
3310
+ throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
3311
+ }
3312
+ subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });
3313
+ if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
3314
+ }
3315
+ var Rule2 = function(_EventEmitter) {
3316
+ _inherits(Rule3, _EventEmitter);
3317
+ function Rule3(options) {
3318
+ _classCallCheck(this, Rule3);
3319
+ var _this = _possibleConstructorReturn(this, (Rule3.__proto__ || Object.getPrototypeOf(Rule3)).call(this));
3320
+ if (typeof options === "string") {
3321
+ options = JSON.parse(options);
3322
+ }
3323
+ if (options && options.conditions) {
3324
+ _this.setConditions(options.conditions);
3325
+ }
3326
+ if (options && options.onSuccess) {
3327
+ _this.on("success", options.onSuccess);
3328
+ }
3329
+ if (options && options.onFailure) {
3330
+ _this.on("failure", options.onFailure);
3331
+ }
3332
+ if (options && (options.name || options.name === 0)) {
3333
+ _this.setName(options.name);
3334
+ }
3335
+ var priority = options && options.priority || 1;
3336
+ _this.setPriority(priority);
3337
+ var event = options && options.event || { type: "unknown" };
3338
+ _this.setEvent(event);
3339
+ return _this;
3340
+ }
3341
+ _createClass(Rule3, [{
3342
+ key: "setPriority",
3343
+ value: function setPriority(priority) {
3344
+ priority = parseInt(priority, 10);
3345
+ if (priority <= 0) throw new Error("Priority must be greater than zero");
3346
+ this.priority = priority;
3347
+ return this;
3348
+ }
3349
+ /**
3350
+ * Sets the name of the rule
3351
+ * @param {any} name - any truthy input and zero is allowed
3352
+ */
3353
+ }, {
3354
+ key: "setName",
3355
+ value: function setName(name) {
3356
+ if (!name && name !== 0) {
3357
+ throw new Error('Rule "name" must be defined');
3358
+ }
3359
+ this.name = name;
3360
+ return this;
3361
+ }
3362
+ /**
3363
+ * Sets the conditions to run when evaluating the rule.
3364
+ * @param {object} conditions - conditions, root element must be a boolean operator
3365
+ */
3366
+ }, {
3367
+ key: "setConditions",
3368
+ value: function setConditions(conditions) {
3369
+ if (!conditions.hasOwnProperty("all") && !conditions.hasOwnProperty("any")) {
3370
+ throw new Error('"conditions" root must contain a single instance of "all" or "any"');
3371
+ }
3372
+ this.conditions = new _condition2.default(conditions);
3373
+ return this;
3374
+ }
3375
+ /**
3376
+ * Sets the event to emit when the conditions evaluate truthy
3377
+ * @param {object} event - event to emit
3378
+ * @param {string} event.type - event name to emit on
3379
+ * @param {string} event.params - parameters to emit as the argument of the event emission
3380
+ */
3381
+ }, {
3382
+ key: "setEvent",
3383
+ value: function setEvent(event) {
3384
+ if (!event) throw new Error("Rule: setEvent() requires event object");
3385
+ if (!event.hasOwnProperty("type")) throw new Error('Rule: setEvent() requires event object with "type" property');
3386
+ this.event = {
3387
+ type: event.type
3388
+ };
3389
+ if (event.params) this.event.params = event.params;
3390
+ return this;
3391
+ }
3392
+ /**
3393
+ * Sets the engine to run the rules under
3394
+ * @param {object} engine
3395
+ * @returns {Rule}
3396
+ */
3397
+ }, {
3398
+ key: "setEngine",
3399
+ value: function setEngine(engine) {
3400
+ this.engine = engine;
3401
+ return this;
3402
+ }
3403
+ }, {
3404
+ key: "toJSON",
3405
+ value: function toJSON() {
3406
+ var stringify2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
3407
+ var props = {
3408
+ conditions: this.conditions.toJSON(false),
3409
+ priority: this.priority,
3410
+ event: this.event,
3411
+ name: this.name
3412
+ };
3413
+ if (stringify2) {
3414
+ return JSON.stringify(props);
3415
+ }
3416
+ return props;
3417
+ }
3418
+ /**
3419
+ * Priorizes an array of conditions based on "priority"
3420
+ * When no explicit priority is provided on the condition itself, the condition's priority is determine by its fact
3421
+ * @param {Condition[]} conditions
3422
+ * @return {Condition[][]} prioritized two-dimensional array of conditions
3423
+ * Each outer array element represents a single priority(integer). Inner array is
3424
+ * all conditions with that priority.
3425
+ */
3426
+ }, {
3427
+ key: "prioritizeConditions",
3428
+ value: function prioritizeConditions(conditions) {
3429
+ var _this2 = this;
3430
+ var factSets = conditions.reduce(function(sets, condition) {
3431
+ var priority = condition.priority;
3432
+ if (!priority) {
3433
+ var fact = _this2.engine.getFact(condition.fact);
3434
+ priority = fact && fact.priority || 1;
3435
+ }
3436
+ if (!sets[priority]) sets[priority] = [];
3437
+ sets[priority].push(condition);
3438
+ return sets;
3439
+ }, {});
3440
+ return Object.keys(factSets).sort(function(a, b) {
3441
+ return Number(a) > Number(b) ? -1 : 1;
3442
+ }).map(function(priority) {
3443
+ return factSets[priority];
3444
+ });
3445
+ }
3446
+ /**
3447
+ * Evaluates the rule, starting with the root boolean operator and recursing down
3448
+ * All evaluation is done within the context of an almanac
3449
+ * @return {Promise(RuleResult)} rule evaluation result
3450
+ */
3451
+ }, {
3452
+ key: "evaluate",
3453
+ value: function evaluate(almanac) {
3454
+ var _this3 = this;
3455
+ var ruleResult = new _ruleResult2.default(this.conditions, this.event, this.priority, this.name);
3456
+ var evaluateCondition = function evaluateCondition2(condition) {
3457
+ if (condition.isBooleanOperator()) {
3458
+ var subConditions = condition[condition.operator];
3459
+ var comparisonPromise = void 0;
3460
+ if (condition.operator === "all") {
3461
+ comparisonPromise = all(subConditions);
3462
+ } else {
3463
+ comparisonPromise = any(subConditions);
3464
+ }
3465
+ return comparisonPromise.then(function(comparisonValue) {
3466
+ var passes = comparisonValue === true;
3467
+ condition.result = passes;
3468
+ return passes;
3469
+ });
3470
+ } else {
3471
+ return condition.evaluate(almanac, _this3.engine.operators).then(function(evaluationResult) {
3472
+ var passes = evaluationResult.result;
3473
+ condition.factResult = evaluationResult.leftHandSideValue;
3474
+ condition.result = passes;
3475
+ return passes;
3476
+ });
3477
+ }
3478
+ };
3479
+ var evaluateConditions = function evaluateConditions2(conditions, method) {
3480
+ if (!Array.isArray(conditions)) conditions = [conditions];
3481
+ return Promise.all(conditions.map(function(condition) {
3482
+ return evaluateCondition(condition);
3483
+ })).then(function(conditionResults) {
3484
+ (0, _debug2.default)("rule::evaluateConditions results", conditionResults);
3485
+ return method.call(conditionResults, function(result) {
3486
+ return result === true;
3487
+ });
3488
+ });
3489
+ };
3490
+ var prioritizeAndRun = function prioritizeAndRun2(conditions, operator) {
3491
+ if (conditions.length === 0) {
3492
+ return Promise.resolve(true);
3493
+ }
3494
+ var method = Array.prototype.some;
3495
+ if (operator === "all") {
3496
+ method = Array.prototype.every;
3497
+ }
3498
+ var orderedSets = _this3.prioritizeConditions(conditions);
3499
+ var cursor = Promise.resolve();
3500
+ var _loop = function _loop2(i2) {
3501
+ var set = orderedSets[i2];
3502
+ var stop = false;
3503
+ cursor = cursor.then(function(setResult) {
3504
+ if (operator === "any" && setResult === true || stop) {
3505
+ (0, _debug2.default)("prioritizeAndRun::detected truthy result; skipping remaining conditions");
3506
+ stop = true;
3507
+ return true;
3508
+ }
3509
+ if (operator === "all" && setResult === false || stop) {
3510
+ (0, _debug2.default)("prioritizeAndRun::detected falsey result; skipping remaining conditions");
3511
+ stop = true;
3512
+ return false;
3513
+ }
3514
+ return evaluateConditions(set, method);
3515
+ });
3516
+ };
3517
+ for (var i = 0; i < orderedSets.length; i++) {
3518
+ _loop(i);
3519
+ }
3520
+ return cursor;
3521
+ };
3522
+ var any = function any2(conditions) {
3523
+ return prioritizeAndRun(conditions, "any");
3524
+ };
3525
+ var all = function all2(conditions) {
3526
+ return prioritizeAndRun(conditions, "all");
3527
+ };
3528
+ var processResult = function processResult2(result) {
3529
+ ruleResult.setResult(result);
3530
+ if (result) _this3.emit("success", ruleResult.event, almanac, ruleResult);
3531
+ else _this3.emit("failure", ruleResult.event, almanac, ruleResult);
3532
+ return ruleResult;
3533
+ };
3534
+ if (ruleResult.conditions.any) {
3535
+ return any(ruleResult.conditions.any).then(function(result) {
3536
+ return processResult(result);
3537
+ });
3538
+ } else {
3539
+ return all(ruleResult.conditions.all).then(function(result) {
3540
+ return processResult(result);
3541
+ });
3542
+ }
3543
+ }
3544
+ }]);
3545
+ return Rule3;
3546
+ }(_events.EventEmitter);
3547
+ exports.default = Rule2;
3548
+ }
3549
+ });
3550
+
3551
+ // ../../node_modules/json-rules-engine/dist/operator.js
3552
+ var require_operator = __commonJS({
3553
+ "../../node_modules/json-rules-engine/dist/operator.js"(exports) {
3554
+ "use strict";
3555
+ Object.defineProperty(exports, "__esModule", {
3556
+ value: true
3557
+ });
3558
+ var _createClass = /* @__PURE__ */ function() {
3559
+ function defineProperties(target, props) {
3560
+ for (var i = 0; i < props.length; i++) {
3561
+ var descriptor = props[i];
3562
+ descriptor.enumerable = descriptor.enumerable || false;
3563
+ descriptor.configurable = true;
3564
+ if ("value" in descriptor) descriptor.writable = true;
3565
+ Object.defineProperty(target, descriptor.key, descriptor);
3566
+ }
3567
+ }
3568
+ return function(Constructor, protoProps, staticProps) {
3569
+ if (protoProps) defineProperties(Constructor.prototype, protoProps);
3570
+ if (staticProps) defineProperties(Constructor, staticProps);
3571
+ return Constructor;
3572
+ };
3573
+ }();
3574
+ function _classCallCheck(instance, Constructor) {
3575
+ if (!(instance instanceof Constructor)) {
3576
+ throw new TypeError("Cannot call a class as a function");
3577
+ }
3578
+ }
3579
+ var Operator = function() {
3580
+ function Operator2(name, cb, factValueValidator) {
3581
+ _classCallCheck(this, Operator2);
3582
+ this.name = String(name);
3583
+ if (!name) throw new Error("Missing operator name");
3584
+ if (typeof cb !== "function") throw new Error("Missing operator callback");
3585
+ this.cb = cb;
3586
+ this.factValueValidator = factValueValidator;
3587
+ if (!this.factValueValidator) this.factValueValidator = function() {
3588
+ return true;
3589
+ };
3590
+ }
3591
+ _createClass(Operator2, [{
3592
+ key: "evaluate",
3593
+ value: function evaluate(factValue, jsonValue) {
3594
+ return this.factValueValidator(factValue) && this.cb(factValue, jsonValue);
3595
+ }
3596
+ }]);
3597
+ return Operator2;
3598
+ }();
3599
+ exports.default = Operator;
3600
+ }
3601
+ });
3602
+
3603
+ // ../../node_modules/json-rules-engine/dist/errors.js
3604
+ var require_errors = __commonJS({
3605
+ "../../node_modules/json-rules-engine/dist/errors.js"(exports) {
3606
+ "use strict";
3607
+ Object.defineProperty(exports, "__esModule", {
3608
+ value: true
3609
+ });
3610
+ function _classCallCheck(instance, Constructor) {
3611
+ if (!(instance instanceof Constructor)) {
3612
+ throw new TypeError("Cannot call a class as a function");
3613
+ }
3614
+ }
3615
+ function _possibleConstructorReturn(self2, call) {
3616
+ if (!self2) {
3617
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
3618
+ }
3619
+ return call && (typeof call === "object" || typeof call === "function") ? call : self2;
3620
+ }
3621
+ function _inherits(subClass, superClass) {
3622
+ if (typeof superClass !== "function" && superClass !== null) {
3623
+ throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
3624
+ }
3625
+ subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });
3626
+ if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
3627
+ }
3628
+ var UndefinedFactError = exports.UndefinedFactError = function(_Error) {
3629
+ _inherits(UndefinedFactError2, _Error);
3630
+ function UndefinedFactError2() {
3631
+ var _ref;
3632
+ _classCallCheck(this, UndefinedFactError2);
3633
+ for (var _len = arguments.length, props = Array(_len), _key = 0; _key < _len; _key++) {
3634
+ props[_key] = arguments[_key];
3635
+ }
3636
+ var _this = _possibleConstructorReturn(this, (_ref = UndefinedFactError2.__proto__ || Object.getPrototypeOf(UndefinedFactError2)).call.apply(_ref, [this].concat(props)));
3637
+ _this.code = "UNDEFINED_FACT";
3638
+ return _this;
3639
+ }
3640
+ return UndefinedFactError2;
3641
+ }(Error);
3642
+ }
3643
+ });
3644
+
3645
+ // ../../node_modules/fast-bind/bind-loop.js
3646
+ var require_bind_loop = __commonJS({
3647
+ "../../node_modules/fast-bind/bind-loop.js"(exports, module) {
3648
+ "use strict";
3649
+ module.exports = function(boundThis) {
3650
+ var f = this, ret;
3651
+ if (arguments.length < 2)
3652
+ ret = function() {
3653
+ if (this instanceof ret) {
3654
+ var ret_ = f.apply(this, arguments);
3655
+ return Object(ret_) === ret_ ? ret_ : this;
3656
+ } else
3657
+ return f.apply(boundThis, arguments);
3658
+ };
3659
+ else {
3660
+ var boundArgs = new Array(arguments.length - 1);
3661
+ for (var i = 1; i < arguments.length; i++)
3662
+ boundArgs[i - 1] = arguments[i];
3663
+ ret = function() {
3664
+ var boundLen = boundArgs.length, args = new Array(boundLen + arguments.length), i2;
3665
+ for (i2 = 0; i2 < boundLen; i2++)
3666
+ args[i2] = boundArgs[i2];
3667
+ for (i2 = 0; i2 < arguments.length; i2++)
3668
+ args[boundLen + i2] = arguments[i2];
3669
+ if (this instanceof ret) {
3670
+ var ret_ = f.apply(this, args);
3671
+ return Object(ret_) === ret_ ? ret_ : this;
3672
+ } else
3673
+ return f.apply(boundThis, args);
3674
+ };
3675
+ }
3676
+ ret.prototype = f.prototype;
3677
+ return ret;
3678
+ };
3679
+ }
3680
+ });
3681
+
3682
+ // ../../node_modules/curry2/index.js
3683
+ var require_curry2 = __commonJS({
3684
+ "../../node_modules/curry2/index.js"(exports, module) {
3685
+ "use strict";
3686
+ var bind = Function.prototype.bind || require_bind_loop();
3687
+ module.exports = curry2;
3688
+ function curry2(fn, self2) {
3689
+ var out = function() {
3690
+ if (arguments.length === 0) return out;
3691
+ return arguments.length > 1 ? fn.apply(self2, arguments) : bind.call(fn, self2, arguments[0]);
3692
+ };
3693
+ out.uncurry = function uncurry() {
3694
+ return fn;
3695
+ };
3696
+ return out;
3697
+ }
3698
+ }
3699
+ });
3700
+
3701
+ // ../../node_modules/brackets2dots/index.js
3702
+ var require_brackets2dots = __commonJS({
3703
+ "../../node_modules/brackets2dots/index.js"(exports, module) {
3704
+ "use strict";
3705
+ module.exports = brackets2dots;
3706
+ var REPLACE_BRACKETS = /\[([^\[\]]+)\]/g;
3707
+ var LFT_RT_TRIM_DOTS = /^[.]*|[.]*$/g;
3708
+ function brackets2dots(string) {
3709
+ return {}.toString.call(string) == "[object String]" ? string.replace(REPLACE_BRACKETS, ".$1").replace(LFT_RT_TRIM_DOTS, "") : "";
3710
+ }
3711
+ }
3712
+ });
3713
+
3714
+ // ../../node_modules/dotsplit.js/index.js
3715
+ var require_dotsplit = __commonJS({
3716
+ "../../node_modules/dotsplit.js/index.js"(exports, module) {
3717
+ "use strict";
3718
+ var toString2 = Object.prototype.toString;
3719
+ function dotsplit(string) {
3720
+ var idx = -1;
3721
+ var str = compact(normalize(string).split("."));
3722
+ var end = str.length;
3723
+ var out = [];
3724
+ while (++idx < end) {
3725
+ out.push(todots(str[idx]));
3726
+ }
3727
+ return out;
3728
+ }
3729
+ function normalize(string) {
3730
+ return (toString2.call(string) === "[object String]" ? string : "").replace(/\\\./g, "\uFFFF");
3731
+ }
3732
+ function compact(arr) {
3733
+ var idx = -1;
3734
+ var end = arr.length;
3735
+ var out = [];
3736
+ while (++idx < end) {
3737
+ if (arr[idx]) out.push(arr[idx]);
3738
+ }
3739
+ return out;
3740
+ }
3741
+ function todots(string) {
3742
+ return string.replace(/\uffff/g, ".");
3743
+ }
3744
+ module.exports = dotsplit;
3745
+ }
3746
+ });
3747
+
3748
+ // ../../node_modules/selectn/index.js
3749
+ var require_selectn = __commonJS({
3750
+ "../../node_modules/selectn/index.js"(exports, module) {
3751
+ "use strict";
3752
+ var curry2 = require_curry2();
3753
+ var dotted = require_brackets2dots();
3754
+ var splits = require_dotsplit();
3755
+ var string = Object.prototype.toString;
3756
+ module.exports = curry2(selectn);
3757
+ function selectn(path, object) {
3758
+ let idx = -1;
3759
+ const seg = string.call(path) === "[object Array]" ? path : splits(dotted(path));
3760
+ const end = seg.length;
3761
+ let ref = end ? object : void 0;
3762
+ while (++idx < end) {
3763
+ if (Object(ref) !== ref) return void 0;
3764
+ ref = ref[seg[idx]];
3765
+ }
3766
+ return typeof ref === "function" ? ref() : ref;
3767
+ }
3768
+ }
3769
+ });
3770
+
3771
+ // ../../node_modules/json-rules-engine/dist/almanac.js
3772
+ var require_almanac = __commonJS({
3773
+ "../../node_modules/json-rules-engine/dist/almanac.js"(exports) {
3774
+ "use strict";
3775
+ Object.defineProperty(exports, "__esModule", {
3776
+ value: true
3777
+ });
3778
+ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
3779
+ return typeof obj;
3780
+ } : function(obj) {
3781
+ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
3782
+ };
3783
+ var _createClass = /* @__PURE__ */ function() {
3784
+ function defineProperties(target, props) {
3785
+ for (var i = 0; i < props.length; i++) {
3786
+ var descriptor = props[i];
3787
+ descriptor.enumerable = descriptor.enumerable || false;
3788
+ descriptor.configurable = true;
3789
+ if ("value" in descriptor) descriptor.writable = true;
3790
+ Object.defineProperty(target, descriptor.key, descriptor);
3791
+ }
3792
+ }
3793
+ return function(Constructor, protoProps, staticProps) {
3794
+ if (protoProps) defineProperties(Constructor.prototype, protoProps);
3795
+ if (staticProps) defineProperties(Constructor, staticProps);
3796
+ return Constructor;
3797
+ };
3798
+ }();
3799
+ var _fact = require_fact();
3800
+ var _fact2 = _interopRequireDefault(_fact);
3801
+ var _errors = require_errors();
3802
+ var _debug = require_debug();
3803
+ var _debug2 = _interopRequireDefault(_debug);
3804
+ var _selectn = require_selectn();
3805
+ var _selectn2 = _interopRequireDefault(_selectn);
3806
+ var _lodash = require_lodash();
3807
+ var _lodash2 = _interopRequireDefault(_lodash);
3808
+ function _interopRequireDefault(obj) {
3809
+ return obj && obj.__esModule ? obj : { default: obj };
3810
+ }
3811
+ function _classCallCheck(instance, Constructor) {
3812
+ if (!(instance instanceof Constructor)) {
3813
+ throw new TypeError("Cannot call a class as a function");
3814
+ }
3815
+ }
3816
+ var Almanac = function() {
3817
+ function Almanac2(factMap) {
3818
+ var runtimeFacts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
3819
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
3820
+ _classCallCheck(this, Almanac2);
3821
+ this.factMap = new Map(factMap);
3822
+ this.factResultsCache = /* @__PURE__ */ new Map();
3823
+ this.allowUndefinedFacts = Boolean(options.allowUndefinedFacts);
3824
+ for (var factId in runtimeFacts) {
3825
+ var fact = void 0;
3826
+ if (runtimeFacts[factId] instanceof _fact2.default) {
3827
+ fact = runtimeFacts[factId];
3828
+ } else {
3829
+ fact = new _fact2.default(factId, runtimeFacts[factId]);
3830
+ }
3831
+ this._addConstantFact(fact);
3832
+ (0, _debug2.default)("almanac::constructor initialized runtime fact:" + fact.id + " with " + fact.value + "<" + _typeof(fact.value) + ">");
3833
+ }
3834
+ }
3835
+ _createClass(Almanac2, [{
3836
+ key: "_getFact",
3837
+ value: function _getFact(factId) {
3838
+ return this.factMap.get(factId);
3839
+ }
3840
+ /**
3841
+ * Registers fact with the almanac
3842
+ * @param {[type]} fact [description]
3843
+ */
3844
+ }, {
3845
+ key: "_addConstantFact",
3846
+ value: function _addConstantFact(fact) {
3847
+ this.factMap.set(fact.id, fact);
3848
+ this._setFactValue(fact, {}, fact.value);
3849
+ }
3850
+ /**
3851
+ * Sets the computed value of a fact
3852
+ * @param {Fact} fact
3853
+ * @param {Object} params - values for differentiating this fact value from others, used for cache key
3854
+ * @param {Mixed} value - computed value
3855
+ */
3856
+ }, {
3857
+ key: "_setFactValue",
3858
+ value: function _setFactValue(fact, params, value) {
3859
+ var cacheKey = fact.getCacheKey(params);
3860
+ var factValue = Promise.resolve(value);
3861
+ if (cacheKey) {
3862
+ this.factResultsCache.set(cacheKey, factValue);
3863
+ }
3864
+ return factValue;
3865
+ }
3866
+ /**
3867
+ * Adds a constant fact during runtime. Can be used mid-run() to add additional information
3868
+ * @param {String} fact - fact identifier
3869
+ * @param {Mixed} value - constant value of the fact
3870
+ */
3871
+ }, {
3872
+ key: "addRuntimeFact",
3873
+ value: function addRuntimeFact(factId, value) {
3874
+ var fact = new _fact2.default(factId, value);
3875
+ return this._addConstantFact(fact);
3876
+ }
3877
+ /**
3878
+ * Returns the value of a fact, based on the given parameters. Utilizes the 'almanac' maintained
3879
+ * by the engine, which cache's fact computations based on parameters provided
3880
+ * @param {string} factId - fact identifier
3881
+ * @param {Object} params - parameters to feed into the fact. By default, these will also be used to compute the cache key
3882
+ * @param {String} path - object
3883
+ * @return {Promise} a promise which will resolve with the fact computation.
3884
+ */
3885
+ }, {
3886
+ key: "factValue",
3887
+ value: function factValue(factId) {
3888
+ var params = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
3889
+ var path = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "";
3890
+ var factValuePromise = void 0;
3891
+ var fact = this._getFact(factId);
3892
+ if (fact === void 0) {
3893
+ if (this.allowUndefinedFacts) {
3894
+ return Promise.resolve(void 0);
3895
+ } else {
3896
+ return Promise.reject(new _errors.UndefinedFactError("Undefined fact: " + factId));
3897
+ }
3898
+ }
3899
+ if (fact.isConstant()) {
3900
+ factValuePromise = Promise.resolve(fact.calculate(params, this));
3901
+ } else {
3902
+ var cacheKey = fact.getCacheKey(params);
3903
+ var cacheVal = cacheKey && this.factResultsCache.get(cacheKey);
3904
+ if (cacheVal) {
3905
+ factValuePromise = Promise.resolve(cacheVal);
3906
+ (0, _debug2.default)("almanac::factValue cache hit for fact:" + factId);
3907
+ } else {
3908
+ (0, _debug2.default)("almanac::factValue cache miss for fact:" + factId + "; calculating");
3909
+ factValuePromise = this._setFactValue(fact, params, fact.calculate(params, this));
3910
+ }
3911
+ }
3912
+ if (path) {
3913
+ return factValuePromise.then(function(factValue2) {
3914
+ if ((0, _lodash2.default)(factValue2)) {
3915
+ var pathValue = (0, _selectn2.default)(path)(factValue2);
3916
+ (0, _debug2.default)("condition::evaluate extracting object property " + path + ", received: " + pathValue);
3917
+ return pathValue;
3918
+ } else {
3919
+ (0, _debug2.default)("condition::evaluate could not compute object path(" + path + ") of non-object: " + factValue2 + " <" + (typeof factValue2 === "undefined" ? "undefined" : _typeof(factValue2)) + ">; continuing with " + factValue2);
3920
+ return factValue2;
3921
+ }
3922
+ });
3923
+ }
3924
+ return factValuePromise;
3925
+ }
3926
+ }]);
3927
+ return Almanac2;
3928
+ }();
3929
+ exports.default = Almanac;
3930
+ }
3931
+ });
3932
+
3933
+ // ../../node_modules/json-rules-engine/dist/engine-facts.js
3934
+ var require_engine_facts = __commonJS({
3935
+ "../../node_modules/json-rules-engine/dist/engine-facts.js"(exports) {
3936
+ "use strict";
3937
+ Object.defineProperty(exports, "__esModule", {
3938
+ value: true
3939
+ });
3940
+ var SuccessEventFact = function SuccessEventFact2() {
3941
+ var successTriggers = [];
3942
+ return function() {
3943
+ var params = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
3944
+ if (params.event) {
3945
+ successTriggers.push(params.event);
3946
+ }
3947
+ return successTriggers;
3948
+ };
3949
+ };
3950
+ exports.SuccessEventFact = SuccessEventFact;
3951
+ }
3952
+ });
3953
+
3954
+ // ../../node_modules/json-rules-engine/dist/engine-default-operators.js
3955
+ var require_engine_default_operators = __commonJS({
3956
+ "../../node_modules/json-rules-engine/dist/engine-default-operators.js"(exports) {
3957
+ "use strict";
3958
+ Object.defineProperty(exports, "__esModule", {
3959
+ value: true
3960
+ });
3961
+ var _operator = require_operator();
3962
+ var _operator2 = _interopRequireDefault(_operator);
3963
+ function _interopRequireDefault(obj) {
3964
+ return obj && obj.__esModule ? obj : { default: obj };
3965
+ }
3966
+ var Operators = [];
3967
+ Operators.push(new _operator2.default("equal", function(a, b) {
3968
+ return a === b;
3969
+ }));
3970
+ Operators.push(new _operator2.default("notEqual", function(a, b) {
3971
+ return a !== b;
3972
+ }));
3973
+ Operators.push(new _operator2.default("in", function(a, b) {
3974
+ return b.indexOf(a) > -1;
3975
+ }));
3976
+ Operators.push(new _operator2.default("notIn", function(a, b) {
3977
+ return b.indexOf(a) === -1;
3978
+ }));
3979
+ Operators.push(new _operator2.default("contains", function(a, b) {
3980
+ return a.indexOf(b) > -1;
3981
+ }, Array.isArray));
3982
+ Operators.push(new _operator2.default("doesNotContain", function(a, b) {
3983
+ return a.indexOf(b) === -1;
3984
+ }, Array.isArray));
3985
+ function numberValidator(factValue) {
3986
+ return Number.parseFloat(factValue).toString() !== "NaN";
3987
+ }
3988
+ Operators.push(new _operator2.default("lessThan", function(a, b) {
3989
+ return a < b;
3990
+ }, numberValidator));
3991
+ Operators.push(new _operator2.default("lessThanInclusive", function(a, b) {
3992
+ return a <= b;
3993
+ }, numberValidator));
3994
+ Operators.push(new _operator2.default("greaterThan", function(a, b) {
3995
+ return a > b;
3996
+ }, numberValidator));
3997
+ Operators.push(new _operator2.default("greaterThanInclusive", function(a, b) {
3998
+ return a >= b;
3999
+ }, numberValidator));
4000
+ exports.default = Operators;
4001
+ }
4002
+ });
4003
+
4004
+ // ../../node_modules/json-rules-engine/dist/engine.js
4005
+ var require_engine = __commonJS({
4006
+ "../../node_modules/json-rules-engine/dist/engine.js"(exports) {
4007
+ "use strict";
4008
+ Object.defineProperty(exports, "__esModule", {
4009
+ value: true
4010
+ });
4011
+ exports.FINISHED = exports.RUNNING = exports.READY = void 0;
4012
+ var _createClass = /* @__PURE__ */ function() {
4013
+ function defineProperties(target, props) {
4014
+ for (var i = 0; i < props.length; i++) {
4015
+ var descriptor = props[i];
4016
+ descriptor.enumerable = descriptor.enumerable || false;
4017
+ descriptor.configurable = true;
4018
+ if ("value" in descriptor) descriptor.writable = true;
4019
+ Object.defineProperty(target, descriptor.key, descriptor);
4020
+ }
4021
+ }
4022
+ return function(Constructor, protoProps, staticProps) {
4023
+ if (protoProps) defineProperties(Constructor.prototype, protoProps);
4024
+ if (staticProps) defineProperties(Constructor, staticProps);
4025
+ return Constructor;
4026
+ };
4027
+ }();
4028
+ var _fact = require_fact();
4029
+ var _fact2 = _interopRequireDefault(_fact);
4030
+ var _rule = require_rule();
4031
+ var _rule2 = _interopRequireDefault(_rule);
4032
+ var _operator = require_operator();
4033
+ var _operator2 = _interopRequireDefault(_operator);
4034
+ var _almanac = require_almanac();
4035
+ var _almanac2 = _interopRequireDefault(_almanac);
4036
+ var _events = require_events();
4037
+ var _engineFacts = require_engine_facts();
4038
+ var _engineDefaultOperators = require_engine_default_operators();
4039
+ var _engineDefaultOperators2 = _interopRequireDefault(_engineDefaultOperators);
4040
+ var _debug = require_debug();
4041
+ var _debug2 = _interopRequireDefault(_debug);
4042
+ function _interopRequireDefault(obj) {
4043
+ return obj && obj.__esModule ? obj : { default: obj };
4044
+ }
4045
+ function _classCallCheck(instance, Constructor) {
4046
+ if (!(instance instanceof Constructor)) {
4047
+ throw new TypeError("Cannot call a class as a function");
4048
+ }
4049
+ }
4050
+ function _possibleConstructorReturn(self2, call) {
4051
+ if (!self2) {
4052
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
4053
+ }
4054
+ return call && (typeof call === "object" || typeof call === "function") ? call : self2;
4055
+ }
4056
+ function _inherits(subClass, superClass) {
4057
+ if (typeof superClass !== "function" && superClass !== null) {
4058
+ throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
4059
+ }
4060
+ subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });
4061
+ if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
4062
+ }
4063
+ var READY = exports.READY = "READY";
4064
+ var RUNNING = exports.RUNNING = "RUNNING";
4065
+ var FINISHED = exports.FINISHED = "FINISHED";
4066
+ var Engine2 = function(_EventEmitter) {
4067
+ _inherits(Engine3, _EventEmitter);
4068
+ function Engine3() {
4069
+ var rules = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
4070
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
4071
+ _classCallCheck(this, Engine3);
4072
+ var _this = _possibleConstructorReturn(this, (Engine3.__proto__ || Object.getPrototypeOf(Engine3)).call(this));
4073
+ _this.rules = [];
4074
+ _this.allowUndefinedFacts = options.allowUndefinedFacts || false;
4075
+ _this.operators = /* @__PURE__ */ new Map();
4076
+ _this.facts = /* @__PURE__ */ new Map();
4077
+ _this.status = READY;
4078
+ rules.map(function(r) {
4079
+ return _this.addRule(r);
4080
+ });
4081
+ _engineDefaultOperators2.default.map(function(o) {
4082
+ return _this.addOperator(o);
4083
+ });
4084
+ return _this;
4085
+ }
4086
+ _createClass(Engine3, [{
4087
+ key: "addRule",
4088
+ value: function addRule(properties) {
4089
+ if (!properties) throw new Error("Engine: addRule() requires options");
4090
+ if (!properties.hasOwnProperty("conditions")) throw new Error('Engine: addRule() argument requires "conditions" property');
4091
+ if (!properties.hasOwnProperty("event")) throw new Error('Engine: addRule() argument requires "event" property');
4092
+ var rule = void 0;
4093
+ if (properties instanceof _rule2.default) {
4094
+ rule = properties;
4095
+ } else {
4096
+ rule = new _rule2.default(properties);
4097
+ }
4098
+ rule.setEngine(this);
4099
+ this.rules.push(rule);
4100
+ this.prioritizedRules = null;
4101
+ return this;
4102
+ }
4103
+ /**
4104
+ * Remove a rule from the engine
4105
+ * @param {object|Rule} rule - rule definition. Must be a instance of Rule
4106
+ */
4107
+ }, {
4108
+ key: "removeRule",
4109
+ value: function removeRule(rule) {
4110
+ if (rule instanceof _rule2.default === false) throw new Error("Engine: removeRule() rule must be a instance of Rule");
4111
+ var index = this.rules.indexOf(rule);
4112
+ if (index === -1) return false;
4113
+ this.prioritizedRules = null;
4114
+ return Boolean(this.rules.splice(index, 1).length);
4115
+ }
4116
+ /**
4117
+ * Add a custom operator definition
4118
+ * @param {string} operatorOrName - operator identifier within the condition; i.e. instead of 'equals', 'greaterThan', etc
4119
+ * @param {function(factValue, jsonValue)} callback - the method to execute when the operator is encountered.
4120
+ */
4121
+ }, {
4122
+ key: "addOperator",
4123
+ value: function addOperator(operatorOrName, cb) {
4124
+ var operator = void 0;
4125
+ if (operatorOrName instanceof _operator2.default) {
4126
+ operator = operatorOrName;
4127
+ } else {
4128
+ operator = new _operator2.default(operatorOrName, cb);
4129
+ }
4130
+ (0, _debug2.default)("engine::addOperator name:" + operator.name);
4131
+ this.operators.set(operator.name, operator);
4132
+ }
4133
+ /**
4134
+ * Remove a custom operator definition
4135
+ * @param {string} operatorOrName - operator identifier within the condition; i.e. instead of 'equals', 'greaterThan', etc
4136
+ * @param {function(factValue, jsonValue)} callback - the method to execute when the operator is encountered.
4137
+ */
4138
+ }, {
4139
+ key: "removeOperator",
4140
+ value: function removeOperator(operatorOrName) {
4141
+ var operatorName = void 0;
4142
+ if (operatorOrName instanceof _operator2.default) {
4143
+ operatorName = operatorOrName.name;
4144
+ } else {
4145
+ operatorName = operatorOrName;
4146
+ }
4147
+ return this.operators.delete(operatorName);
4148
+ }
4149
+ /**
4150
+ * Add a fact definition to the engine. Facts are called by rules as they are evaluated.
4151
+ * @param {object|Fact} id - fact identifier or instance of Fact
4152
+ * @param {function} definitionFunc - function to be called when computing the fact value for a given rule
4153
+ * @param {Object} options - options to initialize the fact with. used when "id" is not a Fact instance
4154
+ */
4155
+ }, {
4156
+ key: "addFact",
4157
+ value: function addFact(id, valueOrMethod, options) {
4158
+ var factId = id;
4159
+ var fact = void 0;
4160
+ if (id instanceof _fact2.default) {
4161
+ factId = id.id;
4162
+ fact = id;
4163
+ } else {
4164
+ fact = new _fact2.default(id, valueOrMethod, options);
4165
+ }
4166
+ (0, _debug2.default)("engine::addFact id:" + factId);
4167
+ this.facts.set(factId, fact);
4168
+ return this;
4169
+ }
4170
+ /**
4171
+ * Add a fact definition to the engine. Facts are called by rules as they are evaluated.
4172
+ * @param {object|Fact} id - fact identifier or instance of Fact
4173
+ */
4174
+ }, {
4175
+ key: "removeFact",
4176
+ value: function removeFact(factOrId) {
4177
+ var factId = void 0;
4178
+ if (!(factOrId instanceof _fact2.default)) {
4179
+ factId = factOrId;
4180
+ } else {
4181
+ factId = factOrId.id;
4182
+ }
4183
+ return this.facts.delete(factId);
4184
+ }
4185
+ /**
4186
+ * Iterates over the engine rules, organizing them by highest -> lowest priority
4187
+ * @return {Rule[][]} two dimensional array of Rules.
4188
+ * Each outer array element represents a single priority(integer). Inner array is
4189
+ * all rules with that priority.
4190
+ */
4191
+ }, {
4192
+ key: "prioritizeRules",
4193
+ value: function prioritizeRules() {
4194
+ if (!this.prioritizedRules) {
4195
+ var ruleSets = this.rules.reduce(function(sets, rule) {
4196
+ var priority = rule.priority;
4197
+ if (!sets[priority]) sets[priority] = [];
4198
+ sets[priority].push(rule);
4199
+ return sets;
4200
+ }, {});
4201
+ this.prioritizedRules = Object.keys(ruleSets).sort(function(a, b) {
4202
+ return Number(a) > Number(b) ? -1 : 1;
4203
+ }).map(function(priority) {
4204
+ return ruleSets[priority];
4205
+ });
4206
+ }
4207
+ return this.prioritizedRules;
4208
+ }
4209
+ /**
4210
+ * Stops the rules engine from running the next priority set of Rules. All remaining rules will be resolved as undefined,
4211
+ * and no further events emitted. Since rules of the same priority are evaluated in parallel(not series), other rules of
4212
+ * the same priority may still emit events, even though the engine is in a "finished" state.
4213
+ * @return {Engine}
4214
+ */
4215
+ }, {
4216
+ key: "stop",
4217
+ value: function stop() {
4218
+ this.status = FINISHED;
4219
+ return this;
4220
+ }
4221
+ /**
4222
+ * Returns a fact by fact-id
4223
+ * @param {string} factId - fact identifier
4224
+ * @return {Fact} fact instance, or undefined if no such fact exists
4225
+ */
4226
+ }, {
4227
+ key: "getFact",
4228
+ value: function getFact(factId) {
4229
+ return this.facts.get(factId);
4230
+ }
4231
+ /**
4232
+ * Runs an array of rules
4233
+ * @param {Rule[]} array of rules to be evaluated
4234
+ * @return {Promise} resolves when all rules in the array have been evaluated
4235
+ */
4236
+ }, {
4237
+ key: "evaluateRules",
4238
+ value: function evaluateRules(ruleArray, almanac) {
4239
+ var _this2 = this;
4240
+ return Promise.all(ruleArray.map(function(rule) {
4241
+ if (_this2.status !== RUNNING) {
4242
+ (0, _debug2.default)("engine::run status:" + _this2.status + "; skipping remaining rules");
4243
+ return;
4244
+ }
4245
+ return rule.evaluate(almanac).then(function(ruleResult) {
4246
+ (0, _debug2.default)("engine::run ruleResult:" + ruleResult.result);
4247
+ if (ruleResult.result) {
4248
+ _this2.emit("success", rule.event, almanac, ruleResult);
4249
+ _this2.emit(rule.event.type, rule.event.params, almanac, ruleResult);
4250
+ almanac.factValue("success-events", { event: rule.event });
4251
+ } else {
4252
+ _this2.emit("failure", rule.event, almanac, ruleResult);
4253
+ }
4254
+ });
4255
+ }));
4256
+ }
4257
+ /**
4258
+ * Runs the rules engine
4259
+ * @param {Object} runtimeFacts - fact values known at runtime
4260
+ * @param {Object} runOptions - run options
4261
+ * @return {Promise} resolves when the engine has completed running
4262
+ */
4263
+ }, {
4264
+ key: "run",
4265
+ value: function run() {
4266
+ var _this3 = this;
4267
+ var runtimeFacts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
4268
+ (0, _debug2.default)("engine::run started");
4269
+ (0, _debug2.default)("engine::run runtimeFacts:", runtimeFacts);
4270
+ runtimeFacts["success-events"] = new _fact2.default("success-events", (0, _engineFacts.SuccessEventFact)(), { cache: false });
4271
+ this.status = RUNNING;
4272
+ var almanac = new _almanac2.default(this.facts, runtimeFacts, { allowUndefinedFacts: this.allowUndefinedFacts });
4273
+ var orderedSets = this.prioritizeRules();
4274
+ var cursor = Promise.resolve();
4275
+ return new Promise(function(resolve, reject) {
4276
+ orderedSets.map(function(set) {
4277
+ cursor = cursor.then(function() {
4278
+ return _this3.evaluateRules(set, almanac);
4279
+ }).catch(reject);
4280
+ return cursor;
4281
+ });
4282
+ cursor.then(function() {
4283
+ _this3.status = FINISHED;
4284
+ (0, _debug2.default)("engine::run completed");
4285
+ return almanac.factValue("success-events");
4286
+ }).then(function(events) {
4287
+ resolve({
4288
+ events,
4289
+ almanac
4290
+ });
4291
+ }).catch(reject);
4292
+ });
4293
+ }
4294
+ }]);
4295
+ return Engine3;
4296
+ }(_events.EventEmitter);
4297
+ exports.default = Engine2;
4298
+ }
4299
+ });
4300
+
4301
+ // ../../node_modules/json-rules-engine/dist/json-rules-engine.js
4302
+ var require_json_rules_engine = __commonJS({
4303
+ "../../node_modules/json-rules-engine/dist/json-rules-engine.js"(exports) {
4304
+ "use strict";
4305
+ Object.defineProperty(exports, "__esModule", {
4306
+ value: true
4307
+ });
4308
+ exports.Engine = exports.Operator = exports.Rule = exports.Fact = void 0;
4309
+ exports.default = function(rules, options) {
4310
+ return new _engine2.default(rules, options);
4311
+ };
4312
+ var _engine = require_engine();
4313
+ var _engine2 = _interopRequireDefault(_engine);
4314
+ var _fact = require_fact();
4315
+ var _fact2 = _interopRequireDefault(_fact);
4316
+ var _rule = require_rule();
4317
+ var _rule2 = _interopRequireDefault(_rule);
4318
+ var _operator = require_operator();
4319
+ var _operator2 = _interopRequireDefault(_operator);
4320
+ function _interopRequireDefault(obj) {
4321
+ return obj && obj.__esModule ? obj : { default: obj };
4322
+ }
4323
+ exports.Fact = _fact2.default;
4324
+ exports.Rule = _rule2.default;
4325
+ exports.Operator = _operator2.default;
4326
+ exports.Engine = _engine2.default;
4327
+ }
4328
+ });
4329
+
4330
+ // ../../node_modules/json-rules-engine/dist/index.js
4331
+ var require_dist = __commonJS({
4332
+ "../../node_modules/json-rules-engine/dist/index.js"(exports, module) {
4333
+ "use strict";
4334
+ module.exports = require_json_rules_engine();
4335
+ }
4336
+ });
4337
+
4338
+ // ../packlytics/dist/utils/get-packlytics-id.js
4339
+ function sha256(ascii) {
4340
+ function rightRotate(value, amount) {
4341
+ return value >>> amount | value << 32 - amount;
4342
+ }
4343
+ const mathPow = Math.pow;
4344
+ const maxWord = mathPow(2, 32);
4345
+ const lengthProperty = "length";
4346
+ let i, j;
4347
+ let result = "";
4348
+ const words = [];
4349
+ const asciiBitLength = ascii[lengthProperty] * 8;
4350
+ let hash2 = sha256.h = sha256.h || [];
4351
+ const k = sha256.k = sha256.k || [];
4352
+ let primeCounter = k[lengthProperty];
4353
+ const isComposite = {};
4354
+ for (let candidate = 2; primeCounter < 64; candidate++) {
4355
+ if (!isComposite[candidate]) {
4356
+ for (i = 0; i < 313; i += candidate) {
4357
+ isComposite[i] = candidate;
4358
+ }
4359
+ hash2[primeCounter] = mathPow(candidate, 0.5) * maxWord | 0;
4360
+ k[primeCounter++] = mathPow(candidate, 1 / 3) * maxWord | 0;
4361
+ }
4362
+ }
4363
+ ascii += "\x80";
4364
+ while (ascii[lengthProperty] % 64 - 56)
4365
+ ascii += "\0";
4366
+ for (i = 0; i < ascii[lengthProperty]; i++) {
4367
+ j = ascii.charCodeAt(i);
4368
+ if (j >> 8)
4369
+ return;
4370
+ words[i >> 2] |= j << (3 - i) % 4 * 8;
4371
+ }
4372
+ words[words[lengthProperty]] = asciiBitLength / maxWord | 0;
4373
+ words[words[lengthProperty]] = asciiBitLength;
4374
+ for (j = 0; j < words[lengthProperty]; ) {
4375
+ const w = words.slice(j, j += 16);
4376
+ const oldHash = hash2;
4377
+ hash2 = hash2.slice(0, 8);
4378
+ for (i = 0; i < 64; i++) {
4379
+ const i2 = i + j;
4380
+ const w15 = w[i - 15], w2 = w[i - 2];
4381
+ const a = hash2[0], e = hash2[4];
4382
+ const temp1 = hash2[7] + (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) + // S1
4383
+ (e & hash2[5] ^ ~e & hash2[6]) + // ch
4384
+ k[i] + // Expand the message schedule if needed
4385
+ (w[i] = i < 16 ? w[i] : w[i - 16] + (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ w15 >>> 3) + // s0
4386
+ w[i - 7] + (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ w2 >>> 10) | // s1
4387
+ 0);
4388
+ const temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) + // S0
4389
+ (a & hash2[1] ^ a & hash2[2] ^ hash2[1] & hash2[2]);
4390
+ hash2 = [temp1 + temp2 | 0].concat(hash2);
4391
+ hash2[4] = hash2[4] + temp1 | 0;
4392
+ }
4393
+ for (i = 0; i < 8; i++) {
4394
+ hash2[i] = hash2[i] + oldHash[i] | 0;
4395
+ }
4396
+ }
4397
+ for (i = 0; i < 8; i++) {
4398
+ for (j = 3; j + 1; j--) {
4399
+ const b = hash2[i] >> j * 8 & 255;
4400
+ result += (b < 16 ? 0 : "") + b.toString(16);
4401
+ }
4402
+ }
4403
+ return result;
4404
+ }
4405
+ function createHash(data) {
4406
+ const hash2 = sha256(data);
4407
+ return [
4408
+ hash2?.substring(0, 8),
4409
+ hash2?.substring(8, 12),
4410
+ hash2?.substring(12, 16),
4411
+ hash2?.substring(16, 20),
4412
+ hash2?.substring(20, 32)
4413
+ ].join("-");
4414
+ }
4415
+ function getPacklyticsId(data, secret) {
4416
+ const currentDate = /* @__PURE__ */ new Date();
4417
+ const formattedDate = currentDate.toLocaleDateString("en-US");
4418
+ const salt = sha256(formattedDate + secret);
4419
+ return createHash(data + salt);
4420
+ }
4421
+
4422
+ // ../../node_modules/intl-parse-accept-language/dist/intl-parse-accept-language.esm.js
4423
+ var defaultValidate = function defaultValidate2(locale) {
4424
+ return locale;
4425
+ };
4426
+ var parseAcceptLanguage = function parseAcceptLanguage2(languageHeaderValue, options) {
4427
+ if (options === void 0) {
4428
+ options = {};
4429
+ }
4430
+ if (!languageHeaderValue) return [];
4431
+ var _options = options, _options$ignoreWildca = _options.ignoreWildcard, ignoreWildcard = _options$ignoreWildca === void 0 ? true : _options$ignoreWildca, _options$validate = _options.validate, validate = _options$validate === void 0 ? defaultValidate : _options$validate;
4432
+ return languageHeaderValue.split(",").map(function(lang) {
4433
+ var _lang$split = lang.split(";"), locale = _lang$split[0], _lang$split$ = _lang$split[1], q = _lang$split$ === void 0 ? "q=1" : _lang$split$;
4434
+ var trimmedLocale = locale.trim();
4435
+ var numQ = Number(q.replace(/q ?=/, ""));
4436
+ if (isNaN(numQ)) return [0, trimmedLocale];
4437
+ return [numQ, trimmedLocale];
4438
+ }).sort(function(_ref, _ref2) {
4439
+ var q1 = _ref[0];
4440
+ var q2 = _ref2[0];
4441
+ return q2 - q1;
4442
+ }).flatMap(function(_ref3) {
4443
+ var locale = _ref3[1];
4444
+ if (locale === "*" && ignoreWildcard) return [];
4445
+ try {
4446
+ return validate(locale) || [];
4447
+ } catch (_unused) {
4448
+ return [];
4449
+ }
4450
+ });
4451
+ };
4452
+
4453
+ // ../packlytics/dist/utils/get-headers.js
4454
+ function getHeaders(requestOrHeaders) {
4455
+ if (requestOrHeaders instanceof Request) {
4456
+ return requestOrHeaders.headers;
4457
+ }
4458
+ return requestOrHeaders;
4459
+ }
4460
+
4461
+ // ../packlytics/dist/utils/get-client-locales.js
4462
+ function getClientLocales(requestOrHeaders) {
4463
+ let headers = getHeaders(requestOrHeaders);
4464
+ let acceptLanguage = headers.get("Accept-Language");
4465
+ if (!acceptLanguage)
4466
+ return void 0;
4467
+ let locales = parseAcceptLanguage(acceptLanguage, {
4468
+ validate: Intl.DateTimeFormat.supportedLocalesOf,
4469
+ ignoreWildcard: true
4470
+ });
4471
+ if (locales.length === 0)
4472
+ return void 0;
4473
+ return locales;
4474
+ }
4475
+
4476
+ // ../packlytics/dist/utils/sanatize-payload.js
4477
+ var sanitizePayload = (data) => {
4478
+ let dataStr = JSON.stringify(data);
1598
4479
  const sensitiveFields = [
1599
4480
  "username",
1600
4481
  "user",
@@ -1823,33 +4704,33 @@ import {
1823
4704
  } from "@shopify/remix-oxygen";
1824
4705
 
1825
4706
  // src/session/cookies-utils.tsx
1826
- var import_cookie2 = __toESM(require_cookie());
4707
+ var import_cookie2 = __toESM(require_cookie(), 1);
1827
4708
  var tokenHash = "xxxx-4xxx-xxxx-xxxxxxxxxxxx";
1828
4709
  function hasUserConsent(request) {
1829
4710
  const cookies = import_cookie2.default.parse(request.headers.get("Cookie"));
1830
4711
  return cookies[PACK_USER_CONSENT_COOKIE_ID] ? cookies[PACK_USER_CONSENT_COOKIE_ID] === "true" : true;
1831
4712
  }
1832
4713
  function buildRandomUUID() {
1833
- let hash = "";
4714
+ let hash2 = "";
1834
4715
  try {
1835
4716
  const crypto2 = window.crypto;
1836
4717
  const randomValuesArray = new Uint16Array(31);
1837
4718
  crypto2.getRandomValues(randomValuesArray);
1838
4719
  let i = 0;
1839
- hash = tokenHash.replace(/[x]/g, (c) => {
4720
+ hash2 = tokenHash.replace(/[x]/g, (c) => {
1840
4721
  const r = randomValuesArray[i] % 16;
1841
4722
  const v = c === "x" ? r : r & 3 | 8;
1842
4723
  i++;
1843
4724
  return v.toString(16);
1844
4725
  });
1845
4726
  } catch (err) {
1846
- hash = tokenHash.replace(/[x]/g, (c) => {
4727
+ hash2 = tokenHash.replace(/[x]/g, (c) => {
1847
4728
  const r = Math.random() * 16 | 0;
1848
4729
  const v = c === "x" ? r : r & 3 | 8;
1849
4730
  return v.toString(16);
1850
4731
  });
1851
4732
  }
1852
- return `${hexTime()}-${hash}`;
4733
+ return `${hexTime()}-${hash2}`;
1853
4734
  }
1854
4735
  function hexTime() {
1855
4736
  let dateNumber = 0;
@@ -1923,6 +4804,8 @@ import {
1923
4804
  createCookie as createCookie2,
1924
4805
  createCookieSessionStorage as createCookieSessionStorage2
1925
4806
  } from "@shopify/remix-oxygen";
4807
+ var import_debug = __toESM(require_browser(), 1);
4808
+ var debug = (0, import_debug.default)("pack:ab-testing:test-session");
1926
4809
  function isSafari2(userAgent) {
1927
4810
  if (!userAgent) return false;
1928
4811
  return /Safari\//.test(userAgent) && !/Chrome\//.test(userAgent) && !/Chromium\//.test(userAgent) && !/Edg\//.test(userAgent) && !/Firefox\//.test(userAgent);
@@ -1939,11 +4822,17 @@ var PackTestSession = class {
1939
4822
  this.#sessionStorage = sessionStorage;
1940
4823
  this.#initialData = {
1941
4824
  test_data: this.#session.get("test_data"),
1942
- test_expire_at: this.#session.get("test_expire_at")
4825
+ test_expire_at: this.#session.get("test_expire_at"),
4826
+ test_rules_cache: this.#session.get("test_rules_cache"),
4827
+ test_rules_cache_timestamp: this.#session.get("test_rules_cache_timestamp")
1943
4828
  };
1944
4829
  }
1945
4830
  static async init(request, secrets) {
1946
4831
  const userAgent = request.headers.get("User-Agent");
4832
+ debug("[PackTestSession.init] Initializing test session", {
4833
+ hasSecrets: secrets.length > 0,
4834
+ userAgent: userAgent?.substring(0, 50)
4835
+ });
1947
4836
  const storage = createCookieSessionStorage2({
1948
4837
  cookie: createCookie2(PACK_TEST_COOKIE_ID, {
1949
4838
  secure: isSafari2(userAgent) && process.env.NODE_ENV === "development" ? false : true,
@@ -1958,24 +4847,60 @@ var PackTestSession = class {
1958
4847
  if (!sessionId) {
1959
4848
  sessionId = crypto.randomUUID();
1960
4849
  session.set("test_session_id", sessionId);
4850
+ debug("[PackTestSession.init] Generated new session ID", { sessionId });
4851
+ } else {
4852
+ debug("[PackTestSession.init] Using existing session ID", { sessionId });
1961
4853
  }
1962
4854
  return new this(sessionId, storage, session);
1963
4855
  }
1964
4856
  getTestData() {
1965
- return this.#session.get("test_data");
4857
+ const testData = this.#session.get("test_data");
4858
+ debug("[getTestData] Called", {
4859
+ sessionId: this.id,
4860
+ hasTestData: !!testData,
4861
+ hasIsFirstExposure: testData && "isFirstExposure" in testData,
4862
+ isFirstExposure: testData ? testData.isFirstExposure : void 0,
4863
+ testId: testData?.id,
4864
+ testHandle: testData?.handle
4865
+ });
4866
+ if (testData && "isFirstExposure" in testData) {
4867
+ const { isFirstExposure, ...cleanTestData } = testData;
4868
+ debug("[getTestData] Cleaning session data, removing isFirstExposure flag", {
4869
+ sessionId: this.id,
4870
+ isFirstExposure
4871
+ });
4872
+ this.#session.set("test_data", cleanTestData);
4873
+ this.#isDirty = true;
4874
+ return cleanTestData;
4875
+ }
4876
+ return testData;
1966
4877
  }
1967
4878
  getExpireAt() {
1968
4879
  return this.#session.get("test_expire_at");
1969
4880
  }
1970
4881
  setTestData(testData) {
4882
+ debug("[setTestData] Setting test data", {
4883
+ sessionId: this.id,
4884
+ testId: testData?.id,
4885
+ testHandle: testData?.handle,
4886
+ variantId: testData?.testVariant?.id,
4887
+ variantHandle: testData?.testVariant?.handle
4888
+ });
1971
4889
  this.#isDirty = true;
1972
4890
  this.#session.set("test_data", testData);
1973
4891
  }
1974
4892
  setExpireAt(expireAt) {
4893
+ debug("[setExpireAt] Setting expiry", {
4894
+ sessionId: this.id,
4895
+ expireAt
4896
+ });
1975
4897
  this.#isDirty = true;
1976
4898
  this.#session.set("test_expire_at", expireAt);
1977
4899
  }
1978
4900
  clearTestData() {
4901
+ debug("[clearTestData] Clearing test data and expiry", {
4902
+ sessionId: this.id
4903
+ });
1979
4904
  this.#isDirty = true;
1980
4905
  this.#session.unset("test_data");
1981
4906
  this.#session.unset("test_expire_at");
@@ -1983,95 +4908,721 @@ var PackTestSession = class {
1983
4908
  hasTestData() {
1984
4909
  return this.#session.has("test_data");
1985
4910
  }
4911
+ // Test rules cache methods
4912
+ getTestRulesCache() {
4913
+ return this.#session.get("test_rules_cache");
4914
+ }
4915
+ getTestRulesCacheTimestamp() {
4916
+ return this.#session.get("test_rules_cache_timestamp");
4917
+ }
4918
+ setTestRulesCache(rules, timestamp) {
4919
+ debug("[setTestRulesCache] Caching test rules", {
4920
+ sessionId: this.id,
4921
+ rulesCount: rules.length,
4922
+ timestamp: new Date(timestamp).toISOString()
4923
+ });
4924
+ this.#isDirty = true;
4925
+ this.#session.set("test_rules_cache", rules);
4926
+ this.#session.set("test_rules_cache_timestamp", timestamp);
4927
+ }
4928
+ clearTestRulesCache() {
4929
+ debug("[clearTestRulesCache] Clearing rules cache", {
4930
+ sessionId: this.id
4931
+ });
4932
+ this.#isDirty = true;
4933
+ this.#session.unset("test_rules_cache");
4934
+ this.#session.unset("test_rules_cache_timestamp");
4935
+ }
4936
+ isTestRulesCacheValid(cacheDurationMs = 60 * 60 * 1e3) {
4937
+ const timestamp = this.getTestRulesCacheTimestamp();
4938
+ if (!timestamp) {
4939
+ debug("[isTestRulesCacheValid] No cache timestamp found", {
4940
+ sessionId: this.id
4941
+ });
4942
+ return false;
4943
+ }
4944
+ const isValid = Date.now() - timestamp < cacheDurationMs;
4945
+ debug("[isTestRulesCacheValid] Cache validity check", {
4946
+ sessionId: this.id,
4947
+ isValid,
4948
+ cacheAge: Math.floor((Date.now() - timestamp) / 1e3) + "s",
4949
+ maxAge: Math.floor(cacheDurationMs / 1e3) + "s"
4950
+ });
4951
+ return isValid;
4952
+ }
1986
4953
  hasChanges() {
1987
4954
  const currentTestData = this.getTestData();
1988
4955
  const currentExpireAt = this.getExpireAt();
4956
+ const currentTestRulesCache = this.getTestRulesCache();
4957
+ const currentTestRulesCacheTimestamp = this.getTestRulesCacheTimestamp();
1989
4958
  const testDataChanged = JSON.stringify(currentTestData) !== JSON.stringify(this.#initialData.test_data);
1990
4959
  const expireAtChanged = currentExpireAt !== this.#initialData.test_expire_at;
1991
- return testDataChanged || expireAtChanged || this.#isDirty;
4960
+ const testRulesCacheChanged = JSON.stringify(currentTestRulesCache) !== JSON.stringify(this.#initialData.test_rules_cache);
4961
+ const testRulesCacheTimestampChanged = currentTestRulesCacheTimestamp !== this.#initialData.test_rules_cache_timestamp;
4962
+ const hasChanges = testDataChanged || expireAtChanged || testRulesCacheChanged || testRulesCacheTimestampChanged || this.#isDirty;
4963
+ debug("[hasChanges] Checking for changes", {
4964
+ sessionId: this.id,
4965
+ hasChanges,
4966
+ testDataChanged,
4967
+ expireAtChanged,
4968
+ testRulesCacheChanged,
4969
+ testRulesCacheTimestampChanged,
4970
+ isDirty: this.#isDirty
4971
+ });
4972
+ return hasChanges;
4973
+ }
4974
+ commit() {
4975
+ debug("[commit] Committing session", {
4976
+ sessionId: this.id,
4977
+ isDirty: this.#isDirty,
4978
+ hasTestData: !!this.getTestData()
4979
+ });
4980
+ this.#isDirty = false;
4981
+ this.#initialData = {
4982
+ test_data: this.getTestData(),
4983
+ test_expire_at: this.getExpireAt(),
4984
+ test_rules_cache: this.getTestRulesCache(),
4985
+ test_rules_cache_timestamp: this.getTestRulesCacheTimestamp()
4986
+ };
4987
+ return this.#sessionStorage.commitSession(this.#session);
4988
+ }
4989
+ destroy() {
4990
+ debug("[destroy] Destroying session", {
4991
+ sessionId: this.id
4992
+ });
4993
+ this.#isDirty = true;
4994
+ this.#session.unset("test_data");
4995
+ this.#session.unset("test_expire_at");
4996
+ this.#session.unset("test_rules_cache");
4997
+ this.#session.unset("test_rules_cache_timestamp");
4998
+ return this.#sessionStorage.destroySession(this.#session);
4999
+ }
5000
+ };
5001
+
5002
+ // src/create-pack-client.ts
5003
+ var cookie3 = __toESM(require_cookie(), 1);
5004
+ import { PackClient } from "@pack/client";
5005
+ import { CacheCustom, createWithCache } from "@shopify/hydrogen";
5006
+
5007
+ // src/tests/test.ts
5008
+ var cookie2 = __toESM(require_cookie(), 1);
5009
+
5010
+ // src/tests/local-test-resolver.ts
5011
+ var import_json_rules_engine = __toESM(require_dist(), 1);
5012
+ var import_debug2 = __toESM(require_browser(), 1);
5013
+ var debug2 = (0, import_debug2.default)("pack:ab-testing:local-resolver");
5014
+ var LocalTestResolver = class {
5015
+ testRules = [];
5016
+ constructor() {
5017
+ }
5018
+ /**
5019
+ * Set test rules (from the shared cache)
5020
+ */
5021
+ setTestRules(rules) {
5022
+ this.testRules = rules;
5023
+ }
5024
+ /**
5025
+ * Check if rules are loaded
5026
+ */
5027
+ hasRules() {
5028
+ return this.testRules.length > 0;
5029
+ }
5030
+ /**
5031
+ * Check if a specific test is still active in the current rules
5032
+ */
5033
+ isTestActive(testId) {
5034
+ return this.testRules.some((test) => test.id === testId);
5035
+ }
5036
+ /**
5037
+ * Get fresh test data by ID from current rules
5038
+ */
5039
+ getTestById(testId) {
5040
+ return this.testRules.find((test) => test.id === testId) || null;
5041
+ }
5042
+ /**
5043
+ * Get random number for test assignment
5044
+ */
5045
+ getRandomNumber(max, min = 0) {
5046
+ return Math.floor(Math.random() * (max - min + 1) + min);
5047
+ }
5048
+ /**
5049
+ * Evaluate test rules and assign a variant
5050
+ */
5051
+ async assignTest(attributes, _sessionId) {
5052
+ debug2("[Pack Test LocalResolver] Starting test assignment:", JSON.stringify({
5053
+ totalRules: this.testRules.length,
5054
+ attributes
5055
+ }));
5056
+ if (!this.testRules.length) {
5057
+ debug2("[Pack Test LocalResolver] No test rules available");
5058
+ return null;
5059
+ }
5060
+ const eligibleTests = await this.evaluateRules(this.testRules, attributes);
5061
+ debug2("[Pack Test LocalResolver] Rule evaluation result:", JSON.stringify({
5062
+ totalTests: this.testRules.length,
5063
+ eligibleTests: eligibleTests.length,
5064
+ eligibleTestIds: eligibleTests.map((t) => ({ id: t.id, handle: t.handle }))
5065
+ }));
5066
+ if (!eligibleTests.length) {
5067
+ debug2("[Pack Test LocalResolver] No eligible tests found");
5068
+ return null;
5069
+ }
5070
+ const randomTestIndex = this.getRandomNumber(eligibleTests.length - 1);
5071
+ const selectedTest = eligibleTests[randomTestIndex];
5072
+ debug2("[Pack Test LocalResolver] Selected test:", JSON.stringify({
5073
+ testId: selectedTest.id,
5074
+ testHandle: selectedTest.handle,
5075
+ randomIndex: randomTestIndex,
5076
+ totalEligible: eligibleTests.length
5077
+ }));
5078
+ const randomPercentage = this.getRandomNumber(100, 1);
5079
+ let accumulatedPercentage = 0;
5080
+ debug2("[Pack Test LocalResolver] Starting variant assignment:", JSON.stringify({
5081
+ randomPercentage,
5082
+ variants: selectedTest.testVariants.map((v) => ({
5083
+ id: v.id,
5084
+ handle: v.handle,
5085
+ trafficPercentage: v.trafficPercentage
5086
+ }))
5087
+ }));
5088
+ for (const variant of selectedTest.testVariants) {
5089
+ accumulatedPercentage += variant.trafficPercentage * 100;
5090
+ debug2("[Pack Test LocalResolver] Checking variant:", JSON.stringify({
5091
+ variantId: variant.id,
5092
+ variantHandle: variant.handle,
5093
+ trafficPercentage: variant.trafficPercentage,
5094
+ accumulatedPercentage,
5095
+ randomPercentage,
5096
+ isSelected: accumulatedPercentage >= randomPercentage
5097
+ }));
5098
+ if (accumulatedPercentage >= randomPercentage) {
5099
+ const result = {
5100
+ id: selectedTest.id,
5101
+ handle: selectedTest.handle,
5102
+ testVariant: {
5103
+ id: variant.id,
5104
+ handle: variant.handle
5105
+ }
5106
+ };
5107
+ debug2("[Pack Test LocalResolver] Variant selected:", JSON.stringify(result));
5108
+ return result;
5109
+ }
5110
+ }
5111
+ debug2("[Pack Test LocalResolver] No variant selected (should not happen)");
5112
+ return null;
5113
+ }
5114
+ /**
5115
+ * Evaluate rules using json-rules-engine (same as tests-service)
5116
+ */
5117
+ async evaluateRules(tests, attributes) {
5118
+ debug2("[Pack Test LocalResolver] Starting rule evaluation:", JSON.stringify({
5119
+ totalTests: tests.length,
5120
+ attributes,
5121
+ isClientSide: typeof window !== "undefined"
5122
+ }));
5123
+ if (typeof window !== "undefined") {
5124
+ debug2("[Pack Test LocalResolver] Client side - returning all tests");
5125
+ return tests;
5126
+ }
5127
+ const engineResultsPromises = tests.map((test, index) => {
5128
+ const { rules } = test;
5129
+ debug2(`[Pack Test LocalResolver] Processing test ${index}:`, JSON.stringify({
5130
+ testId: test.id,
5131
+ testHandle: test.handle,
5132
+ rulesCount: rules?.length || 0,
5133
+ rules
5134
+ }));
5135
+ if (rules && Array.isArray(rules)) {
5136
+ if (rules.length === 0) {
5137
+ debug2(`[Pack Test LocalResolver] Test ${test.handle} has no rules - targeting all`);
5138
+ return Promise.resolve({
5139
+ events: [{ type: "targeted" }]
5140
+ });
5141
+ } else {
5142
+ const engineConditionalProperties = rules.filter(
5143
+ (rule) => rule !== null && typeof rule === "object" && Object.hasOwn(rule, "attribute") && Object.hasOwn(rule, "operator") && Object.hasOwn(rule, "value")
5144
+ ).map((rule) => ({
5145
+ fact: rule.attribute,
5146
+ operator: rule.operator,
5147
+ value: rule.value
5148
+ }));
5149
+ debug2(`[Pack Test LocalResolver] Test ${test.handle} engine conditions:`, JSON.stringify(engineConditionalProperties));
5150
+ const engineRules = [
5151
+ new import_json_rules_engine.Rule({
5152
+ conditions: {
5153
+ all: engineConditionalProperties
5154
+ },
5155
+ event: {
5156
+ type: "targeted"
5157
+ }
5158
+ })
5159
+ ];
5160
+ const engine = new import_json_rules_engine.Engine(engineRules, {
5161
+ allowUndefinedFacts: true
5162
+ });
5163
+ engine.addOperator(
5164
+ "stringContains",
5165
+ (factValue, jsonValue) => {
5166
+ return !!factValue && factValue.includes(jsonValue);
5167
+ }
5168
+ );
5169
+ engine.addOperator(
5170
+ "stringDoesNotContain",
5171
+ (factValue, jsonValue) => {
5172
+ return !!factValue && !factValue.includes(jsonValue);
5173
+ }
5174
+ );
5175
+ engine.addOperator(
5176
+ "matchesRegex",
5177
+ (factValue, jsonValue) => {
5178
+ return !!factValue && new RegExp(jsonValue).test(factValue);
5179
+ }
5180
+ );
5181
+ engine.addOperator(
5182
+ "doesNotMatchRegex",
5183
+ (factValue, jsonValue) => {
5184
+ return !!factValue && !new RegExp(jsonValue).test(factValue);
5185
+ }
5186
+ );
5187
+ engine.addOperator(
5188
+ "isSet",
5189
+ (factValue) => !!factValue
5190
+ );
5191
+ engine.addOperator(
5192
+ "isNotSet",
5193
+ (factValue) => !factValue
5194
+ );
5195
+ const result = engine.run(attributes);
5196
+ debug2(`[Pack Test LocalResolver] Engine result for test ${test.handle}:`, JSON.stringify(result));
5197
+ return result;
5198
+ }
5199
+ }
5200
+ debug2(`[Pack Test LocalResolver] Test ${test.handle} has invalid rules`);
5201
+ return void 0;
5202
+ });
5203
+ const engineResults = await Promise.all(engineResultsPromises);
5204
+ debug2("[Pack Test LocalResolver] All engine results:", JSON.stringify(engineResults));
5205
+ const eligibleTests = tests.filter(
5206
+ (test, index) => {
5207
+ const hasTargetedEvent = !!engineResults?.[index]?.events.find((event) => event.type === "targeted");
5208
+ debug2(`[Pack Test LocalResolver] Test ${test.handle} eligibility:`, JSON.stringify({
5209
+ hasTargetedEvent,
5210
+ events: engineResults?.[index]?.events
5211
+ }));
5212
+ return hasTargetedEvent;
5213
+ }
5214
+ );
5215
+ debug2("[Pack Test LocalResolver] Final eligible tests:", JSON.stringify({
5216
+ eligibleCount: eligibleTests.length,
5217
+ eligibleTests: eligibleTests.map((t) => ({ id: t.id, handle: t.handle }))
5218
+ }));
5219
+ return eligibleTests;
1992
5220
  }
1993
- commit() {
1994
- this.#isDirty = false;
1995
- this.#initialData = {
1996
- test_data: this.getTestData(),
1997
- test_expire_at: this.getExpireAt()
5221
+ /**
5222
+ * Resolve test and variant IDs from their handles
5223
+ */
5224
+ resolveTestIdsFromHandles(testHandle, variantHandle) {
5225
+ const test = this.testRules.find((t) => t.handle === testHandle);
5226
+ if (!test) {
5227
+ return null;
5228
+ }
5229
+ const variant = test.testVariants?.find((v) => v.handle === variantHandle);
5230
+ if (!variant) {
5231
+ return null;
5232
+ }
5233
+ return {
5234
+ testId: test.id,
5235
+ variantId: variant.id
1998
5236
  };
1999
- return this.#sessionStorage.commitSession(this.#session);
2000
- }
2001
- destroy() {
2002
- this.#isDirty = true;
2003
- this.#session.unset("test_data");
2004
- this.#session.unset("test_expire_at");
2005
- return this.#sessionStorage.destroySession(this.#session);
2006
5237
  }
2007
5238
  };
2008
5239
 
2009
- // src/create-pack-client.ts
2010
- var import_cookie4 = __toESM(require_cookie());
2011
- import { PackClient } from "@pack/client";
2012
- import { CacheCustom, createWithCache } from "@shopify/hydrogen";
2013
-
2014
5240
  // src/tests/test.ts
2015
- var import_cookie3 = __toESM(require_cookie());
2016
- var QUERY_TEST_VARIANT_IS_RUNNING = `#graphql
2017
- query TestVariantIsRunning($handle: String!, $testId: ID!) {
2018
- testVariantIsRunning(handle: $handle, testId: $testId)
5241
+ var import_debug3 = __toESM(require_browser(), 1);
5242
+ var debug3 = (0, import_debug3.default)("pack:ab-testing:test");
5243
+ var QUERY_TESTS_BY_RULES = `#graphql
5244
+ query TestsByRules($status: String) {
5245
+ testsByRulesV2(status: $status) {
5246
+ totalCount
5247
+ pageInfo {
5248
+ hasNextPage
5249
+ endCursor
5250
+ }
5251
+ edges {
5252
+ cursor
5253
+ node {
5254
+ id
5255
+ handle
5256
+ rules {
5257
+ attribute
5258
+ operator
5259
+ value
5260
+ }
5261
+ testVariants {
5262
+ id
5263
+ handle
5264
+ trafficPercentage
5265
+ }
5266
+ }
5267
+ }
5268
+ }
2019
5269
  }
2020
5270
  `;
2021
- async function packClientFetchTestByRules(packClient, testTargetAudienceAttributes, token) {
2022
- if (!packClient.storeId) {
2023
- console.error("Pack error: Store ID is required to fetch a test.");
2024
- return void 0;
5271
+ var localTestResolver = new LocalTestResolver();
5272
+ function generateTestRulesCacheKey(storeId, contentEnvironment) {
5273
+ return `pack-tests:${storeId}:${contentEnvironment || "default"}`;
5274
+ }
5275
+ async function fetchTestRulesShared(packClient, withCache, token) {
5276
+ const baseCacheKey = generateTestRulesCacheKey(
5277
+ packClient.storeId || "",
5278
+ packClient.contentEnvironment
5279
+ );
5280
+ debug3(
5281
+ "[Pack Test] Fetching test rules with shared cache:",
5282
+ JSON.stringify({
5283
+ baseCacheKey,
5284
+ storeId: packClient.storeId,
5285
+ contentEnvironment: packClient.contentEnvironment
5286
+ })
5287
+ );
5288
+ let testsUpdatedAt;
5289
+ try {
5290
+ const resp = await withCache.run(
5291
+ {
5292
+ cacheKey: ["pack:tests:updatedAt"],
5293
+ cacheStrategy: {
5294
+ maxAge: 15,
5295
+ staleWhileRevalidate: 15
5296
+ },
5297
+ shouldCacheResult: (value) => value !== null
5298
+ },
5299
+ async ({
5300
+ addDebugData
5301
+ }) => {
5302
+ const URL2 = process.env.NODE_ENV === "development" ? "http://localhost:8787/tests-updated-at" : "https://test-cache-check-production.packdigital.workers.dev/tests-updated-at";
5303
+ debug3("[Pack Test] Fetching timestamp from:", URL2);
5304
+ const resp2 = await fetch(URL2, {
5305
+ headers: {
5306
+ Authorization: `Bearer ${token}`
5307
+ }
5308
+ });
5309
+ addDebugData?.({
5310
+ displayName: "Pack Test Cache Check",
5311
+ response: resp2
5312
+ });
5313
+ const { status } = resp2;
5314
+ if (status !== 200) {
5315
+ let message;
5316
+ if (status === 401) {
5317
+ message = "Pack error: Unauthorized request to test cache check service. Please check your token.";
5318
+ } else {
5319
+ message = `Pack error: Request to test cache check service failed with status ${status}`;
5320
+ }
5321
+ debug3(`[Pack Test] Cache check error: ${message}`);
5322
+ console.error(message);
5323
+ return null;
5324
+ }
5325
+ const data = await resp2.json();
5326
+ debug3("[Pack Test] Timestamp response:", JSON.stringify(data));
5327
+ return data;
5328
+ }
5329
+ );
5330
+ testsUpdatedAt = resp?.testsUpdatedAt;
5331
+ debug3(
5332
+ "[Pack Test] Using timestamp for cache key:",
5333
+ JSON.stringify({
5334
+ testsUpdatedAt,
5335
+ hasTimestamp: !!testsUpdatedAt
5336
+ })
5337
+ );
5338
+ } catch (err) {
5339
+ debug3(
5340
+ "[Pack Test] Error checking test cache timestamp:",
5341
+ JSON.stringify(err)
5342
+ );
5343
+ console.error("[Pack Test] Error checking test cache timestamp:", err);
2025
5344
  }
2026
- let resp = void 0;
2027
- const URL2 = "https://tests-service-production.packdigital.workers.dev/tests/assign";
2028
- const assignByRulesResp = await fetch(URL2, {
2029
- method: "POST",
2030
- headers: {
2031
- Authorization: `Bearer ${token}`,
2032
- "X-Pack-Storefront-Id": packClient.storeId,
2033
- ...packClient.contentEnvironment ? { "X-Environment": packClient.contentEnvironment } : {},
2034
- "Content-Type": "application/json"
5345
+ const cacheKey = testsUpdatedAt ? `${baseCacheKey}:${testsUpdatedAt}` : baseCacheKey;
5346
+ debug3("[Pack Test] Final cache key for test rules:", cacheKey);
5347
+ return withCache.run(
5348
+ {
5349
+ cacheKey: [cacheKey],
5350
+ cacheStrategy: {
5351
+ maxAge: 3600,
5352
+ // 1 hour
5353
+ staleWhileRevalidate: 86400,
5354
+ // 24 hours
5355
+ staleIfError: 86400
5356
+ // 24 hours
5357
+ },
5358
+ shouldCacheResult: (result) => Array.isArray(result) && result.length >= 0,
5359
+ displayName: "Pack Test Rules"
2035
5360
  },
2036
- body: JSON.stringify({
2037
- attributes: testTargetAudienceAttributes
2038
- })
2039
- });
2040
- const { status } = assignByRulesResp;
2041
- if (status !== 200) {
2042
- let message;
2043
- if (status === 401) {
2044
- message = "Pack error: Unauthorized request to test assignment service. Please check your token.";
2045
- } else {
2046
- message = `Pack error: Request to test assignment service failed with status ${status}`;
5361
+ async ({ addDebugData }) => {
5362
+ const startTime = Date.now();
5363
+ debug3(
5364
+ "[Pack Test] Cache miss - fetching test rules from Pack GraphQL API"
5365
+ );
5366
+ try {
5367
+ const { data, error } = await packClient.fetch(QUERY_TESTS_BY_RULES, {
5368
+ variables: { status: "running" }
5369
+ });
5370
+ const fetchDuration = Date.now() - startTime;
5371
+ debug3(
5372
+ "[Pack Test] GraphQL query completed:",
5373
+ JSON.stringify({
5374
+ duration: `${fetchDuration}ms`,
5375
+ hasData: !!data,
5376
+ hasError: !!error,
5377
+ totalCount: data?.testsByRulesV2?.totalCount,
5378
+ edgesCount: data?.testsByRulesV2?.edges?.length || 0
5379
+ })
5380
+ );
5381
+ addDebugData?.({
5382
+ displayName: "Pack Test Rules Query"
5383
+ });
5384
+ if (error) {
5385
+ debug3(
5386
+ "[Pack Test] Error fetching test rules:",
5387
+ JSON.stringify({
5388
+ error,
5389
+ errorType: typeof error,
5390
+ errorMessage: error?.message || JSON.stringify(error)
5391
+ })
5392
+ );
5393
+ throw new Error(`GraphQL error: ${JSON.stringify(error)}`);
5394
+ }
5395
+ const rules = data?.testsByRulesV2?.edges.map((edge) => edge.node) || [];
5396
+ debug3(
5397
+ "[Pack Test] Successfully fetched and cached test rules:",
5398
+ JSON.stringify({
5399
+ rulesCount: rules.length,
5400
+ cacheKey,
5401
+ rules: rules.map((rule) => ({
5402
+ id: rule.id,
5403
+ handle: rule.handle,
5404
+ rulesCount: rule.rules?.length || 0,
5405
+ variantsCount: rule.testVariants?.length || 0
5406
+ }))
5407
+ })
5408
+ );
5409
+ return rules;
5410
+ } catch (error) {
5411
+ const fetchDuration = Date.now() - startTime;
5412
+ debug3(
5413
+ "[Pack Test] Exception fetching test rules:",
5414
+ JSON.stringify({
5415
+ error: error instanceof Error ? error.message : error,
5416
+ duration: `${fetchDuration}ms`,
5417
+ stack: error instanceof Error ? error.stack : void 0
5418
+ })
5419
+ );
5420
+ throw error;
5421
+ }
2047
5422
  }
2048
- console.error(message);
2049
- return resp;
2050
- }
2051
- const assignByRulesRespJson = await assignByRulesResp.json();
2052
- if (assignByRulesRespJson?.data) {
2053
- resp = {
2054
- ...assignByRulesRespJson.data,
2055
- // `isFirstExposure` tells the `<PackTestRoute />` this will be the
2056
- // first exposure on render and will be confirmed next request
2057
- isFirstExposure: true
2058
- };
2059
- }
2060
- return resp;
5423
+ );
2061
5424
  }
2062
- async function packClientCheckTestIsRunning(packClient, testSession) {
5425
+ async function packClientFetchTestByRules(packClient, testTargetAudienceAttributes, testSession, request, withCache, token, exposedTest, validateOnly) {
2063
5426
  try {
2064
- const resp = await packClient.fetch(QUERY_TEST_VARIANT_IS_RUNNING, {
2065
- variables: {
2066
- handle: testSession.testVariant.handle,
2067
- testId: testSession.id
5427
+ debug3(
5428
+ "[Pack Test] Starting test assignment process:",
5429
+ JSON.stringify({
5430
+ storeId: packClient.storeId,
5431
+ targetingAttributes: testTargetAudienceAttributes,
5432
+ requestUrl: request.url,
5433
+ validateOnly
5434
+ })
5435
+ );
5436
+ if (!packClient.storeId) {
5437
+ debug3("[Pack Test] Store ID is required to fetch a test.");
5438
+ console.error("[Pack Test] Store ID is required to fetch a test.");
5439
+ return void 0;
5440
+ }
5441
+ debug3(
5442
+ "[Pack Test] Checking if rules are loaded:",
5443
+ JSON.stringify({
5444
+ hasRules: localTestResolver.hasRules()
5445
+ })
5446
+ );
5447
+ if (withCache && token) {
5448
+ debug3("[Pack Test] Fetching test rules through shared cache");
5449
+ try {
5450
+ const rules = await fetchTestRulesShared(
5451
+ packClient,
5452
+ withCache,
5453
+ token
5454
+ );
5455
+ localTestResolver.setTestRules(rules);
5456
+ debug3(
5457
+ "[Pack Test] Updated local resolver with rules from shared cache"
5458
+ );
5459
+ const currentTestData = testSession.getTestData();
5460
+ let needsNewTest = false;
5461
+ if (currentTestData?.id) {
5462
+ const freshTestData = localTestResolver.getTestById(currentTestData.id);
5463
+ if (!freshTestData) {
5464
+ debug3(
5465
+ "[Pack Test] Current session test is no longer active (paused/stopped), clearing session:",
5466
+ JSON.stringify({
5467
+ testId: currentTestData.id,
5468
+ testHandle: currentTestData.handle
5469
+ })
5470
+ );
5471
+ testSession.clearTestData();
5472
+ needsNewTest = true;
5473
+ } else {
5474
+ debug3(
5475
+ "[Pack Test] Current session test is still active in rules, updating with fresh data:",
5476
+ JSON.stringify({
5477
+ testId: freshTestData.id,
5478
+ testHandle: freshTestData.handle,
5479
+ variantsCount: freshTestData.testVariants?.length
5480
+ })
5481
+ );
5482
+ if (currentTestData.testVariant?.id) {
5483
+ const currentVariant = freshTestData.testVariants?.find(
5484
+ (v) => v.id === currentTestData.testVariant.id
5485
+ );
5486
+ if (currentVariant) {
5487
+ const refreshedTest = {
5488
+ id: freshTestData.id,
5489
+ handle: freshTestData.handle,
5490
+ testVariant: {
5491
+ id: currentVariant.id,
5492
+ handle: currentVariant.handle
5493
+ },
5494
+ isFirstExposure: void 0
5495
+ };
5496
+ const { isFirstExposure: isFirstExposure2, ...testDataWithoutFlag2 } = refreshedTest;
5497
+ testSession.setTestData(testDataWithoutFlag2);
5498
+ testSession.setExpireAt(getExpireAtDate().toISOString());
5499
+ return refreshedTest;
5500
+ } else {
5501
+ debug3(
5502
+ "[Pack Test] Current variant no longer exists in test, clearing session:",
5503
+ JSON.stringify({
5504
+ testId: currentTestData.id,
5505
+ variantId: currentTestData.testVariant.id
5506
+ })
5507
+ );
5508
+ testSession.clearTestData();
5509
+ needsNewTest = true;
5510
+ }
5511
+ }
5512
+ }
5513
+ }
5514
+ if (validateOnly && !needsNewTest) {
5515
+ debug3("[Pack Test] Validation complete, no new test needed");
5516
+ return void 0;
5517
+ }
5518
+ } catch (error) {
5519
+ debug3(
5520
+ "[Pack Test] Failed to fetch test rules:",
5521
+ JSON.stringify(error)
5522
+ );
5523
+ console.error("[Pack Test] Failed to fetch test rules:", error);
2068
5524
  }
2069
- });
2070
- return !!resp.data.testVariantIsRunning;
2071
- } catch (e) {
2072
- console.error(e);
5525
+ } else {
5526
+ debug3(
5527
+ "[Pack Test] No withCache or token available - cannot fetch test rules"
5528
+ );
5529
+ }
5530
+ if (exposedTest) {
5531
+ const freshTestData = localTestResolver.getTestById(exposedTest.id);
5532
+ if (freshTestData) {
5533
+ debug3(
5534
+ "[Pack Test] Exposed test is still active in rules, restoring with fresh data:",
5535
+ JSON.stringify({
5536
+ testId: freshTestData.id,
5537
+ testHandle: freshTestData.handle
5538
+ })
5539
+ );
5540
+ const exposedVariant = freshTestData.testVariants?.find(
5541
+ (v) => v.id === exposedTest.testVariant?.id
5542
+ );
5543
+ if (exposedVariant) {
5544
+ const result2 = {
5545
+ id: freshTestData.id,
5546
+ handle: freshTestData.handle,
5547
+ testVariant: {
5548
+ id: exposedVariant.id,
5549
+ handle: exposedVariant.handle
5550
+ },
5551
+ isFirstExposure: void 0
5552
+ };
5553
+ const { isFirstExposure: isFirstExposure2, ...testDataWithoutFlag2 } = result2;
5554
+ testSession.setTestData(testDataWithoutFlag2);
5555
+ testSession.setExpireAt(getExpireAtDate().toISOString());
5556
+ return result2;
5557
+ } else {
5558
+ debug3(
5559
+ "[Pack Test] Exposed test variant no longer exists in fresh data:",
5560
+ JSON.stringify({
5561
+ testId: exposedTest.id,
5562
+ variantId: exposedTest.testVariant?.id
5563
+ })
5564
+ );
5565
+ }
5566
+ } else {
5567
+ debug3(
5568
+ "[Pack Test] Exposed test is no longer active in rules:",
5569
+ JSON.stringify({
5570
+ testId: exposedTest.id
5571
+ })
5572
+ );
5573
+ }
5574
+ }
5575
+ const sessionId = packClient.storeId;
5576
+ debug3("[Pack Test] Assigning test with session ID:", sessionId);
5577
+ const assignedTest = await localTestResolver.assignTest(
5578
+ testTargetAudienceAttributes || {},
5579
+ sessionId
5580
+ );
5581
+ debug3(
5582
+ "[Pack Test] Test assignment result:",
5583
+ JSON.stringify({
5584
+ assigned: !!assignedTest,
5585
+ testId: assignedTest?.id,
5586
+ testHandle: assignedTest?.handle,
5587
+ variantId: assignedTest?.testVariant?.id,
5588
+ variantHandle: assignedTest?.testVariant?.handle
5589
+ })
5590
+ );
5591
+ if (!assignedTest) {
5592
+ debug3(
5593
+ "[Pack Test] No test assigned - user not eligible for any tests"
5594
+ );
5595
+ return void 0;
5596
+ }
5597
+ const result = {
5598
+ ...assignedTest,
5599
+ isFirstExposure: true
5600
+ };
5601
+ debug3(
5602
+ "[Pack Test] Test assigned, saving to session:",
5603
+ JSON.stringify({
5604
+ testId: result.id,
5605
+ testHandle: result.handle,
5606
+ variantId: result.testVariant.id,
5607
+ variantHandle: result.testVariant.handle
5608
+ })
5609
+ );
5610
+ const { isFirstExposure, ...testDataWithoutFlag } = result;
5611
+ testSession.setTestData(testDataWithoutFlag);
5612
+ testSession.setExpireAt(getExpireAtDate().toISOString());
5613
+ debug3("[Pack Test] Returning test info with first exposure flag");
5614
+ return result;
5615
+ } catch (error) {
5616
+ debug3(
5617
+ "[Pack Test] Error in packClientFetchTestByRules, continuing without test:",
5618
+ JSON.stringify(error)
5619
+ );
5620
+ console.error(
5621
+ "[Pack Test] Error in packClientFetchTestByRules, continuing without test:",
5622
+ error
5623
+ );
5624
+ return void 0;
2073
5625
  }
2074
- return false;
2075
5626
  }
2076
5627
  function getExpireAtDate() {
2077
5628
  const expireAt = /* @__PURE__ */ new Date();
@@ -2083,82 +5634,257 @@ async function getTestInfo({
2083
5634
  testTargetAudienceAttributes,
2084
5635
  packClient,
2085
5636
  testSession,
5637
+ withCache,
2086
5638
  token
2087
5639
  }) {
5640
+ debug3(
5641
+ "[Pack Test] Getting test info:",
5642
+ JSON.stringify({
5643
+ hasTestSession: !!testSession,
5644
+ targetingAttributes: testTargetAudienceAttributes,
5645
+ requestUrl: request.url
5646
+ })
5647
+ );
2088
5648
  let testInfo = void 0;
2089
5649
  let exposedTest = void 0;
2090
5650
  if (!testSession) {
5651
+ debug3("[Pack Test] No test session available, returning undefined");
2091
5652
  return testInfo;
2092
5653
  }
2093
5654
  const testSessionData = testSession.getTestData();
2094
5655
  const testSessionExpireAt = testSession.getExpireAt();
2095
- const exposedTestCookieString = import_cookie3.default.parse(
5656
+ debug3(
5657
+ "[Pack Test] Session data check:",
5658
+ JSON.stringify({
5659
+ hasTestData: !!testSessionData,
5660
+ testId: testSessionData?.id,
5661
+ testHandle: testSessionData?.handle,
5662
+ variantId: testSessionData?.testVariant?.id,
5663
+ variantHandle: testSessionData?.testVariant?.handle,
5664
+ expireAt: testSessionExpireAt,
5665
+ isExpired: testSessionExpireAt ? new Date(testSessionExpireAt) < /* @__PURE__ */ new Date() : false
5666
+ })
5667
+ );
5668
+ const exposedTestCookieString = cookie2.parse(
2096
5669
  request.headers.get("cookie") || ""
2097
5670
  )?.exposedTest;
5671
+ debug3(
5672
+ "[Pack Test] Exposed test cookie check:",
5673
+ JSON.stringify({
5674
+ hasExposedTestCookie: !!exposedTestCookieString
5675
+ })
5676
+ );
2098
5677
  if (testSessionData?.id && testSessionData?.testVariant) {
5678
+ debug3("[Pack Test] Found existing test data in session");
2099
5679
  if (!testSessionExpireAt || new Date(testSessionExpireAt) >= /* @__PURE__ */ new Date()) {
5680
+ debug3(
5681
+ "[Pack Test] Test session not expired by time, fetching rules to validate if test is still active"
5682
+ );
2100
5683
  try {
2101
- const testStillRunning = await packClientCheckTestIsRunning(
5684
+ const validationResult = await packClientFetchTestByRules(
2102
5685
  packClient,
2103
- testSessionData
5686
+ testTargetAudienceAttributes,
5687
+ testSession,
5688
+ request,
5689
+ withCache,
5690
+ token,
5691
+ null,
5692
+ true
5693
+ // validateOnly - but will assign new test if current is inactive
2104
5694
  );
2105
- if (testStillRunning) {
2106
- return testSessionData;
5695
+ if (validationResult) {
5696
+ if (validationResult.id === testSessionData.id) {
5697
+ debug3(
5698
+ "[Pack Test] Test is still active, using refreshed data",
5699
+ JSON.stringify({
5700
+ testId: validationResult.id,
5701
+ testHandle: validationResult.handle,
5702
+ variantId: validationResult.testVariant.id,
5703
+ variantHandle: validationResult.testVariant.handle
5704
+ })
5705
+ );
5706
+ return validationResult;
5707
+ } else {
5708
+ debug3(
5709
+ "[Pack Test] Original test no longer active, new test assigned",
5710
+ JSON.stringify({
5711
+ oldTestId: testSessionData.id,
5712
+ newTestId: validationResult.id,
5713
+ newTestHandle: validationResult.handle,
5714
+ newVariantId: validationResult.testVariant.id,
5715
+ newVariantHandle: validationResult.testVariant.handle
5716
+ })
5717
+ );
5718
+ return {
5719
+ ...validationResult,
5720
+ isFirstExposure: true
5721
+ };
5722
+ }
5723
+ } else {
5724
+ debug3("[Pack Test] Test is no longer active and no new test was assigned");
5725
+ return void 0;
2107
5726
  }
2108
5727
  } catch (error) {
5728
+ debug3(
5729
+ "[Pack Test] Error validating test, using cached data:",
5730
+ JSON.stringify(error)
5731
+ );
2109
5732
  console.error(
2110
- "Error checking if test is running, using cached data",
5733
+ "[Pack Test] Error validating test, using cached data:",
2111
5734
  error
2112
5735
  );
2113
- return testSessionData;
5736
+ return { ...testSessionData, isFirstExposure: void 0 };
2114
5737
  }
5738
+ } else {
5739
+ debug3("[Pack Test] Test session has expired by time");
5740
+ debug3("[Pack Test] Clearing expired test session data");
5741
+ testSession.clearTestData();
2115
5742
  }
2116
- testSession.clearTestData();
2117
5743
  }
2118
5744
  if (exposedTestCookieString) {
2119
- exposedTest = JSON.parse(exposedTestCookieString);
5745
+ try {
5746
+ exposedTest = JSON.parse(exposedTestCookieString);
5747
+ debug3(
5748
+ "[Pack Test] Parsed exposed test from cookie:",
5749
+ JSON.stringify({
5750
+ testId: exposedTest?.id,
5751
+ testHandle: exposedTest?.handle,
5752
+ variantId: exposedTest?.testVariant?.id,
5753
+ variantHandle: exposedTest?.testVariant?.handle
5754
+ })
5755
+ );
5756
+ } catch (error) {
5757
+ debug3(
5758
+ "[Pack Test] Failed to parse exposed test cookie:",
5759
+ JSON.stringify(error)
5760
+ );
5761
+ console.error("[Pack Test] Failed to parse exposed test cookie:", error);
5762
+ }
2120
5763
  }
2121
5764
  if (exposedTest && !testSessionData) {
2122
- const testVariantIsRunning = await packClientCheckTestIsRunning(
2123
- packClient,
2124
- exposedTest
5765
+ debug3(
5766
+ "[Pack Test] Found exposed test cookie with no session data - will fetch rules and validate"
2125
5767
  );
2126
- if (testVariantIsRunning) {
2127
- const { id, handle, testVariant } = exposedTest;
2128
- testInfo = {
2129
- id,
2130
- handle,
2131
- testVariant
2132
- };
2133
- testSession.setTestData(testInfo);
2134
- testSession.setExpireAt(getExpireAtDate().toISOString());
2135
- } else {
2136
- testSession.clearTestData();
5768
+ try {
2137
5769
  testInfo = await packClientFetchTestByRules(
2138
5770
  packClient,
2139
5771
  testTargetAudienceAttributes,
2140
- token
5772
+ testSession,
5773
+ request,
5774
+ withCache,
5775
+ token,
5776
+ exposedTest,
5777
+ false
5778
+ // Not validateOnly - allow assigning new tests
5779
+ );
5780
+ if (testInfo?.id === exposedTest.id) {
5781
+ debug3(
5782
+ "[Pack Test] Exposed test was restored (still active)"
5783
+ );
5784
+ } else if (testInfo) {
5785
+ debug3(
5786
+ "[Pack Test] Exposed test is no longer active, using newly assigned test:",
5787
+ JSON.stringify({
5788
+ exposedTestId: exposedTest.id,
5789
+ newTestId: testInfo.id
5790
+ })
5791
+ );
5792
+ } else {
5793
+ debug3(
5794
+ "[Pack Test] Exposed test is no longer active and no new test was assigned"
5795
+ );
5796
+ }
5797
+ } catch (error) {
5798
+ debug3(
5799
+ "[Pack Test] Error processing exposed test:",
5800
+ JSON.stringify(error)
5801
+ );
5802
+ console.error(
5803
+ "[Pack Test] Error processing exposed test, continuing without test:",
5804
+ error
2141
5805
  );
5806
+ testInfo = void 0;
2142
5807
  }
2143
5808
  } else if (testSessionData) {
2144
- testSession.clearTestData();
2145
- testInfo = await packClientFetchTestByRules(
2146
- packClient,
2147
- testTargetAudienceAttributes,
2148
- token
5809
+ debug3(
5810
+ "[Pack Test] Test session data exists but was invalid - fetching new test"
2149
5811
  );
5812
+ testSession.clearTestData();
5813
+ try {
5814
+ testInfo = await packClientFetchTestByRules(
5815
+ packClient,
5816
+ testTargetAudienceAttributes,
5817
+ testSession,
5818
+ request,
5819
+ withCache,
5820
+ token,
5821
+ null,
5822
+ false
5823
+ // Not validateOnly - allow assigning new tests
5824
+ );
5825
+ } catch (error) {
5826
+ debug3(
5827
+ "[Pack Test] Error fetching new test after expired session:",
5828
+ JSON.stringify(error)
5829
+ );
5830
+ console.error(
5831
+ "[Pack Test] Error fetching new test, continuing without test:",
5832
+ error
5833
+ );
5834
+ testInfo = void 0;
5835
+ }
2150
5836
  } else {
2151
- testInfo = await packClientFetchTestByRules(
2152
- packClient,
2153
- testTargetAudienceAttributes,
2154
- token
5837
+ debug3(
5838
+ "[Pack Test] No existing test data found - fetching new test for user"
2155
5839
  );
5840
+ try {
5841
+ testInfo = await packClientFetchTestByRules(
5842
+ packClient,
5843
+ testTargetAudienceAttributes,
5844
+ testSession,
5845
+ request,
5846
+ withCache,
5847
+ token,
5848
+ null,
5849
+ false
5850
+ // Not validateOnly - allow assigning new tests
5851
+ );
5852
+ } catch (error) {
5853
+ debug3(
5854
+ "[Pack Test] Error fetching new test for user:",
5855
+ JSON.stringify(error)
5856
+ );
5857
+ console.error(
5858
+ "[Pack Test] Error fetching new test, continuing without test:",
5859
+ error
5860
+ );
5861
+ testInfo = void 0;
5862
+ }
2156
5863
  }
5864
+ debug3(
5865
+ "[Pack Test] Final test info result:",
5866
+ JSON.stringify({
5867
+ hasTestInfo: !!testInfo,
5868
+ testId: testInfo?.id,
5869
+ testHandle: testInfo?.handle,
5870
+ variantId: testInfo?.testVariant?.id,
5871
+ variantHandle: testInfo?.testVariant?.handle,
5872
+ isFirstExposure: testInfo?.isFirstExposure
5873
+ })
5874
+ );
2157
5875
  return testInfo;
2158
5876
  }
2159
5877
  function getTestSession(testSession, testFromQueryParams = null, previewEnabled = false) {
5878
+ debug3(
5879
+ "[Pack Test] Getting test session:",
5880
+ JSON.stringify({
5881
+ hasTestSession: !!testSession,
5882
+ hasQueryParams: !!testFromQueryParams,
5883
+ previewEnabled
5884
+ })
5885
+ );
2160
5886
  if (testFromQueryParams) {
2161
- return {
5887
+ const result = {
2162
5888
  id: testFromQueryParams.testId || "",
2163
5889
  handle: testFromQueryParams.testHandle || "",
2164
5890
  testVariant: {
@@ -2166,9 +5892,14 @@ function getTestSession(testSession, testFromQueryParams = null, previewEnabled
2166
5892
  handle: testFromQueryParams.testVariantHandle || ""
2167
5893
  }
2168
5894
  };
5895
+ debug3(
5896
+ "[Pack Test] Using test from query parameters:",
5897
+ JSON.stringify(result)
5898
+ );
5899
+ return result;
2169
5900
  }
2170
5901
  if (previewEnabled) {
2171
- return {
5902
+ const result = {
2172
5903
  id: "",
2173
5904
  handle: "isPreview",
2174
5905
  testVariant: {
@@ -2176,11 +5907,27 @@ function getTestSession(testSession, testFromQueryParams = null, previewEnabled
2176
5907
  handle: "isPreview"
2177
5908
  }
2178
5909
  };
5910
+ debug3(
5911
+ "[Pack Test] Using preview mode test session:",
5912
+ JSON.stringify(result)
5913
+ );
5914
+ return result;
2179
5915
  }
2180
5916
  if (!testSession) {
5917
+ debug3("[Pack Test] No test session available");
2181
5918
  return void 0;
2182
5919
  }
2183
5920
  const testSessionData = testSession.getTestData();
5921
+ debug3(
5922
+ "[Pack Test] Retrieved test session data:",
5923
+ JSON.stringify({
5924
+ hasData: !!testSessionData,
5925
+ testId: testSessionData?.id,
5926
+ testHandle: testSessionData?.handle,
5927
+ variantId: testSessionData?.testVariant?.id,
5928
+ variantHandle: testSessionData?.testVariant?.handle
5929
+ })
5930
+ );
2184
5931
  return testSessionData || null;
2185
5932
  }
2186
5933
  function getTestTargetingAttributesFromRequest(request) {
@@ -2211,7 +5958,7 @@ function getTestFromQueryParams(request) {
2211
5958
  return null;
2212
5959
  }
2213
5960
  function setTestHeaders(headers, options) {
2214
- const { previewEnabled, testFromQueryParams, testInfoForRequest } = options;
5961
+ const { testFromQueryParams, testInfoForRequest } = options;
2215
5962
  if (testFromQueryParams) {
2216
5963
  headers["X-Pack-Test-Ignore-Test-Status"] = true;
2217
5964
  if (testFromQueryParams.testId) {
@@ -2227,25 +5974,25 @@ function setTestHeaders(headers, options) {
2227
5974
  headers["X-Pack-Test-Variant-Handle"] = testFromQueryParams.testVariantHandle;
2228
5975
  }
2229
5976
  } else if (testInfoForRequest) {
2230
- headers = {
2231
- "X-Pack-Test-Id": testInfoForRequest?.id,
2232
- "X-Pack-Test-Variant-Id": testInfoForRequest?.testVariant?.id
2233
- };
5977
+ headers["X-Pack-Test-Id"] = testInfoForRequest?.id;
5978
+ headers["X-Pack-Test-Variant-Id"] = testInfoForRequest?.testVariant?.id;
2234
5979
  }
2235
5980
  return headers;
2236
5981
  }
2237
5982
 
2238
5983
  // src/create-pack-client.ts
5984
+ var import_debug4 = __toESM(require_browser(), 1);
5985
+ var debug4 = (0, import_debug4.default)("pack:ab-testing:create-pack-client");
2239
5986
  async function sha2562(message) {
2240
5987
  const messageBuffer = new TextEncoder().encode(message);
2241
5988
  const hashBuffer = await crypto.subtle.digest("SHA-256", messageBuffer);
2242
5989
  return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
2243
5990
  }
2244
5991
  function hashQuery(query, variables, headers) {
2245
- let hash = query;
2246
- if (variables !== null) hash += JSON.stringify(variables);
2247
- if (headers !== null) hash += JSON.stringify(headers);
2248
- return sha2562(hash);
5992
+ let hash2 = query;
5993
+ if (variables !== null) hash2 += JSON.stringify(variables);
5994
+ if (headers !== null) hash2 += JSON.stringify(headers);
5995
+ return sha2562(hash2);
2249
5996
  }
2250
5997
  async function getCacheKey(withCache, query, token, options) {
2251
5998
  let queryHash = await hashQuery(query, options?.variables, options?.headers);
@@ -2277,6 +6024,7 @@ async function getCacheKey(withCache, query, token, options) {
2277
6024
  } else {
2278
6025
  message = `Pack error: Request to cache check service failed with status ${status}`;
2279
6026
  }
6027
+ debug4(`Cache check error: ${message}`);
2280
6028
  console.error(message);
2281
6029
  return null;
2282
6030
  }
@@ -2285,6 +6033,7 @@ async function getCacheKey(withCache, query, token, options) {
2285
6033
  );
2286
6034
  publishedAt = resp?.publishedAt;
2287
6035
  } catch (err) {
6036
+ debug4(`Error getting cache key: ${err}`);
2288
6037
  console.error(err);
2289
6038
  }
2290
6039
  if (publishedAt) {
@@ -2330,14 +6079,17 @@ function createPackClient(options) {
2330
6079
  storeId,
2331
6080
  token,
2332
6081
  apiUrl,
2333
- defaultThemeData
6082
+ defaultThemeData,
6083
+ request
2334
6084
  } = options;
2335
6085
  const previewEnabled = !!session.get("previewEnabled");
2336
6086
  const previewEnvironment = session.get("environment");
2337
6087
  const clientContentEnvironment = previewEnvironment || contentEnvironment;
2338
6088
  let packClient;
2339
- let testFromQueryParams = null;
2340
6089
  let testInfoForRequest = void 0;
6090
+ let testInfoPromise = void 0;
6091
+ let currentRequest = request;
6092
+ let testFromQueryParams = request ? getTestFromQueryParams(request) : null;
2341
6093
  if (!token && !defaultThemeData) {
2342
6094
  throw new Error(
2343
6095
  "ERR_HY_MISSING_TOKEN: The Pack client token is missing or empty. Please provide a valid token or default theme data. Doc: https://docs.packdigital.com/err/ERR_HY_MISSING_TOKEN"
@@ -2348,25 +6100,17 @@ function createPackClient(options) {
2348
6100
  "ERR_HY_MISSING_STORE_ID: The Pack Store ID is missing or empty. Please provide a valid Store ID. Doc: https://docs.packdigital.com/err/ERR_HY_MISSING_STORE_ID"
2349
6101
  );
2350
6102
  }
2351
- const handleRequest2 = async (request) => {
2352
- testFromQueryParams = getTestFromQueryParams(request);
2353
- const testTargetAudienceAttributes = getTestTargetingAttributesFromRequest(request);
2354
- if (packClient && token) {
2355
- testInfoForRequest = await getTestInfo({
2356
- request,
2357
- testTargetAudienceAttributes,
2358
- packClient,
2359
- testSession,
2360
- // Use dedicated test session instead
2361
- token
2362
- });
6103
+ const handleRequest2 = async (request2) => {
6104
+ if (!currentRequest) {
6105
+ currentRequest = request2;
6106
+ testFromQueryParams = getTestFromQueryParams(request2);
2363
6107
  }
2364
6108
  return (response) => {
2365
- const hasExposedTestCookie = request.headers.get("cookie")?.includes("exposedTest");
6109
+ const hasExposedTestCookie = request2.headers.get("cookie")?.includes("exposedTest");
2366
6110
  if (hasExposedTestCookie) {
2367
6111
  response.headers.append(
2368
6112
  "Set-Cookie",
2369
- import_cookie4.default.serialize("exposedTest", "", {
6113
+ cookie3.serialize("exposedTest", "", {
2370
6114
  maxAge: 0,
2371
6115
  expires: /* @__PURE__ */ new Date(0),
2372
6116
  path: "/"
@@ -2375,17 +6119,11 @@ function createPackClient(options) {
2375
6119
  }
2376
6120
  };
2377
6121
  };
2378
- const getTestInfoForLoader = () => {
2379
- let testInfoForLoader = void 0;
2380
- if (testInfoForRequest?.isFirstExposure) {
2381
- const { isFirstExposure, ...testInfo } = testInfoForRequest;
2382
- testInfoForLoader = testInfo;
2383
- }
2384
- return testInfoForLoader;
2385
- };
2386
6122
  if (!token) {
2387
6123
  return {
2388
- abTest: getTestSession(testSession, testFromQueryParams, previewEnabled),
6124
+ get abTest() {
6125
+ return getTestSession(testSession, testFromQueryParams, previewEnabled);
6126
+ },
2389
6127
  handleRequest: handleRequest2,
2390
6128
  getPackSessionData: () => {
2391
6129
  return {
@@ -2415,27 +6153,25 @@ function createPackClient(options) {
2415
6153
  },
2416
6154
  isPreviewModeEnabled: () => previewEnabled,
2417
6155
  isValidEditToken: () => new Promise(() => false),
2418
- async query(query, options2) {
6156
+ async query(query, { variables } = {}) {
2419
6157
  if (!defaultThemeData?.data) {
6158
+ debug4("Warning: Invalid default theme data provided to Pack client");
2420
6159
  console.warn("Invalid default theme data provided to Pack client.");
2421
6160
  return { data: null, error: null };
2422
6161
  }
2423
- const data = resolveQuery({
2424
- query,
2425
- variables: options2.variables,
2426
- defaultThemeData
2427
- });
6162
+ const data = resolveQuery({ query, variables, defaultThemeData });
2428
6163
  return { data, error: null };
2429
6164
  },
2430
6165
  session,
2431
6166
  testSession
2432
6167
  };
2433
6168
  }
6169
+ const resolvedApiUrl = apiUrl ? apiUrl : previewEnabled || process.env.NODE_ENV === "development" ? "https://app.packdigital.com/graphql" : void 0;
2434
6170
  packClient = new PackClient({
2435
6171
  // Use apiUrl, it is configured
2436
6172
  // Use active API URL if preview mode is enabled
2437
6173
  // Otherwise, Live PackClient uses its internal configuration
2438
- apiUrl: apiUrl ? apiUrl : previewEnabled || process.env.NODE_ENV === "development" ? "https://app.packdigital.com/graphql" : void 0,
6174
+ apiUrl: resolvedApiUrl,
2439
6175
  storeId,
2440
6176
  token,
2441
6177
  contentEnvironment: clientContentEnvironment,
@@ -2443,7 +6179,9 @@ function createPackClient(options) {
2443
6179
  clientName: "HydrogenClient"
2444
6180
  });
2445
6181
  return {
2446
- abTest: getTestSession(testSession, testFromQueryParams, previewEnabled),
6182
+ get abTest() {
6183
+ return getTestSession(testSession, testFromQueryParams, previewEnabled);
6184
+ },
2447
6185
  getPackSessionData: () => {
2448
6186
  return {
2449
6187
  storeId,
@@ -2473,72 +6211,121 @@ function createPackClient(options) {
2473
6211
  handleRequest: handleRequest2,
2474
6212
  isPreviewModeEnabled: () => previewEnabled,
2475
6213
  isValidEditToken: (token2) => packClient.isValidEditToken(token2),
2476
- async query(query, options2) {
2477
- let headers = {};
2478
- headers = setTestHeaders(headers, {
2479
- previewEnabled,
2480
- testInfoForRequest,
2481
- testFromQueryParams: testFromQueryParams || options2.test
2482
- });
2483
- if (previewEnabled) {
2484
- const queryVariables2 = options2.variables ? { ...options2.variables } : {};
2485
- queryVariables2.version = "CURRENT";
2486
- const testInfoForLoader2 = getTestInfoForLoader();
2487
- try {
2488
- return {
2489
- ...await packClient.fetch(query, {
2490
- variables: queryVariables2,
2491
- headers
2492
- }),
2493
- packTestInfo: testInfoForLoader2
2494
- };
2495
- } catch (error) {
2496
- return { error, data: null };
6214
+ async query(query, { variables, cache: strategy = cacheCustom, test } = {}) {
6215
+ try {
6216
+ let headers = {};
6217
+ let testInfoForLoader = void 0;
6218
+ const withCache = createWithCache({
6219
+ cache,
6220
+ waitUntil,
6221
+ request: new Request("https://pack.local/cache", { method: "GET" })
6222
+ });
6223
+ const queryVariables = variables ? { ...variables } : {};
6224
+ if (previewEnabled) {
6225
+ queryVariables.version = "CURRENT";
6226
+ } else {
6227
+ queryVariables.version = "PUBLISHED";
2497
6228
  }
2498
- }
2499
- const withCache = createWithCache({
2500
- cache,
2501
- waitUntil,
2502
- request: options2.request
2503
- });
2504
- headers = setTestHeaders(headers, {
2505
- previewEnabled,
2506
- testInfoForRequest,
2507
- testFromQueryParams: testFromQueryParams || options2.test
2508
- });
2509
- const queryVariables = options2.variables ? { ...options2.variables } : {};
2510
- if (previewEnabled) {
2511
- queryVariables.version = "CURRENT";
2512
- } else {
2513
- queryVariables.version = "PUBLISHED";
2514
- }
2515
- const testInfoForLoader = getTestInfoForLoader();
2516
- const queryHash = await getCacheKey(withCache, query, token, {
2517
- variables: queryVariables,
2518
- headers
2519
- });
2520
- const response = await withCache.run(
2521
- {
2522
- cacheKey: [queryHash],
2523
- cacheStrategy: options2.cache || cacheCustom,
2524
- shouldCacheResult: (value) => !value?.error
2525
- },
2526
- async ({ addDebugData }) => {
6229
+ if (packClient && token && !testInfoForRequest && currentRequest) {
6230
+ try {
6231
+ if (!testInfoPromise) {
6232
+ debug4(
6233
+ "[Pack Test] Creating getTestInfo promise - first query for this request"
6234
+ );
6235
+ testInfoPromise = getTestInfo({
6236
+ request: currentRequest,
6237
+ testTargetAudienceAttributes: getTestTargetingAttributesFromRequest(currentRequest),
6238
+ packClient,
6239
+ testSession,
6240
+ // Use dedicated test session instead
6241
+ withCache,
6242
+ token
6243
+ });
6244
+ } else {
6245
+ debug4(
6246
+ "[Pack Test] Reusing existing getTestInfo promise - concurrent query"
6247
+ );
6248
+ }
6249
+ testInfoForRequest = await testInfoPromise;
6250
+ } catch (error) {
6251
+ debug4(
6252
+ "[Pack Test] Error getting test info, continuing without test:",
6253
+ error
6254
+ );
6255
+ console.error(
6256
+ "[Pack Test] Error getting test info, continuing without test:",
6257
+ error
6258
+ );
6259
+ testInfoForRequest = void 0;
6260
+ testInfoPromise = void 0;
6261
+ }
6262
+ } else if (packClient && token && testInfoForRequest) {
6263
+ debug4("[Pack Test] Using cached testInfo - subsequent query");
6264
+ if (process.env.NODE_ENV === "development") {
6265
+ console.log("[Pack Test] Using cached testInfo - subsequent query");
6266
+ }
6267
+ }
6268
+ if (testInfoForRequest?.isFirstExposure) {
6269
+ const { isFirstExposure, ...testInfo } = testInfoForRequest;
6270
+ testInfoForLoader = testInfo;
6271
+ }
6272
+ headers = setTestHeaders(headers, {
6273
+ previewEnabled,
6274
+ testInfoForRequest,
6275
+ testFromQueryParams: testFromQueryParams || test
6276
+ });
6277
+ if (previewEnabled) {
2527
6278
  try {
2528
6279
  const result = await packClient.fetch(query, {
2529
6280
  variables: queryVariables,
2530
6281
  headers
2531
6282
  });
2532
- addDebugData?.({
2533
- displayName: "Pack GraphQL Query"
2534
- });
2535
- return result;
6283
+ return {
6284
+ ...result,
6285
+ packTestInfo: testInfoForLoader
6286
+ };
2536
6287
  } catch (error) {
2537
6288
  return { error, data: null };
2538
6289
  }
2539
6290
  }
2540
- );
2541
- return response.error ? response : { ...response, packTestInfo: testInfoForLoader };
6291
+ const queryHash = await getCacheKey(withCache, query, token, {
6292
+ variables: queryVariables,
6293
+ headers
6294
+ });
6295
+ const response = await withCache.run(
6296
+ {
6297
+ cacheKey: [queryHash],
6298
+ cacheStrategy: strategy,
6299
+ shouldCacheResult: (value) => !value?.error
6300
+ },
6301
+ async () => {
6302
+ try {
6303
+ const result = await packClient.fetch(query, {
6304
+ variables: queryVariables,
6305
+ headers
6306
+ });
6307
+ return result;
6308
+ } catch (error) {
6309
+ return { error, data: null };
6310
+ }
6311
+ }
6312
+ );
6313
+ return response.error ? response : { ...response, packTestInfo: testInfoForLoader };
6314
+ } catch (error) {
6315
+ debug4(
6316
+ "[Pack Test] Critical error in query method, returning error:",
6317
+ error
6318
+ );
6319
+ console.error(
6320
+ "[Pack Test] Critical error in query method, returning error:",
6321
+ error
6322
+ );
6323
+ const queryError = {
6324
+ message: error instanceof Error ? error.message : String(error),
6325
+ type: "NetworkError"
6326
+ };
6327
+ return { error: queryError, data: null };
6328
+ }
2542
6329
  },
2543
6330
  session,
2544
6331
  testSession
@@ -2743,16 +6530,26 @@ var usePackTestContext = () => useContext(PackTestContext);
2743
6530
  // src/tests/pack-test-route.ts
2744
6531
  var usePackLoaderData = () => {
2745
6532
  const [exposedTestInfo, setExposedTestInfo] = useState();
2746
- const { packTestInfo } = useLoaderData();
2747
- const [root] = useMatches();
2748
- const { packIsPreviewMode } = root?.data;
6533
+ let packTestInfo;
6534
+ let packIsPreviewMode;
6535
+ let revalidator;
6536
+ try {
6537
+ const loaderData = useLoaderData();
6538
+ packTestInfo = loaderData?.packTestInfo;
6539
+ const [root] = useMatches();
6540
+ packIsPreviewMode = root?.data?.packIsPreviewMode;
6541
+ revalidator = useRevalidator();
6542
+ } catch (error) {
6543
+ packTestInfo = void 0;
6544
+ packIsPreviewMode = void 0;
6545
+ revalidator = void 0;
6546
+ }
2749
6547
  const {
2750
6548
  testExposureCallback,
2751
6549
  hasUserConsent: hasUserConsent2,
2752
6550
  pendingExposureQueue,
2753
6551
  setPendingExposureQueue
2754
6552
  } = usePackTestContext();
2755
- const revalidator = useRevalidator();
2756
6553
  const exposedTestCookieString = api.get("exposedTest");
2757
6554
  useEffect2(() => {
2758
6555
  if (packTestInfo && !packIsPreviewMode && !hasUserConsent2 && exposedTestCookieString && exposedTestInfo) {
@@ -2780,7 +6577,6 @@ var usePackLoaderData = () => {
2780
6577
  expires
2781
6578
  });
2782
6579
  setExposedTestInfo(packTestInfo);
2783
- console.log("=== TCB HAS USER CONSENT", hasUserConsent2);
2784
6580
  pendingExposureQueue?.forEach((data, key) => {
2785
6581
  try {
2786
6582
  testExposureCallback?.({
@@ -2797,7 +6593,7 @@ var usePackLoaderData = () => {
2797
6593
  }
2798
6594
  });
2799
6595
  testExposureCallback?.({ ...packTestInfo, exposureTime: Date.now() });
2800
- revalidator.revalidate();
6596
+ revalidator?.revalidate();
2801
6597
  }
2802
6598
  }, [packTestInfo, testExposureCallback, exposedTestInfo, hasUserConsent2]);
2803
6599
  };
@@ -2897,6 +6693,27 @@ cookie/index.js:
2897
6693
  * MIT Licensed
2898
6694
  *)
2899
6695
 
6696
+ curry2/index.js:
6697
+ (*!
6698
+ * imports.
6699
+ *)
6700
+ (*!
6701
+ * exports.
6702
+ *)
6703
+
6704
+ brackets2dots/index.js:
6705
+ (*!
6706
+ * exports.
6707
+ *)
6708
+ (*!
6709
+ * regexp patterns.
6710
+ *)
6711
+
6712
+ dotsplit.js/index.js:
6713
+ (*!
6714
+ * exports.
6715
+ *)
6716
+
2900
6717
  js-cookie/dist/js.cookie.mjs:
2901
6718
  (*! js-cookie v3.0.5 | MIT *)
2902
6719
  */