File size: 158,506 Bytes
4888678 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 |
var BSON = (function (exports) {
'use strict';
function isAnyArrayBuffer(value) {
return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value));
}
function isUint8Array(value) {
return Object.prototype.toString.call(value) === '[object Uint8Array]';
}
function isRegExp(d) {
return Object.prototype.toString.call(d) === '[object RegExp]';
}
function isMap(d) {
return Object.prototype.toString.call(d) === '[object Map]';
}
function isDate(d) {
return Object.prototype.toString.call(d) === '[object Date]';
}
const BSON_MAJOR_VERSION = 5;
const BSON_INT32_MAX = 0x7fffffff;
const BSON_INT32_MIN = -0x80000000;
const BSON_INT64_MAX = Math.pow(2, 63) - 1;
const BSON_INT64_MIN = -Math.pow(2, 63);
const JS_INT_MAX = Math.pow(2, 53);
const JS_INT_MIN = -Math.pow(2, 53);
const BSON_DATA_NUMBER = 1;
const BSON_DATA_STRING = 2;
const BSON_DATA_OBJECT = 3;
const BSON_DATA_ARRAY = 4;
const BSON_DATA_BINARY = 5;
const BSON_DATA_UNDEFINED = 6;
const BSON_DATA_OID = 7;
const BSON_DATA_BOOLEAN = 8;
const BSON_DATA_DATE = 9;
const BSON_DATA_NULL = 10;
const BSON_DATA_REGEXP = 11;
const BSON_DATA_DBPOINTER = 12;
const BSON_DATA_CODE = 13;
const BSON_DATA_SYMBOL = 14;
const BSON_DATA_CODE_W_SCOPE = 15;
const BSON_DATA_INT = 16;
const BSON_DATA_TIMESTAMP = 17;
const BSON_DATA_LONG = 18;
const BSON_DATA_DECIMAL128 = 19;
const BSON_DATA_MIN_KEY = 0xff;
const BSON_DATA_MAX_KEY = 0x7f;
const BSON_BINARY_SUBTYPE_DEFAULT = 0;
const BSON_BINARY_SUBTYPE_UUID_NEW = 4;
const BSONType = Object.freeze({
double: 1,
string: 2,
object: 3,
array: 4,
binData: 5,
undefined: 6,
objectId: 7,
bool: 8,
date: 9,
null: 10,
regex: 11,
dbPointer: 12,
javascript: 13,
symbol: 14,
javascriptWithScope: 15,
int: 16,
timestamp: 17,
long: 18,
decimal: 19,
minKey: -1,
maxKey: 127
});
class BSONError extends Error {
get bsonError() {
return true;
}
get name() {
return 'BSONError';
}
constructor(message) {
super(message);
}
static isBSONError(value) {
return (value != null &&
typeof value === 'object' &&
'bsonError' in value &&
value.bsonError === true &&
'name' in value &&
'message' in value &&
'stack' in value);
}
}
class BSONVersionError extends BSONError {
get name() {
return 'BSONVersionError';
}
constructor() {
super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
}
}
class BSONRuntimeError extends BSONError {
get name() {
return 'BSONRuntimeError';
}
constructor(message) {
super(message);
}
}
function nodejsMathRandomBytes(byteLength) {
return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
}
const nodejsRandomBytes = (() => {
try {
return require('crypto').randomBytes;
}
catch {
return nodejsMathRandomBytes;
}
})();
const nodeJsByteUtils = {
toLocalBufferType(potentialBuffer) {
if (Buffer.isBuffer(potentialBuffer)) {
return potentialBuffer;
}
if (ArrayBuffer.isView(potentialBuffer)) {
return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
}
const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
if (stringTag === 'ArrayBuffer' ||
stringTag === 'SharedArrayBuffer' ||
stringTag === '[object ArrayBuffer]' ||
stringTag === '[object SharedArrayBuffer]') {
return Buffer.from(potentialBuffer);
}
throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`);
},
allocate(size) {
return Buffer.alloc(size);
},
equals(a, b) {
return nodeJsByteUtils.toLocalBufferType(a).equals(b);
},
fromNumberArray(array) {
return Buffer.from(array);
},
fromBase64(base64) {
return Buffer.from(base64, 'base64');
},
toBase64(buffer) {
return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64');
},
fromISO88591(codePoints) {
return Buffer.from(codePoints, 'binary');
},
toISO88591(buffer) {
return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary');
},
fromHex(hex) {
return Buffer.from(hex, 'hex');
},
toHex(buffer) {
return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex');
},
fromUTF8(text) {
return Buffer.from(text, 'utf8');
},
toUTF8(buffer, start, end) {
return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
},
utf8ByteLength(input) {
return Buffer.byteLength(input, 'utf8');
},
encodeUTF8Into(buffer, source, byteOffset) {
return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');
},
randomBytes: nodejsRandomBytes
};
function isReactNative() {
const { navigator } = globalThis;
return typeof navigator === 'object' && navigator.product === 'ReactNative';
}
function webMathRandomBytes(byteLength) {
if (byteLength < 0) {
throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
}
return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
}
const webRandomBytes = (() => {
const { crypto } = globalThis;
if (crypto != null && typeof crypto.getRandomValues === 'function') {
return (byteLength) => {
return crypto.getRandomValues(webByteUtils.allocate(byteLength));
};
}
else {
if (isReactNative()) {
const { console } = globalThis;
console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.');
}
return webMathRandomBytes;
}
})();
const HEX_DIGIT = /(\d|[a-f])/i;
const webByteUtils = {
toLocalBufferType(potentialUint8array) {
const stringTag = potentialUint8array?.[Symbol.toStringTag] ??
Object.prototype.toString.call(potentialUint8array);
if (stringTag === 'Uint8Array') {
return potentialUint8array;
}
if (ArrayBuffer.isView(potentialUint8array)) {
return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
}
if (stringTag === 'ArrayBuffer' ||
stringTag === 'SharedArrayBuffer' ||
stringTag === '[object ArrayBuffer]' ||
stringTag === '[object SharedArrayBuffer]') {
return new Uint8Array(potentialUint8array);
}
throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`);
},
allocate(size) {
if (typeof size !== 'number') {
throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
}
return new Uint8Array(size);
},
equals(a, b) {
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
},
fromNumberArray(array) {
return Uint8Array.from(array);
},
fromBase64(base64) {
return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
},
toBase64(uint8array) {
return btoa(webByteUtils.toISO88591(uint8array));
},
fromISO88591(codePoints) {
return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff);
},
toISO88591(uint8array) {
return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join('');
},
fromHex(hex) {
const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
const buffer = [];
for (let i = 0; i < evenLengthHex.length; i += 2) {
const firstDigit = evenLengthHex[i];
const secondDigit = evenLengthHex[i + 1];
if (!HEX_DIGIT.test(firstDigit)) {
break;
}
if (!HEX_DIGIT.test(secondDigit)) {
break;
}
const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
buffer.push(hexDigit);
}
return Uint8Array.from(buffer);
},
toHex(uint8array) {
return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');
},
fromUTF8(text) {
return new TextEncoder().encode(text);
},
toUTF8(uint8array, start, end) {
return new TextDecoder('utf8', { fatal: false }).decode(uint8array.slice(start, end));
},
utf8ByteLength(input) {
return webByteUtils.fromUTF8(input).byteLength;
},
encodeUTF8Into(buffer, source, byteOffset) {
const bytes = webByteUtils.fromUTF8(source);
buffer.set(bytes, byteOffset);
return bytes.byteLength;
},
randomBytes: webRandomBytes
};
const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;
const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
class BSONDataView extends DataView {
static fromUint8Array(input) {
return new DataView(input.buffer, input.byteOffset, input.byteLength);
}
}
class BSONValue {
get [Symbol.for('@@mdb.bson.version')]() {
return BSON_MAJOR_VERSION;
}
}
class Binary extends BSONValue {
get _bsontype() {
return 'Binary';
}
constructor(buffer, subType) {
super();
if (!(buffer == null) &&
!(typeof buffer === 'string') &&
!ArrayBuffer.isView(buffer) &&
!(buffer instanceof ArrayBuffer) &&
!Array.isArray(buffer)) {
throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
}
this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
if (buffer == null) {
this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
this.position = 0;
}
else {
if (typeof buffer === 'string') {
this.buffer = ByteUtils.fromISO88591(buffer);
}
else if (Array.isArray(buffer)) {
this.buffer = ByteUtils.fromNumberArray(buffer);
}
else {
this.buffer = ByteUtils.toLocalBufferType(buffer);
}
this.position = this.buffer.byteLength;
}
}
put(byteValue) {
if (typeof byteValue === 'string' && byteValue.length !== 1) {
throw new BSONError('only accepts single character String');
}
else if (typeof byteValue !== 'number' && byteValue.length !== 1)
throw new BSONError('only accepts single character Uint8Array or Array');
let decodedByte;
if (typeof byteValue === 'string') {
decodedByte = byteValue.charCodeAt(0);
}
else if (typeof byteValue === 'number') {
decodedByte = byteValue;
}
else {
decodedByte = byteValue[0];
}
if (decodedByte < 0 || decodedByte > 255) {
throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
}
if (this.buffer.byteLength > this.position) {
this.buffer[this.position++] = decodedByte;
}
else {
const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
newSpace.set(this.buffer, 0);
this.buffer = newSpace;
this.buffer[this.position++] = decodedByte;
}
}
write(sequence, offset) {
offset = typeof offset === 'number' ? offset : this.position;
if (this.buffer.byteLength < offset + sequence.length) {
const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
newSpace.set(this.buffer, 0);
this.buffer = newSpace;
}
if (ArrayBuffer.isView(sequence)) {
this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
this.position =
offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
}
else if (typeof sequence === 'string') {
const bytes = ByteUtils.fromISO88591(sequence);
this.buffer.set(bytes, offset);
this.position =
offset + sequence.length > this.position ? offset + sequence.length : this.position;
}
}
read(position, length) {
length = length && length > 0 ? length : this.position;
return this.buffer.slice(position, position + length);
}
value(asRaw) {
asRaw = !!asRaw;
if (asRaw && this.buffer.length === this.position) {
return this.buffer;
}
if (asRaw) {
return this.buffer.slice(0, this.position);
}
return ByteUtils.toISO88591(this.buffer.subarray(0, this.position));
}
length() {
return this.position;
}
toJSON() {
return ByteUtils.toBase64(this.buffer);
}
toString(encoding) {
if (encoding === 'hex')
return ByteUtils.toHex(this.buffer);
if (encoding === 'base64')
return ByteUtils.toBase64(this.buffer);
if (encoding === 'utf8' || encoding === 'utf-8')
return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
}
toExtendedJSON(options) {
options = options || {};
const base64String = ByteUtils.toBase64(this.buffer);
const subType = Number(this.sub_type).toString(16);
if (options.legacy) {
return {
$binary: base64String,
$type: subType.length === 1 ? '0' + subType : subType
};
}
return {
$binary: {
base64: base64String,
subType: subType.length === 1 ? '0' + subType : subType
}
};
}
toUUID() {
if (this.sub_type === Binary.SUBTYPE_UUID) {
return new UUID(this.buffer.slice(0, this.position));
}
throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);
}
static createFromHexString(hex, subType) {
return new Binary(ByteUtils.fromHex(hex), subType);
}
static createFromBase64(base64, subType) {
return new Binary(ByteUtils.fromBase64(base64), subType);
}
static fromExtendedJSON(doc, options) {
options = options || {};
let data;
let type;
if ('$binary' in doc) {
if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
type = doc.$type ? parseInt(doc.$type, 16) : 0;
data = ByteUtils.fromBase64(doc.$binary);
}
else {
if (typeof doc.$binary !== 'string') {
type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
data = ByteUtils.fromBase64(doc.$binary.base64);
}
}
}
else if ('$uuid' in doc) {
type = 4;
data = UUID.bytesFromString(doc.$uuid);
}
if (!data) {
throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
}
return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
return `Binary.createFromBase64("${base64}", ${this.sub_type})`;
}
}
Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
Binary.BUFFER_SIZE = 256;
Binary.SUBTYPE_DEFAULT = 0;
Binary.SUBTYPE_FUNCTION = 1;
Binary.SUBTYPE_BYTE_ARRAY = 2;
Binary.SUBTYPE_UUID_OLD = 3;
Binary.SUBTYPE_UUID = 4;
Binary.SUBTYPE_MD5 = 5;
Binary.SUBTYPE_ENCRYPTED = 6;
Binary.SUBTYPE_COLUMN = 7;
Binary.SUBTYPE_USER_DEFINED = 128;
const UUID_BYTE_LENGTH = 16;
const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
class UUID extends Binary {
constructor(input) {
let bytes;
if (input == null) {
bytes = UUID.generate();
}
else if (input instanceof UUID) {
bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
}
else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
bytes = ByteUtils.toLocalBufferType(input);
}
else if (typeof input === 'string') {
bytes = UUID.bytesFromString(input);
}
else {
throw new BSONError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).');
}
super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
}
get id() {
return this.buffer;
}
set id(value) {
this.buffer = value;
}
toHexString(includeDashes = true) {
if (includeDashes) {
return [
ByteUtils.toHex(this.buffer.subarray(0, 4)),
ByteUtils.toHex(this.buffer.subarray(4, 6)),
ByteUtils.toHex(this.buffer.subarray(6, 8)),
ByteUtils.toHex(this.buffer.subarray(8, 10)),
ByteUtils.toHex(this.buffer.subarray(10, 16))
].join('-');
}
return ByteUtils.toHex(this.buffer);
}
toString(encoding) {
if (encoding === 'hex')
return ByteUtils.toHex(this.id);
if (encoding === 'base64')
return ByteUtils.toBase64(this.id);
return this.toHexString();
}
toJSON() {
return this.toHexString();
}
equals(otherId) {
if (!otherId) {
return false;
}
if (otherId instanceof UUID) {
return ByteUtils.equals(otherId.id, this.id);
}
try {
return ByteUtils.equals(new UUID(otherId).id, this.id);
}
catch {
return false;
}
}
toBinary() {
return new Binary(this.id, Binary.SUBTYPE_UUID);
}
static generate() {
const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
return bytes;
}
static isValid(input) {
if (!input) {
return false;
}
if (typeof input === 'string') {
return UUID.isValidUUIDString(input);
}
if (isUint8Array(input)) {
return input.byteLength === UUID_BYTE_LENGTH;
}
return (input._bsontype === 'Binary' &&
input.sub_type === this.SUBTYPE_UUID &&
input.buffer.byteLength === 16);
}
static createFromHexString(hexString) {
const buffer = UUID.bytesFromString(hexString);
return new UUID(buffer);
}
static createFromBase64(base64) {
return new UUID(ByteUtils.fromBase64(base64));
}
static bytesFromString(representation) {
if (!UUID.isValidUUIDString(representation)) {
throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');
}
return ByteUtils.fromHex(representation.replace(/-/g, ''));
}
static isValidUUIDString(representation) {
return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
return `new UUID("${this.toHexString()}")`;
}
}
UUID.cacheHexString = false;
class Code extends BSONValue {
get _bsontype() {
return 'Code';
}
constructor(code, scope) {
super();
this.code = code.toString();
this.scope = scope ?? null;
}
toJSON() {
if (this.scope != null) {
return { code: this.code, scope: this.scope };
}
return { code: this.code };
}
toExtendedJSON() {
if (this.scope) {
return { $code: this.code, $scope: this.scope };
}
return { $code: this.code };
}
static fromExtendedJSON(doc) {
return new Code(doc.$code, doc.$scope);
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
const codeJson = this.toJSON();
return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`;
}
}
function isDBRefLike(value) {
return (value != null &&
typeof value === 'object' &&
'$id' in value &&
value.$id != null &&
'$ref' in value &&
typeof value.$ref === 'string' &&
(!('$db' in value) || ('$db' in value && typeof value.$db === 'string')));
}
class DBRef extends BSONValue {
get _bsontype() {
return 'DBRef';
}
constructor(collection, oid, db, fields) {
super();
const parts = collection.split('.');
if (parts.length === 2) {
db = parts.shift();
collection = parts.shift();
}
this.collection = collection;
this.oid = oid;
this.db = db;
this.fields = fields || {};
}
get namespace() {
return this.collection;
}
set namespace(value) {
this.collection = value;
}
toJSON() {
const o = Object.assign({
$ref: this.collection,
$id: this.oid
}, this.fields);
if (this.db != null)
o.$db = this.db;
return o;
}
toExtendedJSON(options) {
options = options || {};
let o = {
$ref: this.collection,
$id: this.oid
};
if (options.legacy) {
return o;
}
if (this.db)
o.$db = this.db;
o = Object.assign(o, this.fields);
return o;
}
static fromExtendedJSON(doc) {
const copy = Object.assign({}, doc);
delete copy.$ref;
delete copy.$id;
delete copy.$db;
return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
const oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString();
return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db ? `, "${this.db}"` : ''})`;
}
}
let wasm = undefined;
try {
wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
}
catch {
}
const TWO_PWR_16_DBL = 1 << 16;
const TWO_PWR_24_DBL = 1 << 24;
const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
const INT_CACHE = {};
const UINT_CACHE = {};
const MAX_INT64_STRING_LENGTH = 20;
const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
class Long extends BSONValue {
get _bsontype() {
return 'Long';
}
get __isLong__() {
return true;
}
constructor(low = 0, high, unsigned) {
super();
if (typeof low === 'bigint') {
Object.assign(this, Long.fromBigInt(low, !!high));
}
else if (typeof low === 'string') {
Object.assign(this, Long.fromString(low, !!high));
}
else {
this.low = low | 0;
this.high = high | 0;
this.unsigned = !!unsigned;
}
}
static fromBits(lowBits, highBits, unsigned) {
return new Long(lowBits, highBits, unsigned);
}
static fromInt(value, unsigned) {
let obj, cachedObj, cache;
if (unsigned) {
value >>>= 0;
if ((cache = 0 <= value && value < 256)) {
cachedObj = UINT_CACHE[value];
if (cachedObj)
return cachedObj;
}
obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
if (cache)
UINT_CACHE[value] = obj;
return obj;
}
else {
value |= 0;
if ((cache = -128 <= value && value < 128)) {
cachedObj = INT_CACHE[value];
if (cachedObj)
return cachedObj;
}
obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
if (cache)
INT_CACHE[value] = obj;
return obj;
}
}
static fromNumber(value, unsigned) {
if (isNaN(value))
return unsigned ? Long.UZERO : Long.ZERO;
if (unsigned) {
if (value < 0)
return Long.UZERO;
if (value >= TWO_PWR_64_DBL)
return Long.MAX_UNSIGNED_VALUE;
}
else {
if (value <= -TWO_PWR_63_DBL)
return Long.MIN_VALUE;
if (value + 1 >= TWO_PWR_63_DBL)
return Long.MAX_VALUE;
}
if (value < 0)
return Long.fromNumber(-value, unsigned).neg();
return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
}
static fromBigInt(value, unsigned) {
return Long.fromString(value.toString(), unsigned);
}
static fromString(str, unsigned, radix) {
if (str.length === 0)
throw new BSONError('empty string');
if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity')
return Long.ZERO;
if (typeof unsigned === 'number') {
(radix = unsigned), (unsigned = false);
}
else {
unsigned = !!unsigned;
}
radix = radix || 10;
if (radix < 2 || 36 < radix)
throw new BSONError('radix');
let p;
if ((p = str.indexOf('-')) > 0)
throw new BSONError('interior hyphen');
else if (p === 0) {
return Long.fromString(str.substring(1), unsigned, radix).neg();
}
const radixToPower = Long.fromNumber(Math.pow(radix, 8));
let result = Long.ZERO;
for (let i = 0; i < str.length; i += 8) {
const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
if (size < 8) {
const power = Long.fromNumber(Math.pow(radix, size));
result = result.mul(power).add(Long.fromNumber(value));
}
else {
result = result.mul(radixToPower);
result = result.add(Long.fromNumber(value));
}
}
result.unsigned = unsigned;
return result;
}
static fromBytes(bytes, unsigned, le) {
return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
}
static fromBytesLE(bytes, unsigned) {
return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned);
}
static fromBytesBE(bytes, unsigned) {
return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned);
}
static isLong(value) {
return (value != null &&
typeof value === 'object' &&
'__isLong__' in value &&
value.__isLong__ === true);
}
static fromValue(val, unsigned) {
if (typeof val === 'number')
return Long.fromNumber(val, unsigned);
if (typeof val === 'string')
return Long.fromString(val, unsigned);
return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
}
add(addend) {
if (!Long.isLong(addend))
addend = Long.fromValue(addend);
const a48 = this.high >>> 16;
const a32 = this.high & 0xffff;
const a16 = this.low >>> 16;
const a00 = this.low & 0xffff;
const b48 = addend.high >>> 16;
const b32 = addend.high & 0xffff;
const b16 = addend.low >>> 16;
const b00 = addend.low & 0xffff;
let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 + b00;
c16 += c00 >>> 16;
c00 &= 0xffff;
c16 += a16 + b16;
c32 += c16 >>> 16;
c16 &= 0xffff;
c32 += a32 + b32;
c48 += c32 >>> 16;
c32 &= 0xffff;
c48 += a48 + b48;
c48 &= 0xffff;
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
}
and(other) {
if (!Long.isLong(other))
other = Long.fromValue(other);
return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
}
compare(other) {
if (!Long.isLong(other))
other = Long.fromValue(other);
if (this.eq(other))
return 0;
const thisNeg = this.isNegative(), otherNeg = other.isNegative();
if (thisNeg && !otherNeg)
return -1;
if (!thisNeg && otherNeg)
return 1;
if (!this.unsigned)
return this.sub(other).isNegative() ? -1 : 1;
return other.high >>> 0 > this.high >>> 0 ||
(other.high === this.high && other.low >>> 0 > this.low >>> 0)
? -1
: 1;
}
comp(other) {
return this.compare(other);
}
divide(divisor) {
if (!Long.isLong(divisor))
divisor = Long.fromValue(divisor);
if (divisor.isZero())
throw new BSONError('division by zero');
if (wasm) {
if (!this.unsigned &&
this.high === -0x80000000 &&
divisor.low === -1 &&
divisor.high === -1) {
return this;
}
const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
return Long.fromBits(low, wasm.get_high(), this.unsigned);
}
if (this.isZero())
return this.unsigned ? Long.UZERO : Long.ZERO;
let approx, rem, res;
if (!this.unsigned) {
if (this.eq(Long.MIN_VALUE)) {
if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
return Long.MIN_VALUE;
else if (divisor.eq(Long.MIN_VALUE))
return Long.ONE;
else {
const halfThis = this.shr(1);
approx = halfThis.div(divisor).shl(1);
if (approx.eq(Long.ZERO)) {
return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
}
else {
rem = this.sub(divisor.mul(approx));
res = approx.add(rem.div(divisor));
return res;
}
}
}
else if (divisor.eq(Long.MIN_VALUE))
return this.unsigned ? Long.UZERO : Long.ZERO;
if (this.isNegative()) {
if (divisor.isNegative())
return this.neg().div(divisor.neg());
return this.neg().div(divisor).neg();
}
else if (divisor.isNegative())
return this.div(divisor.neg()).neg();
res = Long.ZERO;
}
else {
if (!divisor.unsigned)
divisor = divisor.toUnsigned();
if (divisor.gt(this))
return Long.UZERO;
if (divisor.gt(this.shru(1)))
return Long.UONE;
res = Long.UZERO;
}
rem = this;
while (rem.gte(divisor)) {
approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
const log2 = Math.ceil(Math.log(approx) / Math.LN2);
const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
let approxRes = Long.fromNumber(approx);
let approxRem = approxRes.mul(divisor);
while (approxRem.isNegative() || approxRem.gt(rem)) {
approx -= delta;
approxRes = Long.fromNumber(approx, this.unsigned);
approxRem = approxRes.mul(divisor);
}
if (approxRes.isZero())
approxRes = Long.ONE;
res = res.add(approxRes);
rem = rem.sub(approxRem);
}
return res;
}
div(divisor) {
return this.divide(divisor);
}
equals(other) {
if (!Long.isLong(other))
other = Long.fromValue(other);
if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
return false;
return this.high === other.high && this.low === other.low;
}
eq(other) {
return this.equals(other);
}
getHighBits() {
return this.high;
}
getHighBitsUnsigned() {
return this.high >>> 0;
}
getLowBits() {
return this.low;
}
getLowBitsUnsigned() {
return this.low >>> 0;
}
getNumBitsAbs() {
if (this.isNegative()) {
return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
}
const val = this.high !== 0 ? this.high : this.low;
let bit;
for (bit = 31; bit > 0; bit--)
if ((val & (1 << bit)) !== 0)
break;
return this.high !== 0 ? bit + 33 : bit + 1;
}
greaterThan(other) {
return this.comp(other) > 0;
}
gt(other) {
return this.greaterThan(other);
}
greaterThanOrEqual(other) {
return this.comp(other) >= 0;
}
gte(other) {
return this.greaterThanOrEqual(other);
}
ge(other) {
return this.greaterThanOrEqual(other);
}
isEven() {
return (this.low & 1) === 0;
}
isNegative() {
return !this.unsigned && this.high < 0;
}
isOdd() {
return (this.low & 1) === 1;
}
isPositive() {
return this.unsigned || this.high >= 0;
}
isZero() {
return this.high === 0 && this.low === 0;
}
lessThan(other) {
return this.comp(other) < 0;
}
lt(other) {
return this.lessThan(other);
}
lessThanOrEqual(other) {
return this.comp(other) <= 0;
}
lte(other) {
return this.lessThanOrEqual(other);
}
modulo(divisor) {
if (!Long.isLong(divisor))
divisor = Long.fromValue(divisor);
if (wasm) {
const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
return Long.fromBits(low, wasm.get_high(), this.unsigned);
}
return this.sub(this.div(divisor).mul(divisor));
}
mod(divisor) {
return this.modulo(divisor);
}
rem(divisor) {
return this.modulo(divisor);
}
multiply(multiplier) {
if (this.isZero())
return Long.ZERO;
if (!Long.isLong(multiplier))
multiplier = Long.fromValue(multiplier);
if (wasm) {
const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
return Long.fromBits(low, wasm.get_high(), this.unsigned);
}
if (multiplier.isZero())
return Long.ZERO;
if (this.eq(Long.MIN_VALUE))
return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
if (multiplier.eq(Long.MIN_VALUE))
return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
if (this.isNegative()) {
if (multiplier.isNegative())
return this.neg().mul(multiplier.neg());
else
return this.neg().mul(multiplier).neg();
}
else if (multiplier.isNegative())
return this.mul(multiplier.neg()).neg();
if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
const a48 = this.high >>> 16;
const a32 = this.high & 0xffff;
const a16 = this.low >>> 16;
const a00 = this.low & 0xffff;
const b48 = multiplier.high >>> 16;
const b32 = multiplier.high & 0xffff;
const b16 = multiplier.low >>> 16;
const b00 = multiplier.low & 0xffff;
let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 * b00;
c16 += c00 >>> 16;
c00 &= 0xffff;
c16 += a16 * b00;
c32 += c16 >>> 16;
c16 &= 0xffff;
c16 += a00 * b16;
c32 += c16 >>> 16;
c16 &= 0xffff;
c32 += a32 * b00;
c48 += c32 >>> 16;
c32 &= 0xffff;
c32 += a16 * b16;
c48 += c32 >>> 16;
c32 &= 0xffff;
c32 += a00 * b32;
c48 += c32 >>> 16;
c32 &= 0xffff;
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
c48 &= 0xffff;
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
}
mul(multiplier) {
return this.multiply(multiplier);
}
negate() {
if (!this.unsigned && this.eq(Long.MIN_VALUE))
return Long.MIN_VALUE;
return this.not().add(Long.ONE);
}
neg() {
return this.negate();
}
not() {
return Long.fromBits(~this.low, ~this.high, this.unsigned);
}
notEquals(other) {
return !this.equals(other);
}
neq(other) {
return this.notEquals(other);
}
ne(other) {
return this.notEquals(other);
}
or(other) {
if (!Long.isLong(other))
other = Long.fromValue(other);
return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
}
shiftLeft(numBits) {
if (Long.isLong(numBits))
numBits = numBits.toInt();
if ((numBits &= 63) === 0)
return this;
else if (numBits < 32)
return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
else
return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
}
shl(numBits) {
return this.shiftLeft(numBits);
}
shiftRight(numBits) {
if (Long.isLong(numBits))
numBits = numBits.toInt();
if ((numBits &= 63) === 0)
return this;
else if (numBits < 32)
return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
else
return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
}
shr(numBits) {
return this.shiftRight(numBits);
}
shiftRightUnsigned(numBits) {
if (Long.isLong(numBits))
numBits = numBits.toInt();
numBits &= 63;
if (numBits === 0)
return this;
else {
const high = this.high;
if (numBits < 32) {
const low = this.low;
return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
}
else if (numBits === 32)
return Long.fromBits(high, 0, this.unsigned);
else
return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
}
}
shr_u(numBits) {
return this.shiftRightUnsigned(numBits);
}
shru(numBits) {
return this.shiftRightUnsigned(numBits);
}
subtract(subtrahend) {
if (!Long.isLong(subtrahend))
subtrahend = Long.fromValue(subtrahend);
return this.add(subtrahend.neg());
}
sub(subtrahend) {
return this.subtract(subtrahend);
}
toInt() {
return this.unsigned ? this.low >>> 0 : this.low;
}
toNumber() {
if (this.unsigned)
return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
}
toBigInt() {
return BigInt(this.toString());
}
toBytes(le) {
return le ? this.toBytesLE() : this.toBytesBE();
}
toBytesLE() {
const hi = this.high, lo = this.low;
return [
lo & 0xff,
(lo >>> 8) & 0xff,
(lo >>> 16) & 0xff,
lo >>> 24,
hi & 0xff,
(hi >>> 8) & 0xff,
(hi >>> 16) & 0xff,
hi >>> 24
];
}
toBytesBE() {
const hi = this.high, lo = this.low;
return [
hi >>> 24,
(hi >>> 16) & 0xff,
(hi >>> 8) & 0xff,
hi & 0xff,
lo >>> 24,
(lo >>> 16) & 0xff,
(lo >>> 8) & 0xff,
lo & 0xff
];
}
toSigned() {
if (!this.unsigned)
return this;
return Long.fromBits(this.low, this.high, false);
}
toString(radix) {
radix = radix || 10;
if (radix < 2 || 36 < radix)
throw new BSONError('radix');
if (this.isZero())
return '0';
if (this.isNegative()) {
if (this.eq(Long.MIN_VALUE)) {
const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
return div.toString(radix) + rem1.toInt().toString(radix);
}
else
return '-' + this.neg().toString(radix);
}
const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
let rem = this;
let result = '';
while (true) {
const remDiv = rem.div(radixToPower);
const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
let digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero()) {
return digits + result;
}
else {
while (digits.length < 6)
digits = '0' + digits;
result = '' + digits + result;
}
}
}
toUnsigned() {
if (this.unsigned)
return this;
return Long.fromBits(this.low, this.high, true);
}
xor(other) {
if (!Long.isLong(other))
other = Long.fromValue(other);
return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
}
eqz() {
return this.isZero();
}
le(other) {
return this.lessThanOrEqual(other);
}
toExtendedJSON(options) {
if (options && options.relaxed)
return this.toNumber();
return { $numberLong: this.toString() };
}
static fromExtendedJSON(doc, options) {
const { useBigInt64 = false, relaxed = true } = { ...options };
if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
throw new BSONError('$numberLong string is too long');
}
if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
}
if (useBigInt64) {
const bigIntResult = BigInt(doc.$numberLong);
return BigInt.asIntN(64, bigIntResult);
}
const longResult = Long.fromString(doc.$numberLong);
if (relaxed) {
return longResult.toNumber();
}
return longResult;
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`;
}
}
Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
Long.ZERO = Long.fromInt(0);
Long.UZERO = Long.fromInt(0, true);
Long.ONE = Long.fromInt(1);
Long.UONE = Long.fromInt(1, true);
Long.NEG_ONE = Long.fromInt(-1);
Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
const EXPONENT_MAX = 6111;
const EXPONENT_MIN = -6176;
const EXPONENT_BIAS = 6176;
const MAX_DIGITS = 34;
const NAN_BUFFER = ByteUtils.fromNumberArray([
0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
].reverse());
const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
].reverse());
const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
].reverse());
const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
const COMBINATION_MASK = 0x1f;
const EXPONENT_MASK = 0x3fff;
const COMBINATION_INFINITY = 30;
const COMBINATION_NAN = 31;
function isDigit(value) {
return !isNaN(parseInt(value, 10));
}
function divideu128(value) {
const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
let _rem = Long.fromNumber(0);
if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
return { quotient: value, rem: _rem };
}
for (let i = 0; i <= 3; i++) {
_rem = _rem.shiftLeft(32);
_rem = _rem.add(new Long(value.parts[i], 0));
value.parts[i] = _rem.div(DIVISOR).low;
_rem = _rem.modulo(DIVISOR);
}
return { quotient: value, rem: _rem };
}
function multiply64x2(left, right) {
if (!left && !right) {
return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
}
const leftHigh = left.shiftRightUnsigned(32);
const leftLow = new Long(left.getLowBits(), 0);
const rightHigh = right.shiftRightUnsigned(32);
const rightLow = new Long(right.getLowBits(), 0);
let productHigh = leftHigh.multiply(rightHigh);
let productMid = leftHigh.multiply(rightLow);
const productMid2 = leftLow.multiply(rightHigh);
let productLow = leftLow.multiply(rightLow);
productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
productMid = new Long(productMid.getLowBits(), 0)
.add(productMid2)
.add(productLow.shiftRightUnsigned(32));
productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
return { high: productHigh, low: productLow };
}
function lessThan(left, right) {
const uhleft = left.high >>> 0;
const uhright = right.high >>> 0;
if (uhleft < uhright) {
return true;
}
else if (uhleft === uhright) {
const ulleft = left.low >>> 0;
const ulright = right.low >>> 0;
if (ulleft < ulright)
return true;
}
return false;
}
function invalidErr(string, message) {
throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
}
class Decimal128 extends BSONValue {
get _bsontype() {
return 'Decimal128';
}
constructor(bytes) {
super();
if (typeof bytes === 'string') {
this.bytes = Decimal128.fromString(bytes).bytes;
}
else if (isUint8Array(bytes)) {
if (bytes.byteLength !== 16) {
throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
}
this.bytes = bytes;
}
else {
throw new BSONError('Decimal128 must take a Buffer or string');
}
}
static fromString(representation) {
return Decimal128._fromString(representation, { allowRounding: false });
}
static fromStringWithRounding(representation) {
return Decimal128._fromString(representation, { allowRounding: true });
}
static _fromString(representation, options) {
let isNegative = false;
let sawSign = false;
let sawRadix = false;
let foundNonZero = false;
let significantDigits = 0;
let nDigitsRead = 0;
let nDigits = 0;
let radixPosition = 0;
let firstNonZero = 0;
const digits = [0];
let nDigitsStored = 0;
let digitsInsert = 0;
let lastDigit = 0;
let exponent = 0;
let significandHigh = new Long(0, 0);
let significandLow = new Long(0, 0);
let biasedExponent = 0;
let index = 0;
if (representation.length >= 7000) {
throw new BSONError('' + representation + ' not a valid Decimal128 string');
}
const stringMatch = representation.match(PARSE_STRING_REGEXP);
const infMatch = representation.match(PARSE_INF_REGEXP);
const nanMatch = representation.match(PARSE_NAN_REGEXP);
if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
throw new BSONError('' + representation + ' not a valid Decimal128 string');
}
if (stringMatch) {
const unsignedNumber = stringMatch[2];
const e = stringMatch[4];
const expSign = stringMatch[5];
const expNumber = stringMatch[6];
if (e && expNumber === undefined)
invalidErr(representation, 'missing exponent power');
if (e && unsignedNumber === undefined)
invalidErr(representation, 'missing exponent base');
if (e === undefined && (expSign || expNumber)) {
invalidErr(representation, 'missing e before exponent');
}
}
if (representation[index] === '+' || representation[index] === '-') {
sawSign = true;
isNegative = representation[index++] === '-';
}
if (!isDigit(representation[index]) && representation[index] !== '.') {
if (representation[index] === 'i' || representation[index] === 'I') {
return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
}
else if (representation[index] === 'N') {
return new Decimal128(NAN_BUFFER);
}
}
while (isDigit(representation[index]) || representation[index] === '.') {
if (representation[index] === '.') {
if (sawRadix)
invalidErr(representation, 'contains multiple periods');
sawRadix = true;
index = index + 1;
continue;
}
if (nDigitsStored < MAX_DIGITS) {
if (representation[index] !== '0' || foundNonZero) {
if (!foundNonZero) {
firstNonZero = nDigitsRead;
}
foundNonZero = true;
digits[digitsInsert++] = parseInt(representation[index], 10);
nDigitsStored = nDigitsStored + 1;
}
}
if (foundNonZero)
nDigits = nDigits + 1;
if (sawRadix)
radixPosition = radixPosition + 1;
nDigitsRead = nDigitsRead + 1;
index = index + 1;
}
if (sawRadix && !nDigitsRead)
throw new BSONError('' + representation + ' not a valid Decimal128 string');
if (representation[index] === 'e' || representation[index] === 'E') {
const match = representation.substr(++index).match(EXPONENT_REGEX);
if (!match || !match[2])
return new Decimal128(NAN_BUFFER);
exponent = parseInt(match[0], 10);
index = index + match[0].length;
}
if (representation[index])
return new Decimal128(NAN_BUFFER);
if (!nDigitsStored) {
digits[0] = 0;
nDigits = 1;
nDigitsStored = 1;
significantDigits = 0;
}
else {
lastDigit = nDigitsStored - 1;
significantDigits = nDigits;
if (significantDigits !== 1) {
while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') {
significantDigits = significantDigits - 1;
}
}
}
if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
exponent = EXPONENT_MIN;
}
else {
exponent = exponent - radixPosition;
}
while (exponent > EXPONENT_MAX) {
lastDigit = lastDigit + 1;
if (lastDigit >= MAX_DIGITS) {
if (significantDigits === 0) {
exponent = EXPONENT_MAX;
break;
}
invalidErr(representation, 'overflow');
}
exponent = exponent - 1;
}
if (options.allowRounding) {
while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
if (lastDigit === 0 && significantDigits < nDigitsStored) {
exponent = EXPONENT_MIN;
significantDigits = 0;
break;
}
if (nDigitsStored < nDigits) {
nDigits = nDigits - 1;
}
else {
lastDigit = lastDigit - 1;
}
if (exponent < EXPONENT_MAX) {
exponent = exponent + 1;
}
else {
const digitsString = digits.join('');
if (digitsString.match(/^0+$/)) {
exponent = EXPONENT_MAX;
break;
}
invalidErr(representation, 'overflow');
}
}
if (lastDigit + 1 < significantDigits) {
let endOfString = nDigitsRead;
if (sawRadix) {
firstNonZero = firstNonZero + 1;
endOfString = endOfString + 1;
}
if (sawSign) {
firstNonZero = firstNonZero + 1;
endOfString = endOfString + 1;
}
const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
let roundBit = 0;
if (roundDigit >= 5) {
roundBit = 1;
if (roundDigit === 5) {
roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
if (parseInt(representation[i], 10)) {
roundBit = 1;
break;
}
}
}
}
if (roundBit) {
let dIdx = lastDigit;
for (; dIdx >= 0; dIdx--) {
if (++digits[dIdx] > 9) {
digits[dIdx] = 0;
if (dIdx === 0) {
if (exponent < EXPONENT_MAX) {
exponent = exponent + 1;
digits[dIdx] = 1;
}
else {
return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
}
}
}
else {
break;
}
}
}
}
}
else {
while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
if (lastDigit === 0) {
if (significantDigits === 0) {
exponent = EXPONENT_MIN;
break;
}
invalidErr(representation, 'exponent underflow');
}
if (nDigitsStored < nDigits) {
if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' &&
significantDigits !== 0) {
invalidErr(representation, 'inexact rounding');
}
nDigits = nDigits - 1;
}
else {
if (digits[lastDigit] !== 0) {
invalidErr(representation, 'inexact rounding');
}
lastDigit = lastDigit - 1;
}
if (exponent < EXPONENT_MAX) {
exponent = exponent + 1;
}
else {
invalidErr(representation, 'overflow');
}
}
if (lastDigit + 1 < significantDigits) {
if (sawRadix) {
firstNonZero = firstNonZero + 1;
}
if (sawSign) {
firstNonZero = firstNonZero + 1;
}
const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
if (roundDigit !== 0) {
invalidErr(representation, 'inexact rounding');
}
}
}
significandHigh = Long.fromNumber(0);
significandLow = Long.fromNumber(0);
if (significantDigits === 0) {
significandHigh = Long.fromNumber(0);
significandLow = Long.fromNumber(0);
}
else if (lastDigit < 17) {
let dIdx = 0;
significandLow = Long.fromNumber(digits[dIdx++]);
significandHigh = new Long(0, 0);
for (; dIdx <= lastDigit; dIdx++) {
significandLow = significandLow.multiply(Long.fromNumber(10));
significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
}
}
else {
let dIdx = 0;
significandHigh = Long.fromNumber(digits[dIdx++]);
for (; dIdx <= lastDigit - 17; dIdx++) {
significandHigh = significandHigh.multiply(Long.fromNumber(10));
significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
}
significandLow = Long.fromNumber(digits[dIdx++]);
for (; dIdx <= lastDigit; dIdx++) {
significandLow = significandLow.multiply(Long.fromNumber(10));
significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
}
}
const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
significand.low = significand.low.add(significandLow);
if (lessThan(significand.low, significandLow)) {
significand.high = significand.high.add(Long.fromNumber(1));
}
biasedExponent = exponent + EXPONENT_BIAS;
const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
}
else {
dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
}
dec.low = significand.low;
if (isNegative) {
dec.high = dec.high.or(Long.fromString('9223372036854775808'));
}
const buffer = ByteUtils.allocate(16);
index = 0;
buffer[index++] = dec.low.low & 0xff;
buffer[index++] = (dec.low.low >> 8) & 0xff;
buffer[index++] = (dec.low.low >> 16) & 0xff;
buffer[index++] = (dec.low.low >> 24) & 0xff;
buffer[index++] = dec.low.high & 0xff;
buffer[index++] = (dec.low.high >> 8) & 0xff;
buffer[index++] = (dec.low.high >> 16) & 0xff;
buffer[index++] = (dec.low.high >> 24) & 0xff;
buffer[index++] = dec.high.low & 0xff;
buffer[index++] = (dec.high.low >> 8) & 0xff;
buffer[index++] = (dec.high.low >> 16) & 0xff;
buffer[index++] = (dec.high.low >> 24) & 0xff;
buffer[index++] = dec.high.high & 0xff;
buffer[index++] = (dec.high.high >> 8) & 0xff;
buffer[index++] = (dec.high.high >> 16) & 0xff;
buffer[index++] = (dec.high.high >> 24) & 0xff;
return new Decimal128(buffer);
}
toString() {
let biased_exponent;
let significand_digits = 0;
const significand = new Array(36);
for (let i = 0; i < significand.length; i++)
significand[i] = 0;
let index = 0;
let is_zero = false;
let significand_msb;
let significand128 = { parts: [0, 0, 0, 0] };
let j, k;
const string = [];
index = 0;
const buffer = this.bytes;
const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
index = 0;
const dec = {
low: new Long(low, midl),
high: new Long(midh, high)
};
if (dec.high.lessThan(Long.ZERO)) {
string.push('-');
}
const combination = (high >> 26) & COMBINATION_MASK;
if (combination >> 3 === 3) {
if (combination === COMBINATION_INFINITY) {
return string.join('') + 'Infinity';
}
else if (combination === COMBINATION_NAN) {
return 'NaN';
}
else {
biased_exponent = (high >> 15) & EXPONENT_MASK;
significand_msb = 0x08 + ((high >> 14) & 0x01);
}
}
else {
significand_msb = (high >> 14) & 0x07;
biased_exponent = (high >> 17) & EXPONENT_MASK;
}
const exponent = biased_exponent - EXPONENT_BIAS;
significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
significand128.parts[1] = midh;
significand128.parts[2] = midl;
significand128.parts[3] = low;
if (significand128.parts[0] === 0 &&
significand128.parts[1] === 0 &&
significand128.parts[2] === 0 &&
significand128.parts[3] === 0) {
is_zero = true;
}
else {
for (k = 3; k >= 0; k--) {
let least_digits = 0;
const result = divideu128(significand128);
significand128 = result.quotient;
least_digits = result.rem.low;
if (!least_digits)
continue;
for (j = 8; j >= 0; j--) {
significand[k * 9 + j] = least_digits % 10;
least_digits = Math.floor(least_digits / 10);
}
}
}
if (is_zero) {
significand_digits = 1;
significand[index] = 0;
}
else {
significand_digits = 36;
while (!significand[index]) {
significand_digits = significand_digits - 1;
index = index + 1;
}
}
const scientific_exponent = significand_digits - 1 + exponent;
if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
if (significand_digits > 34) {
string.push(`${0}`);
if (exponent > 0)
string.push(`E+${exponent}`);
else if (exponent < 0)
string.push(`E${exponent}`);
return string.join('');
}
string.push(`${significand[index++]}`);
significand_digits = significand_digits - 1;
if (significand_digits) {
string.push('.');
}
for (let i = 0; i < significand_digits; i++) {
string.push(`${significand[index++]}`);
}
string.push('E');
if (scientific_exponent > 0) {
string.push(`+${scientific_exponent}`);
}
else {
string.push(`${scientific_exponent}`);
}
}
else {
if (exponent >= 0) {
for (let i = 0; i < significand_digits; i++) {
string.push(`${significand[index++]}`);
}
}
else {
let radix_position = significand_digits + exponent;
if (radix_position > 0) {
for (let i = 0; i < radix_position; i++) {
string.push(`${significand[index++]}`);
}
}
else {
string.push('0');
}
string.push('.');
while (radix_position++ < 0) {
string.push('0');
}
for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
string.push(`${significand[index++]}`);
}
}
}
return string.join('');
}
toJSON() {
return { $numberDecimal: this.toString() };
}
toExtendedJSON() {
return { $numberDecimal: this.toString() };
}
static fromExtendedJSON(doc) {
return Decimal128.fromString(doc.$numberDecimal);
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
return `new Decimal128("${this.toString()}")`;
}
}
class Double extends BSONValue {
get _bsontype() {
return 'Double';
}
constructor(value) {
super();
if (value instanceof Number) {
value = value.valueOf();
}
this.value = +value;
}
valueOf() {
return this.value;
}
toJSON() {
return this.value;
}
toString(radix) {
return this.value.toString(radix);
}
toExtendedJSON(options) {
if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
return this.value;
}
if (Object.is(Math.sign(this.value), -0)) {
return { $numberDouble: '-0.0' };
}
return {
$numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
};
}
static fromExtendedJSON(doc, options) {
const doubleValue = parseFloat(doc.$numberDouble);
return options && options.relaxed ? doubleValue : new Double(doubleValue);
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
const eJSON = this.toExtendedJSON();
return `new Double(${eJSON.$numberDouble})`;
}
}
class Int32 extends BSONValue {
get _bsontype() {
return 'Int32';
}
constructor(value) {
super();
if (value instanceof Number) {
value = value.valueOf();
}
this.value = +value | 0;
}
valueOf() {
return this.value;
}
toString(radix) {
return this.value.toString(radix);
}
toJSON() {
return this.value;
}
toExtendedJSON(options) {
if (options && (options.relaxed || options.legacy))
return this.value;
return { $numberInt: this.value.toString() };
}
static fromExtendedJSON(doc, options) {
return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
return `new Int32(${this.valueOf()})`;
}
}
class MaxKey extends BSONValue {
get _bsontype() {
return 'MaxKey';
}
toExtendedJSON() {
return { $maxKey: 1 };
}
static fromExtendedJSON() {
return new MaxKey();
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
return 'new MaxKey()';
}
}
class MinKey extends BSONValue {
get _bsontype() {
return 'MinKey';
}
toExtendedJSON() {
return { $minKey: 1 };
}
static fromExtendedJSON() {
return new MinKey();
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
return 'new MinKey()';
}
}
const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
let PROCESS_UNIQUE = null;
const kId = Symbol('id');
class ObjectId extends BSONValue {
get _bsontype() {
return 'ObjectId';
}
constructor(inputId) {
super();
let workingId;
if (typeof inputId === 'object' && inputId && 'id' in inputId) {
if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
}
if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
workingId = ByteUtils.fromHex(inputId.toHexString());
}
else {
workingId = inputId.id;
}
}
else {
workingId = inputId;
}
if (workingId == null || typeof workingId === 'number') {
this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
}
else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
this[kId] = ByteUtils.toLocalBufferType(workingId);
}
else if (typeof workingId === 'string') {
if (workingId.length === 12) {
const bytes = ByteUtils.fromUTF8(workingId);
if (bytes.byteLength === 12) {
this[kId] = bytes;
}
else {
throw new BSONError('Argument passed in must be a string of 12 bytes');
}
}
else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
this[kId] = ByteUtils.fromHex(workingId);
}
else {
throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer');
}
}
else {
throw new BSONError('Argument passed in does not match the accepted types');
}
if (ObjectId.cacheHexString) {
this.__id = ByteUtils.toHex(this.id);
}
}
get id() {
return this[kId];
}
set id(value) {
this[kId] = value;
if (ObjectId.cacheHexString) {
this.__id = ByteUtils.toHex(value);
}
}
toHexString() {
if (ObjectId.cacheHexString && this.__id) {
return this.__id;
}
const hexString = ByteUtils.toHex(this.id);
if (ObjectId.cacheHexString && !this.__id) {
this.__id = hexString;
}
return hexString;
}
static getInc() {
return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
}
static generate(time) {
if ('number' !== typeof time) {
time = Math.floor(Date.now() / 1000);
}
const inc = ObjectId.getInc();
const buffer = ByteUtils.allocate(12);
BSONDataView.fromUint8Array(buffer).setUint32(0, time, false);
if (PROCESS_UNIQUE === null) {
PROCESS_UNIQUE = ByteUtils.randomBytes(5);
}
buffer[4] = PROCESS_UNIQUE[0];
buffer[5] = PROCESS_UNIQUE[1];
buffer[6] = PROCESS_UNIQUE[2];
buffer[7] = PROCESS_UNIQUE[3];
buffer[8] = PROCESS_UNIQUE[4];
buffer[11] = inc & 0xff;
buffer[10] = (inc >> 8) & 0xff;
buffer[9] = (inc >> 16) & 0xff;
return buffer;
}
toString(encoding) {
if (encoding === 'base64')
return ByteUtils.toBase64(this.id);
if (encoding === 'hex')
return this.toHexString();
return this.toHexString();
}
toJSON() {
return this.toHexString();
}
equals(otherId) {
if (otherId === undefined || otherId === null) {
return false;
}
if (otherId instanceof ObjectId) {
return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]);
}
if (typeof otherId === 'string' &&
ObjectId.isValid(otherId) &&
otherId.length === 12 &&
isUint8Array(this.id)) {
return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId));
}
if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) {
return otherId.toLowerCase() === this.toHexString();
}
if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) {
return ByteUtils.equals(ByteUtils.fromUTF8(otherId), this.id);
}
if (typeof otherId === 'object' &&
'toHexString' in otherId &&
typeof otherId.toHexString === 'function') {
const otherIdString = otherId.toHexString();
const thisIdString = this.toHexString().toLowerCase();
return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
}
return false;
}
getTimestamp() {
const timestamp = new Date();
const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false);
timestamp.setTime(Math.floor(time) * 1000);
return timestamp;
}
static createPk() {
return new ObjectId();
}
static createFromTime(time) {
const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
BSONDataView.fromUint8Array(buffer).setUint32(0, time, false);
return new ObjectId(buffer);
}
static createFromHexString(hexString) {
if (hexString?.length !== 24) {
throw new BSONError('hex string must be 24 characters');
}
return new ObjectId(ByteUtils.fromHex(hexString));
}
static createFromBase64(base64) {
if (base64?.length !== 16) {
throw new BSONError('base64 string must be 16 characters');
}
return new ObjectId(ByteUtils.fromBase64(base64));
}
static isValid(id) {
if (id == null)
return false;
try {
new ObjectId(id);
return true;
}
catch {
return false;
}
}
toExtendedJSON() {
if (this.toHexString)
return { $oid: this.toHexString() };
return { $oid: this.toString('hex') };
}
static fromExtendedJSON(doc) {
return new ObjectId(doc.$oid);
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
return `new ObjectId("${this.toHexString()}")`;
}
}
ObjectId.index = Math.floor(Math.random() * 0xffffff);
function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
let totalLength = 4 + 1;
if (Array.isArray(object)) {
for (let i = 0; i < object.length; i++) {
totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
}
}
else {
if (typeof object?.toBSON === 'function') {
object = object.toBSON();
}
for (const key of Object.keys(object)) {
totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
}
}
return totalLength;
}
function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
if (typeof value?.toBSON === 'function') {
value = value.toBSON();
}
switch (typeof value) {
case 'string':
return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
case 'number':
if (Math.floor(value) === value &&
value >= JS_INT_MIN &&
value <= JS_INT_MAX) {
if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
}
else {
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
}
}
else {
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
}
case 'undefined':
if (isArray || !ignoreUndefined)
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
return 0;
case 'boolean':
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
case 'object':
if (value != null &&
typeof value._bsontype === 'string' &&
value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
throw new BSONVersionError();
}
else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
}
else if (value._bsontype === 'ObjectId') {
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
}
else if (value instanceof Date || isDate(value)) {
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
}
else if (ArrayBuffer.isView(value) ||
value instanceof ArrayBuffer ||
isAnyArrayBuffer(value)) {
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength);
}
else if (value._bsontype === 'Long' ||
value._bsontype === 'Double' ||
value._bsontype === 'Timestamp') {
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
}
else if (value._bsontype === 'Decimal128') {
return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
}
else if (value._bsontype === 'Code') {
if (value.scope != null && Object.keys(value.scope).length > 0) {
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
1 +
4 +
4 +
ByteUtils.utf8ByteLength(value.code.toString()) +
1 +
internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
}
else {
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
1 +
4 +
ByteUtils.utf8ByteLength(value.code.toString()) +
1);
}
}
else if (value._bsontype === 'Binary') {
const binary = value;
if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
(binary.position + 1 + 4 + 1 + 4));
}
else {
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1));
}
}
else if (value._bsontype === 'Symbol') {
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
ByteUtils.utf8ByteLength(value.value) +
4 +
1 +
1);
}
else if (value._bsontype === 'DBRef') {
const ordered_values = Object.assign({
$ref: value.collection,
$id: value.oid
}, value.fields);
if (value.db != null) {
ordered_values['$db'] = value.db;
}
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
1 +
internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
}
else if (value instanceof RegExp || isRegExp(value)) {
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
1 +
ByteUtils.utf8ByteLength(value.source) +
1 +
(value.global ? 1 : 0) +
(value.ignoreCase ? 1 : 0) +
(value.multiline ? 1 : 0) +
1);
}
else if (value._bsontype === 'BSONRegExp') {
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
1 +
ByteUtils.utf8ByteLength(value.pattern) +
1 +
ByteUtils.utf8ByteLength(value.options) +
1);
}
else {
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) +
1);
}
case 'function':
if (serializeFunctions) {
return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
1 +
4 +
ByteUtils.utf8ByteLength(value.toString()) +
1);
}
}
return 0;
}
function alphabetize(str) {
return str.split('').sort().join('');
}
class BSONRegExp extends BSONValue {
get _bsontype() {
return 'BSONRegExp';
}
constructor(pattern, options) {
super();
this.pattern = pattern;
this.options = alphabetize(options ?? '');
if (this.pattern.indexOf('\x00') !== -1) {
throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
}
if (this.options.indexOf('\x00') !== -1) {
throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
}
for (let i = 0; i < this.options.length; i++) {
if (!(this.options[i] === 'i' ||
this.options[i] === 'm' ||
this.options[i] === 'x' ||
this.options[i] === 'l' ||
this.options[i] === 's' ||
this.options[i] === 'u')) {
throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
}
}
}
static parseOptions(options) {
return options ? options.split('').sort().join('') : '';
}
toExtendedJSON(options) {
options = options || {};
if (options.legacy) {
return { $regex: this.pattern, $options: this.options };
}
return { $regularExpression: { pattern: this.pattern, options: this.options } };
}
static fromExtendedJSON(doc) {
if ('$regex' in doc) {
if (typeof doc.$regex !== 'string') {
if (doc.$regex._bsontype === 'BSONRegExp') {
return doc;
}
}
else {
return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
}
}
if ('$regularExpression' in doc) {
return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
}
throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`;
}
}
class BSONSymbol extends BSONValue {
get _bsontype() {
return 'BSONSymbol';
}
constructor(value) {
super();
this.value = value;
}
valueOf() {
return this.value;
}
toString() {
return this.value;
}
inspect() {
return `new BSONSymbol("${this.value}")`;
}
toJSON() {
return this.value;
}
toExtendedJSON() {
return { $symbol: this.value };
}
static fromExtendedJSON(doc) {
return new BSONSymbol(doc.$symbol);
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
}
const LongWithoutOverridesClass = Long;
class Timestamp extends LongWithoutOverridesClass {
get _bsontype() {
return 'Timestamp';
}
constructor(low) {
if (low == null) {
super(0, 0, true);
}
else if (typeof low === 'bigint') {
super(low, true);
}
else if (Long.isLong(low)) {
super(low.low, low.high, true);
}
else if (typeof low === 'object' && 't' in low && 'i' in low) {
if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) {
throw new BSONError('Timestamp constructed from { t, i } must provide t as a number');
}
if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) {
throw new BSONError('Timestamp constructed from { t, i } must provide i as a number');
}
const t = Number(low.t);
const i = Number(low.i);
if (t < 0 || Number.isNaN(t)) {
throw new BSONError('Timestamp constructed from { t, i } must provide a positive t');
}
if (i < 0 || Number.isNaN(i)) {
throw new BSONError('Timestamp constructed from { t, i } must provide a positive i');
}
if (t > 4294967295) {
throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max');
}
if (i > 4294967295) {
throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max');
}
super(i, t, true);
}
else {
throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }');
}
}
toJSON() {
return {
$timestamp: this.toString()
};
}
static fromInt(value) {
return new Timestamp(Long.fromInt(value, true));
}
static fromNumber(value) {
return new Timestamp(Long.fromNumber(value, true));
}
static fromBits(lowBits, highBits) {
return new Timestamp({ i: lowBits, t: highBits });
}
static fromString(str, optRadix) {
return new Timestamp(Long.fromString(str, true, optRadix));
}
toExtendedJSON() {
return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } };
}
static fromExtendedJSON(doc) {
const i = Long.isLong(doc.$timestamp.i)
? doc.$timestamp.i.getLowBitsUnsigned()
: doc.$timestamp.i;
const t = Long.isLong(doc.$timestamp.t)
? doc.$timestamp.t.getLowBitsUnsigned()
: doc.$timestamp.t;
return new Timestamp({ t, i });
}
[Symbol.for('nodejs.util.inspect.custom')]() {
return this.inspect();
}
inspect() {
return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`;
}
}
Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
const FIRST_BIT = 0x80;
const FIRST_TWO_BITS = 0xc0;
const FIRST_THREE_BITS = 0xe0;
const FIRST_FOUR_BITS = 0xf0;
const FIRST_FIVE_BITS = 0xf8;
const TWO_BIT_CHAR = 0xc0;
const THREE_BIT_CHAR = 0xe0;
const FOUR_BIT_CHAR = 0xf0;
const CONTINUING_CHAR = 0x80;
function validateUtf8(bytes, start, end) {
let continuation = 0;
for (let i = start; i < end; i += 1) {
const byte = bytes[i];
if (continuation) {
if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
return false;
}
continuation -= 1;
}
else if (byte & FIRST_BIT) {
if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
continuation = 1;
}
else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
continuation = 2;
}
else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
continuation = 3;
}
else {
return false;
}
}
}
return !continuation;
}
const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
function internalDeserialize(buffer, options, isArray) {
options = options == null ? {} : options;
const index = options && options.index ? options.index : 0;
const size = buffer[index] |
(buffer[index + 1] << 8) |
(buffer[index + 2] << 16) |
(buffer[index + 3] << 24);
if (size < 5) {
throw new BSONError(`bson size must be >= 5, is ${size}`);
}
if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`);
}
if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`);
}
if (size + index > buffer.byteLength) {
throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`);
}
if (buffer[index + size - 1] !== 0) {
throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
}
return deserializeObject(buffer, index, options, isArray);
}
const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
function deserializeObject(buffer, index, options, isArray = false) {
const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
const raw = options['raw'] == null ? false : options['raw'];
const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
const promoteBuffers = options.promoteBuffers ?? false;
const promoteLongs = options.promoteLongs ?? true;
const promoteValues = options.promoteValues ?? true;
const useBigInt64 = options.useBigInt64 ?? false;
if (useBigInt64 && !promoteValues) {
throw new BSONError('Must either request bigint or Long for int64 deserialization');
}
if (useBigInt64 && !promoteLongs) {
throw new BSONError('Must either request bigint or Long for int64 deserialization');
}
const validation = options.validation == null ? { utf8: true } : options.validation;
let globalUTFValidation = true;
let validationSetting;
const utf8KeysSet = new Set();
const utf8ValidatedKeys = validation.utf8;
if (typeof utf8ValidatedKeys === 'boolean') {
validationSetting = utf8ValidatedKeys;
}
else {
globalUTFValidation = false;
const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
return utf8ValidatedKeys[key];
});
if (utf8ValidationValues.length === 0) {
throw new BSONError('UTF-8 validation setting cannot be empty');
}
if (typeof utf8ValidationValues[0] !== 'boolean') {
throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
}
validationSetting = utf8ValidationValues[0];
if (!utf8ValidationValues.every(item => item === validationSetting)) {
throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
}
}
if (!globalUTFValidation) {
for (const key of Object.keys(utf8ValidatedKeys)) {
utf8KeysSet.add(key);
}
}
const startIndex = index;
if (buffer.length < 5)
throw new BSONError('corrupt bson message < 5 bytes long');
const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
if (size < 5 || size > buffer.length)
throw new BSONError('corrupt bson message');
const object = isArray ? [] : {};
let arrayIndex = 0;
const done = false;
let isPossibleDBRef = isArray ? false : null;
const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
while (!done) {
const elementType = buffer[index++];
if (elementType === 0)
break;
let i = index;
while (buffer[i] !== 0x00 && i < buffer.length) {
i++;
}
if (i >= buffer.byteLength)
throw new BSONError('Bad BSON Document: illegal CString');
const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i);
let shouldValidateKey = true;
if (globalUTFValidation || utf8KeysSet.has(name)) {
shouldValidateKey = validationSetting;
}
else {
shouldValidateKey = !validationSetting;
}
if (isPossibleDBRef !== false && name[0] === '$') {
isPossibleDBRef = allowedDBRefKeys.test(name);
}
let value;
index = i + 1;
if (elementType === BSON_DATA_STRING) {
const stringSize = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
if (stringSize <= 0 ||
stringSize > buffer.length - index ||
buffer[index + stringSize - 1] !== 0) {
throw new BSONError('bad string length in bson');
}
value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
index = index + stringSize;
}
else if (elementType === BSON_DATA_OID) {
const oid = ByteUtils.allocate(12);
oid.set(buffer.subarray(index, index + 12));
value = new ObjectId(oid);
index = index + 12;
}
else if (elementType === BSON_DATA_INT && promoteValues === false) {
value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24));
}
else if (elementType === BSON_DATA_INT) {
value =
buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
}
else if (elementType === BSON_DATA_NUMBER && promoteValues === false) {
value = new Double(dataview.getFloat64(index, true));
index = index + 8;
}
else if (elementType === BSON_DATA_NUMBER) {
value = dataview.getFloat64(index, true);
index = index + 8;
}
else if (elementType === BSON_DATA_DATE) {
const lowBits = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
const highBits = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
value = new Date(new Long(lowBits, highBits).toNumber());
}
else if (elementType === BSON_DATA_BOOLEAN) {
if (buffer[index] !== 0 && buffer[index] !== 1)
throw new BSONError('illegal boolean type value');
value = buffer[index++] === 1;
}
else if (elementType === BSON_DATA_OBJECT) {
const _index = index;
const objectSize = buffer[index] |
(buffer[index + 1] << 8) |
(buffer[index + 2] << 16) |
(buffer[index + 3] << 24);
if (objectSize <= 0 || objectSize > buffer.length - index)
throw new BSONError('bad embedded document length in bson');
if (raw) {
value = buffer.slice(index, index + objectSize);
}
else {
let objectOptions = options;
if (!globalUTFValidation) {
objectOptions = { ...options, validation: { utf8: shouldValidateKey } };
}
value = deserializeObject(buffer, _index, objectOptions, false);
}
index = index + objectSize;
}
else if (elementType === BSON_DATA_ARRAY) {
const _index = index;
const objectSize = buffer[index] |
(buffer[index + 1] << 8) |
(buffer[index + 2] << 16) |
(buffer[index + 3] << 24);
let arrayOptions = options;
const stopIndex = index + objectSize;
if (fieldsAsRaw && fieldsAsRaw[name]) {
arrayOptions = { ...options, raw: true };
}
if (!globalUTFValidation) {
arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } };
}
value = deserializeObject(buffer, _index, arrayOptions, true);
index = index + objectSize;
if (buffer[index - 1] !== 0)
throw new BSONError('invalid array terminator byte');
if (index !== stopIndex)
throw new BSONError('corrupted array bson');
}
else if (elementType === BSON_DATA_UNDEFINED) {
value = undefined;
}
else if (elementType === BSON_DATA_NULL) {
value = null;
}
else if (elementType === BSON_DATA_LONG) {
const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8));
const lowBits = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
const highBits = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
const long = new Long(lowBits, highBits);
if (useBigInt64) {
value = dataview.getBigInt64(0, true);
}
else if (promoteLongs && promoteValues === true) {
value =
long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
? long.toNumber()
: long;
}
else {
value = long;
}
}
else if (elementType === BSON_DATA_DECIMAL128) {
const bytes = ByteUtils.allocate(16);
bytes.set(buffer.subarray(index, index + 16), 0);
index = index + 16;
value = new Decimal128(bytes);
}
else if (elementType === BSON_DATA_BINARY) {
let binarySize = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
const totalBinarySize = binarySize;
const subType = buffer[index++];
if (binarySize < 0)
throw new BSONError('Negative binary type element size found');
if (binarySize > buffer.byteLength)
throw new BSONError('Binary type size larger than document size');
if (buffer['slice'] != null) {
if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
binarySize =
buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
if (binarySize < 0)
throw new BSONError('Negative binary type element size found for subtype 0x02');
if (binarySize > totalBinarySize - 4)
throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
if (binarySize < totalBinarySize - 4)
throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
}
if (promoteBuffers && promoteValues) {
value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize));
}
else {
value = new Binary(buffer.slice(index, index + binarySize), subType);
if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
value = value.toUUID();
}
}
}
else {
const _buffer = ByteUtils.allocate(binarySize);
if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
binarySize =
buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
if (binarySize < 0)
throw new BSONError('Negative binary type element size found for subtype 0x02');
if (binarySize > totalBinarySize - 4)
throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
if (binarySize < totalBinarySize - 4)
throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
}
for (i = 0; i < binarySize; i++) {
_buffer[i] = buffer[index + i];
}
if (promoteBuffers && promoteValues) {
value = _buffer;
}
else {
value = new Binary(buffer.slice(index, index + binarySize), subType);
if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
value = value.toUUID();
}
}
}
index = index + binarySize;
}
else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
i = index;
while (buffer[i] !== 0x00 && i < buffer.length) {
i++;
}
if (i >= buffer.length)
throw new BSONError('Bad BSON Document: illegal CString');
const source = ByteUtils.toUTF8(buffer, index, i);
index = i + 1;
i = index;
while (buffer[i] !== 0x00 && i < buffer.length) {
i++;
}
if (i >= buffer.length)
throw new BSONError('Bad BSON Document: illegal CString');
const regExpOptions = ByteUtils.toUTF8(buffer, index, i);
index = i + 1;
const optionsArray = new Array(regExpOptions.length);
for (i = 0; i < regExpOptions.length; i++) {
switch (regExpOptions[i]) {
case 'm':
optionsArray[i] = 'm';
break;
case 's':
optionsArray[i] = 'g';
break;
case 'i':
optionsArray[i] = 'i';
break;
}
}
value = new RegExp(source, optionsArray.join(''));
}
else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
i = index;
while (buffer[i] !== 0x00 && i < buffer.length) {
i++;
}
if (i >= buffer.length)
throw new BSONError('Bad BSON Document: illegal CString');
const source = ByteUtils.toUTF8(buffer, index, i);
index = i + 1;
i = index;
while (buffer[i] !== 0x00 && i < buffer.length) {
i++;
}
if (i >= buffer.length)
throw new BSONError('Bad BSON Document: illegal CString');
const regExpOptions = ByteUtils.toUTF8(buffer, index, i);
index = i + 1;
value = new BSONRegExp(source, regExpOptions);
}
else if (elementType === BSON_DATA_SYMBOL) {
const stringSize = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
if (stringSize <= 0 ||
stringSize > buffer.length - index ||
buffer[index + stringSize - 1] !== 0) {
throw new BSONError('bad string length in bson');
}
const symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
value = promoteValues ? symbol : new BSONSymbol(symbol);
index = index + stringSize;
}
else if (elementType === BSON_DATA_TIMESTAMP) {
const i = buffer[index++] +
buffer[index++] * (1 << 8) +
buffer[index++] * (1 << 16) +
buffer[index++] * (1 << 24);
const t = buffer[index++] +
buffer[index++] * (1 << 8) +
buffer[index++] * (1 << 16) +
buffer[index++] * (1 << 24);
value = new Timestamp({ i, t });
}
else if (elementType === BSON_DATA_MIN_KEY) {
value = new MinKey();
}
else if (elementType === BSON_DATA_MAX_KEY) {
value = new MaxKey();
}
else if (elementType === BSON_DATA_CODE) {
const stringSize = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
if (stringSize <= 0 ||
stringSize > buffer.length - index ||
buffer[index + stringSize - 1] !== 0) {
throw new BSONError('bad string length in bson');
}
const functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
value = new Code(functionString);
index = index + stringSize;
}
else if (elementType === BSON_DATA_CODE_W_SCOPE) {
const totalSize = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
if (totalSize < 4 + 4 + 4 + 1) {
throw new BSONError('code_w_scope total size shorter minimum expected length');
}
const stringSize = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
if (stringSize <= 0 ||
stringSize > buffer.length - index ||
buffer[index + stringSize - 1] !== 0) {
throw new BSONError('bad string length in bson');
}
const functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
index = index + stringSize;
const _index = index;
const objectSize = buffer[index] |
(buffer[index + 1] << 8) |
(buffer[index + 2] << 16) |
(buffer[index + 3] << 24);
const scopeObject = deserializeObject(buffer, _index, options, false);
index = index + objectSize;
if (totalSize < 4 + 4 + objectSize + stringSize) {
throw new BSONError('code_w_scope total size is too short, truncating scope');
}
if (totalSize > 4 + 4 + objectSize + stringSize) {
throw new BSONError('code_w_scope total size is too long, clips outer document');
}
value = new Code(functionString, scopeObject);
}
else if (elementType === BSON_DATA_DBPOINTER) {
const stringSize = buffer[index++] |
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);
if (stringSize <= 0 ||
stringSize > buffer.length - index ||
buffer[index + stringSize - 1] !== 0)
throw new BSONError('bad string length in bson');
if (validation != null && validation.utf8) {
if (!validateUtf8(buffer, index, index + stringSize - 1)) {
throw new BSONError('Invalid UTF-8 string in BSON document');
}
}
const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1);
index = index + stringSize;
const oidBuffer = ByteUtils.allocate(12);
oidBuffer.set(buffer.subarray(index, index + 12), 0);
const oid = new ObjectId(oidBuffer);
index = index + 12;
value = new DBRef(namespace, oid);
}
else {
throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
}
if (name === '__proto__') {
Object.defineProperty(object, name, {
value,
writable: true,
enumerable: true,
configurable: true
});
}
else {
object[name] = value;
}
}
if (size !== index - startIndex) {
if (isArray)
throw new BSONError('corrupt array bson');
throw new BSONError('corrupt object bson');
}
if (!isPossibleDBRef)
return object;
if (isDBRefLike(object)) {
const copy = Object.assign({}, object);
delete copy.$ref;
delete copy.$id;
delete copy.$db;
return new DBRef(object.$ref, object.$id, object.$db, copy);
}
return object;
}
function getValidatedString(buffer, start, end, shouldValidateUtf8) {
const value = ByteUtils.toUTF8(buffer, start, end);
if (shouldValidateUtf8) {
for (let i = 0; i < value.length; i++) {
if (value.charCodeAt(i) === 0xfffd) {
if (!validateUtf8(buffer, start, end)) {
throw new BSONError('Invalid UTF-8 string in BSON document');
}
break;
}
}
}
return value;
}
const regexp = /\x00/;
const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
function serializeString(buffer, key, value, index) {
buffer[index++] = BSON_DATA_STRING;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes + 1;
buffer[index - 1] = 0;
const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4);
buffer[index + 3] = ((size + 1) >> 24) & 0xff;
buffer[index + 2] = ((size + 1) >> 16) & 0xff;
buffer[index + 1] = ((size + 1) >> 8) & 0xff;
buffer[index] = (size + 1) & 0xff;
index = index + 4 + size;
buffer[index++] = 0;
return index;
}
const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8);
const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4);
const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8);
function serializeNumber(buffer, key, value, index) {
const isNegativeZero = Object.is(value, -0);
const type = !isNegativeZero &&
Number.isSafeInteger(value) &&
value <= BSON_INT32_MAX &&
value >= BSON_INT32_MIN
? BSON_DATA_INT
: BSON_DATA_NUMBER;
if (type === BSON_DATA_INT) {
NUMBER_SPACE.setInt32(0, value, true);
}
else {
NUMBER_SPACE.setFloat64(0, value, true);
}
const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER;
buffer[index++] = type;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0x00;
buffer.set(bytes, index);
index += bytes.byteLength;
return index;
}
function serializeBigInt(buffer, key, value, index) {
buffer[index++] = BSON_DATA_LONG;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index += numberOfWrittenBytes;
buffer[index++] = 0;
NUMBER_SPACE.setBigInt64(0, value, true);
buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index);
index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;
return index;
}
function serializeNull(buffer, key, _, index) {
buffer[index++] = BSON_DATA_NULL;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
return index;
}
function serializeBoolean(buffer, key, value, index) {
buffer[index++] = BSON_DATA_BOOLEAN;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
buffer[index++] = value ? 1 : 0;
return index;
}
function serializeDate(buffer, key, value, index) {
buffer[index++] = BSON_DATA_DATE;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
const dateInMilis = Long.fromNumber(value.getTime());
const lowBits = dateInMilis.getLowBits();
const highBits = dateInMilis.getHighBits();
buffer[index++] = lowBits & 0xff;
buffer[index++] = (lowBits >> 8) & 0xff;
buffer[index++] = (lowBits >> 16) & 0xff;
buffer[index++] = (lowBits >> 24) & 0xff;
buffer[index++] = highBits & 0xff;
buffer[index++] = (highBits >> 8) & 0xff;
buffer[index++] = (highBits >> 16) & 0xff;
buffer[index++] = (highBits >> 24) & 0xff;
return index;
}
function serializeRegExp(buffer, key, value, index) {
buffer[index++] = BSON_DATA_REGEXP;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
if (value.source && value.source.match(regexp) != null) {
throw new BSONError('value ' + value.source + ' must not contain null bytes');
}
index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index);
buffer[index++] = 0x00;
if (value.ignoreCase)
buffer[index++] = 0x69;
if (value.global)
buffer[index++] = 0x73;
if (value.multiline)
buffer[index++] = 0x6d;
buffer[index++] = 0x00;
return index;
}
function serializeBSONRegExp(buffer, key, value, index) {
buffer[index++] = BSON_DATA_REGEXP;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
if (value.pattern.match(regexp) != null) {
throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
}
index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index);
buffer[index++] = 0x00;
const sortedOptions = value.options.split('').sort().join('');
index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index);
buffer[index++] = 0x00;
return index;
}
function serializeMinMax(buffer, key, value, index) {
if (value === null) {
buffer[index++] = BSON_DATA_NULL;
}
else if (value._bsontype === 'MinKey') {
buffer[index++] = BSON_DATA_MIN_KEY;
}
else {
buffer[index++] = BSON_DATA_MAX_KEY;
}
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
return index;
}
function serializeObjectId(buffer, key, value, index) {
buffer[index++] = BSON_DATA_OID;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
if (isUint8Array(value.id)) {
buffer.set(value.id.subarray(0, 12), index);
}
else {
throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
}
return index + 12;
}
function serializeBuffer(buffer, key, value, index) {
buffer[index++] = BSON_DATA_BINARY;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
const size = value.length;
buffer[index++] = size & 0xff;
buffer[index++] = (size >> 8) & 0xff;
buffer[index++] = (size >> 16) & 0xff;
buffer[index++] = (size >> 24) & 0xff;
buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
buffer.set(value, index);
index = index + size;
return index;
}
function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) {
if (path.has(value)) {
throw new BSONError('Cannot convert circular structure to BSON');
}
path.add(value);
buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
path.delete(value);
return endIndex;
}
function serializeDecimal128(buffer, key, value, index) {
buffer[index++] = BSON_DATA_DECIMAL128;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
buffer.set(value.bytes.subarray(0, 16), index);
return index + 16;
}
function serializeLong(buffer, key, value, index) {
buffer[index++] =
value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
const lowBits = value.getLowBits();
const highBits = value.getHighBits();
buffer[index++] = lowBits & 0xff;
buffer[index++] = (lowBits >> 8) & 0xff;
buffer[index++] = (lowBits >> 16) & 0xff;
buffer[index++] = (lowBits >> 24) & 0xff;
buffer[index++] = highBits & 0xff;
buffer[index++] = (highBits >> 8) & 0xff;
buffer[index++] = (highBits >> 16) & 0xff;
buffer[index++] = (highBits >> 24) & 0xff;
return index;
}
function serializeInt32(buffer, key, value, index) {
value = value.valueOf();
buffer[index++] = BSON_DATA_INT;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
buffer[index++] = value & 0xff;
buffer[index++] = (value >> 8) & 0xff;
buffer[index++] = (value >> 16) & 0xff;
buffer[index++] = (value >> 24) & 0xff;
return index;
}
function serializeDouble(buffer, key, value, index) {
buffer[index++] = BSON_DATA_NUMBER;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
NUMBER_SPACE.setFloat64(0, value.value, true);
buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index);
index = index + 8;
return index;
}
function serializeFunction(buffer, key, value, index) {
buffer[index++] = BSON_DATA_CODE;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
const functionString = value.toString();
const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
buffer[index] = size & 0xff;
buffer[index + 1] = (size >> 8) & 0xff;
buffer[index + 2] = (size >> 16) & 0xff;
buffer[index + 3] = (size >> 24) & 0xff;
index = index + 4 + size - 1;
buffer[index++] = 0;
return index;
}
function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) {
if (value.scope && typeof value.scope === 'object') {
buffer[index++] = BSON_DATA_CODE_W_SCOPE;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
let startIndex = index;
const functionString = value.code;
index = index + 4;
const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
buffer[index] = codeSize & 0xff;
buffer[index + 1] = (codeSize >> 8) & 0xff;
buffer[index + 2] = (codeSize >> 16) & 0xff;
buffer[index + 3] = (codeSize >> 24) & 0xff;
buffer[index + 4 + codeSize - 1] = 0;
index = index + codeSize + 4;
const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
index = endIndex - 1;
const totalSize = endIndex - startIndex;
buffer[startIndex++] = totalSize & 0xff;
buffer[startIndex++] = (totalSize >> 8) & 0xff;
buffer[startIndex++] = (totalSize >> 16) & 0xff;
buffer[startIndex++] = (totalSize >> 24) & 0xff;
buffer[index++] = 0;
}
else {
buffer[index++] = BSON_DATA_CODE;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
const functionString = value.code.toString();
const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
buffer[index] = size & 0xff;
buffer[index + 1] = (size >> 8) & 0xff;
buffer[index + 2] = (size >> 16) & 0xff;
buffer[index + 3] = (size >> 24) & 0xff;
index = index + 4 + size - 1;
buffer[index++] = 0;
}
return index;
}
function serializeBinary(buffer, key, value, index) {
buffer[index++] = BSON_DATA_BINARY;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
const data = value.buffer;
let size = value.position;
if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
size = size + 4;
buffer[index++] = size & 0xff;
buffer[index++] = (size >> 8) & 0xff;
buffer[index++] = (size >> 16) & 0xff;
buffer[index++] = (size >> 24) & 0xff;
buffer[index++] = value.sub_type;
if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
size = size - 4;
buffer[index++] = size & 0xff;
buffer[index++] = (size >> 8) & 0xff;
buffer[index++] = (size >> 16) & 0xff;
buffer[index++] = (size >> 24) & 0xff;
}
buffer.set(data, index);
index = index + value.position;
return index;
}
function serializeSymbol(buffer, key, value, index) {
buffer[index++] = BSON_DATA_SYMBOL;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1;
buffer[index] = size & 0xff;
buffer[index + 1] = (size >> 8) & 0xff;
buffer[index + 2] = (size >> 16) & 0xff;
buffer[index + 3] = (size >> 24) & 0xff;
index = index + 4 + size - 1;
buffer[index++] = 0x00;
return index;
}
function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) {
buffer[index++] = BSON_DATA_OBJECT;
const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
let startIndex = index;
let output = {
$ref: value.collection || value.namespace,
$id: value.oid
};
if (value.db != null) {
output.$db = value.db;
}
output = Object.assign(output, value.fields);
const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path);
const size = endIndex - startIndex;
buffer[startIndex++] = size & 0xff;
buffer[startIndex++] = (size >> 8) & 0xff;
buffer[startIndex++] = (size >> 16) & 0xff;
buffer[startIndex++] = (size >> 24) & 0xff;
return endIndex;
}
function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
if (path == null) {
if (object == null) {
buffer[0] = 0x05;
buffer[1] = 0x00;
buffer[2] = 0x00;
buffer[3] = 0x00;
buffer[4] = 0x00;
return 5;
}
if (Array.isArray(object)) {
throw new BSONError('serialize does not support an array as the root input');
}
if (typeof object !== 'object') {
throw new BSONError('serialize does not support non-object as the root input');
}
else if ('_bsontype' in object && typeof object._bsontype === 'string') {
throw new BSONError(`BSON types cannot be serialized as a document`);
}
else if (isDate(object) ||
isRegExp(object) ||
isUint8Array(object) ||
isAnyArrayBuffer(object)) {
throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
}
path = new Set();
}
path.add(object);
let index = startingIndex + 4;
if (Array.isArray(object)) {
for (let i = 0; i < object.length; i++) {
const key = `${i}`;
let value = object[i];
if (typeof value?.toBSON === 'function') {
value = value.toBSON();
}
if (typeof value === 'string') {
index = serializeString(buffer, key, value, index);
}
else if (typeof value === 'number') {
index = serializeNumber(buffer, key, value, index);
}
else if (typeof value === 'bigint') {
index = serializeBigInt(buffer, key, value, index);
}
else if (typeof value === 'boolean') {
index = serializeBoolean(buffer, key, value, index);
}
else if (value instanceof Date || isDate(value)) {
index = serializeDate(buffer, key, value, index);
}
else if (value === undefined) {
index = serializeNull(buffer, key, value, index);
}
else if (value === null) {
index = serializeNull(buffer, key, value, index);
}
else if (isUint8Array(value)) {
index = serializeBuffer(buffer, key, value, index);
}
else if (value instanceof RegExp || isRegExp(value)) {
index = serializeRegExp(buffer, key, value, index);
}
else if (typeof value === 'object' && value._bsontype == null) {
index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
}
else if (typeof value === 'object' &&
value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
throw new BSONVersionError();
}
else if (value._bsontype === 'ObjectId') {
index = serializeObjectId(buffer, key, value, index);
}
else if (value._bsontype === 'Decimal128') {
index = serializeDecimal128(buffer, key, value, index);
}
else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
index = serializeLong(buffer, key, value, index);
}
else if (value._bsontype === 'Double') {
index = serializeDouble(buffer, key, value, index);
}
else if (typeof value === 'function' && serializeFunctions) {
index = serializeFunction(buffer, key, value, index);
}
else if (value._bsontype === 'Code') {
index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
}
else if (value._bsontype === 'Binary') {
index = serializeBinary(buffer, key, value, index);
}
else if (value._bsontype === 'BSONSymbol') {
index = serializeSymbol(buffer, key, value, index);
}
else if (value._bsontype === 'DBRef') {
index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
}
else if (value._bsontype === 'BSONRegExp') {
index = serializeBSONRegExp(buffer, key, value, index);
}
else if (value._bsontype === 'Int32') {
index = serializeInt32(buffer, key, value, index);
}
else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
index = serializeMinMax(buffer, key, value, index);
}
else if (typeof value._bsontype !== 'undefined') {
throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
}
}
}
else if (object instanceof Map || isMap(object)) {
const iterator = object.entries();
let done = false;
while (!done) {
const entry = iterator.next();
done = !!entry.done;
if (done)
continue;
const key = entry.value[0];
let value = entry.value[1];
if (typeof value?.toBSON === 'function') {
value = value.toBSON();
}
const type = typeof value;
if (typeof key === 'string' && !ignoreKeys.has(key)) {
if (key.match(regexp) != null) {
throw new BSONError('key ' + key + ' must not contain null bytes');
}
if (checkKeys) {
if ('$' === key[0]) {
throw new BSONError('key ' + key + " must not start with '$'");
}
else if (~key.indexOf('.')) {
throw new BSONError('key ' + key + " must not contain '.'");
}
}
}
if (type === 'string') {
index = serializeString(buffer, key, value, index);
}
else if (type === 'number') {
index = serializeNumber(buffer, key, value, index);
}
else if (type === 'bigint') {
index = serializeBigInt(buffer, key, value, index);
}
else if (type === 'boolean') {
index = serializeBoolean(buffer, key, value, index);
}
else if (value instanceof Date || isDate(value)) {
index = serializeDate(buffer, key, value, index);
}
else if (value === null || (value === undefined && ignoreUndefined === false)) {
index = serializeNull(buffer, key, value, index);
}
else if (isUint8Array(value)) {
index = serializeBuffer(buffer, key, value, index);
}
else if (value instanceof RegExp || isRegExp(value)) {
index = serializeRegExp(buffer, key, value, index);
}
else if (type === 'object' && value._bsontype == null) {
index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
}
else if (typeof value === 'object' &&
value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
throw new BSONVersionError();
}
else if (value._bsontype === 'ObjectId') {
index = serializeObjectId(buffer, key, value, index);
}
else if (type === 'object' && value._bsontype === 'Decimal128') {
index = serializeDecimal128(buffer, key, value, index);
}
else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
index = serializeLong(buffer, key, value, index);
}
else if (value._bsontype === 'Double') {
index = serializeDouble(buffer, key, value, index);
}
else if (value._bsontype === 'Code') {
index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
}
else if (typeof value === 'function' && serializeFunctions) {
index = serializeFunction(buffer, key, value, index);
}
else if (value._bsontype === 'Binary') {
index = serializeBinary(buffer, key, value, index);
}
else if (value._bsontype === 'BSONSymbol') {
index = serializeSymbol(buffer, key, value, index);
}
else if (value._bsontype === 'DBRef') {
index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
}
else if (value._bsontype === 'BSONRegExp') {
index = serializeBSONRegExp(buffer, key, value, index);
}
else if (value._bsontype === 'Int32') {
index = serializeInt32(buffer, key, value, index);
}
else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
index = serializeMinMax(buffer, key, value, index);
}
else if (typeof value._bsontype !== 'undefined') {
throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
}
}
}
else {
if (typeof object?.toBSON === 'function') {
object = object.toBSON();
if (object != null && typeof object !== 'object') {
throw new BSONError('toBSON function did not return an object');
}
}
for (const key of Object.keys(object)) {
let value = object[key];
if (typeof value?.toBSON === 'function') {
value = value.toBSON();
}
const type = typeof value;
if (typeof key === 'string' && !ignoreKeys.has(key)) {
if (key.match(regexp) != null) {
throw new BSONError('key ' + key + ' must not contain null bytes');
}
if (checkKeys) {
if ('$' === key[0]) {
throw new BSONError('key ' + key + " must not start with '$'");
}
else if (~key.indexOf('.')) {
throw new BSONError('key ' + key + " must not contain '.'");
}
}
}
if (type === 'string') {
index = serializeString(buffer, key, value, index);
}
else if (type === 'number') {
index = serializeNumber(buffer, key, value, index);
}
else if (type === 'bigint') {
index = serializeBigInt(buffer, key, value, index);
}
else if (type === 'boolean') {
index = serializeBoolean(buffer, key, value, index);
}
else if (value instanceof Date || isDate(value)) {
index = serializeDate(buffer, key, value, index);
}
else if (value === undefined) {
if (ignoreUndefined === false)
index = serializeNull(buffer, key, value, index);
}
else if (value === null) {
index = serializeNull(buffer, key, value, index);
}
else if (isUint8Array(value)) {
index = serializeBuffer(buffer, key, value, index);
}
else if (value instanceof RegExp || isRegExp(value)) {
index = serializeRegExp(buffer, key, value, index);
}
else if (type === 'object' && value._bsontype == null) {
index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
}
else if (typeof value === 'object' &&
value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
throw new BSONVersionError();
}
else if (value._bsontype === 'ObjectId') {
index = serializeObjectId(buffer, key, value, index);
}
else if (type === 'object' && value._bsontype === 'Decimal128') {
index = serializeDecimal128(buffer, key, value, index);
}
else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
index = serializeLong(buffer, key, value, index);
}
else if (value._bsontype === 'Double') {
index = serializeDouble(buffer, key, value, index);
}
else if (value._bsontype === 'Code') {
index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
}
else if (typeof value === 'function' && serializeFunctions) {
index = serializeFunction(buffer, key, value, index);
}
else if (value._bsontype === 'Binary') {
index = serializeBinary(buffer, key, value, index);
}
else if (value._bsontype === 'BSONSymbol') {
index = serializeSymbol(buffer, key, value, index);
}
else if (value._bsontype === 'DBRef') {
index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
}
else if (value._bsontype === 'BSONRegExp') {
index = serializeBSONRegExp(buffer, key, value, index);
}
else if (value._bsontype === 'Int32') {
index = serializeInt32(buffer, key, value, index);
}
else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
index = serializeMinMax(buffer, key, value, index);
}
else if (typeof value._bsontype !== 'undefined') {
throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
}
}
}
path.delete(object);
buffer[index++] = 0x00;
const size = index - startingIndex;
buffer[startingIndex++] = size & 0xff;
buffer[startingIndex++] = (size >> 8) & 0xff;
buffer[startingIndex++] = (size >> 16) & 0xff;
buffer[startingIndex++] = (size >> 24) & 0xff;
return index;
}
function isBSONType(value) {
return (value != null &&
typeof value === 'object' &&
'_bsontype' in value &&
typeof value._bsontype === 'string');
}
const keysToCodecs = {
$oid: ObjectId,
$binary: Binary,
$uuid: Binary,
$symbol: BSONSymbol,
$numberInt: Int32,
$numberDecimal: Decimal128,
$numberDouble: Double,
$numberLong: Long,
$minKey: MinKey,
$maxKey: MaxKey,
$regex: BSONRegExp,
$regularExpression: BSONRegExp,
$timestamp: Timestamp
};
function deserializeValue(value, options = {}) {
if (typeof value === 'number') {
const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
if (options.relaxed || options.legacy) {
return value;
}
if (Number.isInteger(value) && !Object.is(value, -0)) {
if (in32BitRange) {
return new Int32(value);
}
if (in64BitRange) {
if (options.useBigInt64) {
return BigInt(value);
}
return Long.fromNumber(value);
}
}
return new Double(value);
}
if (value == null || typeof value !== 'object')
return value;
if (value.$undefined)
return null;
const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null);
for (let i = 0; i < keys.length; i++) {
const c = keysToCodecs[keys[i]];
if (c)
return c.fromExtendedJSON(value, options);
}
if (value.$date != null) {
const d = value.$date;
const date = new Date();
if (options.legacy) {
if (typeof d === 'number')
date.setTime(d);
else if (typeof d === 'string')
date.setTime(Date.parse(d));
else if (typeof d === 'bigint')
date.setTime(Number(d));
else
throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
}
else {
if (typeof d === 'string')
date.setTime(Date.parse(d));
else if (Long.isLong(d))
date.setTime(d.toNumber());
else if (typeof d === 'number' && options.relaxed)
date.setTime(d);
else if (typeof d === 'bigint')
date.setTime(Number(d));
else
throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
}
return date;
}
if (value.$code != null) {
const copy = Object.assign({}, value);
if (value.$scope) {
copy.$scope = deserializeValue(value.$scope);
}
return Code.fromExtendedJSON(value);
}
if (isDBRefLike(value) || value.$dbPointer) {
const v = value.$ref ? value : value.$dbPointer;
if (v instanceof DBRef)
return v;
const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
let valid = true;
dollarKeys.forEach(k => {
if (['$ref', '$id', '$db'].indexOf(k) === -1)
valid = false;
});
if (valid)
return DBRef.fromExtendedJSON(v);
}
return value;
}
function serializeArray(array, options) {
return array.map((v, index) => {
options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
try {
return serializeValue(v, options);
}
finally {
options.seenObjects.pop();
}
});
}
function getISOString(date) {
const isoStr = date.toISOString();
return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
}
function serializeValue(value, options) {
if (value instanceof Map || isMap(value)) {
const obj = Object.create(null);
for (const [k, v] of value) {
if (typeof k !== 'string') {
throw new BSONError('Can only serialize maps with string keys');
}
obj[k] = v;
}
return serializeValue(obj, options);
}
if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
const index = options.seenObjects.findIndex(entry => entry.obj === value);
if (index !== -1) {
const props = options.seenObjects.map(entry => entry.propertyName);
const leadingPart = props
.slice(0, index)
.map(prop => `${prop} -> `)
.join('');
const alreadySeen = props[index];
const circularPart = ' -> ' +
props
.slice(index + 1, props.length - 1)
.map(prop => `${prop} -> `)
.join('');
const current = props[props.length - 1];
const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
throw new BSONError('Converting circular structure to EJSON:\n' +
` ${leadingPart}${alreadySeen}${circularPart}${current}\n` +
` ${leadingSpace}\\${dashes}/`);
}
options.seenObjects[options.seenObjects.length - 1].obj = value;
}
if (Array.isArray(value))
return serializeArray(value, options);
if (value === undefined)
return null;
if (value instanceof Date || isDate(value)) {
const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000;
if (options.legacy) {
return options.relaxed && inRange
? { $date: value.getTime() }
: { $date: getISOString(value) };
}
return options.relaxed && inRange
? { $date: getISOString(value) }
: { $date: { $numberLong: value.getTime().toString() } };
}
if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
if (Number.isInteger(value) && !Object.is(value, -0)) {
if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
return { $numberInt: value.toString() };
}
if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
return { $numberLong: value.toString() };
}
}
return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() };
}
if (typeof value === 'bigint') {
if (!options.relaxed) {
return { $numberLong: BigInt.asIntN(64, value).toString() };
}
return Number(BigInt.asIntN(64, value));
}
if (value instanceof RegExp || isRegExp(value)) {
let flags = value.flags;
if (flags === undefined) {
const match = value.toString().match(/[gimuy]*$/);
if (match) {
flags = match[0];
}
}
const rx = new BSONRegExp(value.source, flags);
return rx.toExtendedJSON(options);
}
if (value != null && typeof value === 'object')
return serializeDocument(value, options);
return value;
}
const BSON_TYPE_MAPPINGS = {
Binary: (o) => new Binary(o.value(), o.sub_type),
Code: (o) => new Code(o.code, o.scope),
DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
Decimal128: (o) => new Decimal128(o.bytes),
Double: (o) => new Double(o.value),
Int32: (o) => new Int32(o.value),
Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_),
MaxKey: () => new MaxKey(),
MinKey: () => new MinKey(),
ObjectId: (o) => new ObjectId(o),
BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
BSONSymbol: (o) => new BSONSymbol(o.value),
Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
};
function serializeDocument(doc, options) {
if (doc == null || typeof doc !== 'object')
throw new BSONError('not an object instance');
const bsontype = doc._bsontype;
if (typeof bsontype === 'undefined') {
const _doc = {};
for (const name of Object.keys(doc)) {
options.seenObjects.push({ propertyName: name, obj: null });
try {
const value = serializeValue(doc[name], options);
if (name === '__proto__') {
Object.defineProperty(_doc, name, {
value,
writable: true,
enumerable: true,
configurable: true
});
}
else {
_doc[name] = value;
}
}
finally {
options.seenObjects.pop();
}
}
return _doc;
}
else if (doc != null &&
typeof doc === 'object' &&
typeof doc._bsontype === 'string' &&
doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
throw new BSONVersionError();
}
else if (isBSONType(doc)) {
let outDoc = doc;
if (typeof outDoc.toExtendedJSON !== 'function') {
const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
if (!mapper) {
throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
}
outDoc = mapper(outDoc);
}
if (bsontype === 'Code' && outDoc.scope) {
outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
}
else if (bsontype === 'DBRef' && outDoc.oid) {
outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
}
return outDoc.toExtendedJSON(options);
}
else {
throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
}
}
function parse(text, options) {
const ejsonOptions = {
useBigInt64: options?.useBigInt64 ?? false,
relaxed: options?.relaxed ?? true,
legacy: options?.legacy ?? false
};
return JSON.parse(text, (key, value) => {
if (key.indexOf('\x00') !== -1) {
throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
}
return deserializeValue(value, ejsonOptions);
});
}
function stringify(value, replacer, space, options) {
if (space != null && typeof space === 'object') {
options = space;
space = 0;
}
if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
options = replacer;
replacer = undefined;
space = 0;
}
const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
seenObjects: [{ propertyName: '(root)', obj: null }]
});
const doc = serializeValue(value, serializeOptions);
return JSON.stringify(doc, replacer, space);
}
function EJSONserialize(value, options) {
options = options || {};
return JSON.parse(stringify(value, options));
}
function EJSONdeserialize(ejson, options) {
options = options || {};
return parse(JSON.stringify(ejson), options);
}
const EJSON = Object.create(null);
EJSON.parse = parse;
EJSON.stringify = stringify;
EJSON.serialize = EJSONserialize;
EJSON.deserialize = EJSONdeserialize;
Object.freeze(EJSON);
const MAXSIZE = 1024 * 1024 * 17;
let buffer = ByteUtils.allocate(MAXSIZE);
function setInternalBufferSize(size) {
if (buffer.length < size) {
buffer = ByteUtils.allocate(size);
}
}
function serialize(object, options = {}) {
const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
if (buffer.length < minInternalBufferSize) {
buffer = ByteUtils.allocate(minInternalBufferSize);
}
const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
const finishedBuffer = ByteUtils.allocate(serializationIndex);
finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
return finishedBuffer;
}
function serializeWithBufferAndIndex(object, finalBuffer, options = {}) {
const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
const startIndex = typeof options.index === 'number' ? options.index : 0;
const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
return startIndex + serializationIndex - 1;
}
function deserialize(buffer, options = {}) {
return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
}
function calculateObjectSize(object, options = {}) {
options = options || {};
const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
}
function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
const bufferData = ByteUtils.toLocalBufferType(data);
let index = startIndex;
for (let i = 0; i < numberOfDocuments; i++) {
const size = bufferData[index] |
(bufferData[index + 1] << 8) |
(bufferData[index + 2] << 16) |
(bufferData[index + 3] << 24);
internalOptions.index = index;
documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
index = index + size;
}
return index;
}
var bson = /*#__PURE__*/Object.freeze({
__proto__: null,
BSONError: BSONError,
BSONRegExp: BSONRegExp,
BSONRuntimeError: BSONRuntimeError,
BSONSymbol: BSONSymbol,
BSONType: BSONType,
BSONValue: BSONValue,
BSONVersionError: BSONVersionError,
Binary: Binary,
Code: Code,
DBRef: DBRef,
Decimal128: Decimal128,
Double: Double,
EJSON: EJSON,
Int32: Int32,
Long: Long,
MaxKey: MaxKey,
MinKey: MinKey,
ObjectId: ObjectId,
Timestamp: Timestamp,
UUID: UUID,
calculateObjectSize: calculateObjectSize,
deserialize: deserialize,
deserializeStream: deserializeStream,
serialize: serialize,
serializeWithBufferAndIndex: serializeWithBufferAndIndex,
setInternalBufferSize: setInternalBufferSize
});
exports.BSON = bson;
exports.BSONError = BSONError;
exports.BSONRegExp = BSONRegExp;
exports.BSONRuntimeError = BSONRuntimeError;
exports.BSONSymbol = BSONSymbol;
exports.BSONType = BSONType;
exports.BSONValue = BSONValue;
exports.BSONVersionError = BSONVersionError;
exports.Binary = Binary;
exports.Code = Code;
exports.DBRef = DBRef;
exports.Decimal128 = Decimal128;
exports.Double = Double;
exports.EJSON = EJSON;
exports.Int32 = Int32;
exports.Long = Long;
exports.MaxKey = MaxKey;
exports.MinKey = MinKey;
exports.ObjectId = ObjectId;
exports.Timestamp = Timestamp;
exports.UUID = UUID;
exports.calculateObjectSize = calculateObjectSize;
exports.deserialize = deserialize;
exports.deserializeStream = deserializeStream;
exports.serialize = serialize;
exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
exports.setInternalBufferSize = setInternalBufferSize;
return exports;
})({});
//# sourceMappingURL=bson.bundle.js.map
|