nedb-lite v2016.9.1

Code coverage report for node-nedb-lite/index.js

Statements: 48.2% (909 / 1886)      Branches: 32.31% (359 / 1111)      Functions: 56.83% (179 / 315)      Lines: 48.24% (906 / 1878)      Ignored: none     

All files » node-nedb-lite/ » index.js
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 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494                                                              2   2         2   2                 14     14 14 14   14     14       14         14 14   2   2 2 2         1             2               2 2       1657 1657 1649   8               8     2       2 2 2 4   2     2       2 2 4 4 2     2 2 2 2 2         2     2       2 2 6 6 2     2 2   2 2 2   2 2 2     2 18 18 18 4 4   4   14     2   2       20 20 20 16 16   4 4 4 6   6 14 6 6       4     2       40 39   1   1     1     2         104 104           30       12 2   10   10 4 6 6         6       18 18         18         18   104 104         2       53     2       6 6 6 6 6 6   6 24 6   18           6     2 18 18 18 18 50     50   16   12   16 16 4   16 10 10   6 6 6 6 6   16 2 2   14 14 14   18     18 18     2       62   62 14     48     48       48     48       48 48 48                                         48             2 49 49 5 5 5   5   44 44     44 44         44       24 24   20   44   1 1   20 20                                 3 3   20 20   44 132       2 1     2 20 20     2 2 2 1   1 1 2   2 2 2     1       1 1     1 1 1   1         1     1 5   1     1     2       2       2   2 3 3     2 20 20 20       2 10 10 10                                       2 14 2 28 28 28     28 28     14     28 28   28 28       28   28     56 56 28 28 28 28 28     28         14   2 2 2                 2 28   2 6   2                             2           1 1         1 18 18         18 18         1           1           1 1 1   1 1       1 20 20 20 20   20   20   20     1                   2 2 2 1 1     1   2 2 2 30 18           18     18 26 26     30   2 2 2           2                   2 10 10 10 6               2 10 10             2                   2                     2 6 6             2 10       10 10                                                                                                                   2 10             2 10 6   4       10 10       10 10 4   4 4     4 4 4 4                         10                                                               10 10           10       2 6                   2                             2 6 6   6 192 192     6               2 6           2 60       6 60 60       6               6 6 6 6 6 6     6                       2 6         2       2                 2         2 14                     2 26             2 28   28 88         2                     10 10         10       10 10 2     10 10             10     10     10                   2 8   8   8     8     8               2 6   6 26 26                 6                         2 2   2 10                   2                                               2                           12     12 10 10       12 12 12 24     24       12 12 12 12     12 12   12 12                                                                     12 2     10       10 4 4 4       4 4           10                   10       12                   2 6     6 6 6         6 6     6             2 6   6     6               2 6   6           6 6 6   6 6 6   6 6   6     6             2 6     6                 2                                           2 2                       2                                           2                                                                                   2 6           6 6 6   6     6 6     6 4   2       6 6 6                                                               2 4       4       4 4 4   4 4 4 4     4     4         4 4 4     4     4   4 4   4                     4 4     4       4                                                                                                                           4     2 4                                   2 2         2 2 2   2 2   2 2       2 2 2 2 2       2             2 2     2         2 2                 2                             2 14 14     14 28     28 44   28     28   28 28 12   16   28                             28                             2 28 26   2             2       2           2                                                         2 56 56 56   56   56                 2 144   144 44                   2 80     80 54 54     26     26 4     22 22                                                               2 54   54                   54                               2 10   10             10   10 2     8 8                           2                                                 2                                                                     2                                           2 18   18 18                                                   2                 2 26   26 28   28 6       26             2                           2                             2 352       352       352                   2 40           40 10 30 30                           2 70   70 322   322     322           322           322     70               2 20 24     24 14   10       10                   2 66   66         50     16               16 16 16 50 50     16                     2 12                                                   2               2                     2                                                                                                           2                                                                             2                                           2                                     2                                     2                     2                 2 18                                   2 18             2                                                                                                                                 2 42     42       42       42 42                                                       2 6     6   6                                                                                 2                                     2       2       2       2       2             2                               2               2                       2                             2                   2                           2 2               2                                           2                                           2                   2                                         2 6         6             6 6 6 6   6               6           6               2 6       6                                                         6                                                         6           6       6         2 2 2 2 2 2 2 2 2                     2                 2 14   14                   2 10       10     10 32 22                   10 10     10               2                 2             24       24 24     24       24 24                 2 14             14 20   20 20 6           6 4 2       14   14       14       14                                 2 14     14   14 14 14 28     28   14 14 14           14 4       14 14           14   14   14               14 14 2     14     14         2                     2                 2 144                     2 152   152 152 152 152 8   152 152               2         2             2                                                                     2 48   48             2                                   2         2                   2                                                                                         2                                                                                       2                                 2                                     2 16     16           16 24   24             24               16               2 22       22 14 14 14 14       8   8                       8   8                     8 8       8             8       2 22     22 22                   2 8         8           8 16 8     8   8               8 8               8                         8 8           8     8   8                                                                                                                                 2 8     8 8               2 10 44           2                                 2                                             2                       2               2                       2                 2                                     2                                                           2                                       2                       2                                                         2 8 8   8             2                       2 8 8 8   8             2                                                                                               2 20 6     14 6     8             8 2   6                 2                                                                                     2                                                                                 2                             2                                                       2                                                   2                                                                                                   2                                                                                                                                                                                   2 28     28 28 2                 2                                                       2                 2   2   2 83     2             1 1 1             1 1 1   1 1 1 1        
/*
 * assets.nedb-lite.js
 *
 * this package will run a standalone, browser-compatible version of the nedb v1.8.0 database
 * with zero npm-dependencies
 *
 * browser example:
 *     <script src="assets.nedb-lite.js"></script>
 *     <script>
 *     var table = new window.Nedb({ name: 'table1' });
 *     table.insert({ field1: 'hello', field2: 'world'}, console.log.bind(console));
 *     </script>
 *
 * node example:
 *     var Nedb = require('./assets.nedb-lite.js');
 *     var table = new Nedb({ name: 'table1' });
 *     table.insert({ field1: 'hello', field2: 'world'}, console.log.bind(console));
 */
 
 
 
/* istanbul instrument in package nedb-lite */
/*jslint
    browser: true,
    maxerr: 8,
    maxlen: 196,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = function (options, onError) {
        /**
         * Create a new collection
         * @param {String} options.name
         * @param {Function} onError Optional,
         * if autoload is used this will be called after the load database
         * with the error object as parameter. If you don't pass it the error will be thrown
         */
            // validate name
            Iif (!(options && options.name && typeof options.name === 'string')) {
                throw new Error('Nedb - missing name param, e.g. new Nedb({ name: "table1" })');
            }
            this.name = options.name;
            local.dbTableDrop(this, local.nop);
            local.dbTableDict[this.name] = this;
            // Persistence handling
            this.persistence = new local.Persistence({ db: this });
            // This new executor is ready if we don't use persistence
            // If we do, it will only be ready once loadDatabase is called
            this.executor = new local.Executor();
            // Indexed by field name, dot notation can be used
            // _id is always indexed and since _ids are generated randomly the underlying
            // binary is always well-balanced
            this.indexes = {
                _id: new local.Index({ fieldName: '_id', unique: true }),
                createdAt: new local.Index({ fieldName: 'createdAt' }),
                updatedAt: new local.Index({ fieldName: 'updatedAt' })
            };
            this.ttlIndexes = {};
            this.load(options, onError);
        };
        local.Nedb = local.local = local;
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
    }());
 
 
 
    // run shared js-env code - function
    (function () {
        local.assert = function (passed, message) {
        /*
         * this function will throw the error message if passed is falsey
         */
            var error;
            if (passed) {
                return;
            }
            error = message && message.message
                // if message is an error-object, then leave it as is
                ? message
                : new Error(typeof message === 'string'
                    // if message is a string, then leave it as is
                    ? message
                    // else JSON.stringify message
                    : JSON.stringify(message));
            throw error;
        };
 
        local.dbExport = function () {
        /*
         * this function will export the database as a serialized tableList
         */
            var data;
            data = '';
            Object.keys(local.dbTableDict).map(function (key) {
                data += local.dbTableDict[key].export() + '\n\n';
            });
            return data.slice(0, -2);
        };
 
        local.dbImport = function (tableList, onError) {
        /*
         * this function will import the serialized tableList
         */
            var onParallel;
            onParallel = function () {
                onParallel.counter -= 1;
                if (onParallel.counter === 0) {
                    onError();
                }
            };
            onParallel.counter = 0;
            onParallel.counter += 1;
            tableList.trim().split('\n\n').forEach(function (table) {
                onParallel.counter += 1;
                local.dbTableCreate({
                    persistenceData: table,
                    name: JSON.parse((/.*/).exec(table)[0])
                }, onParallel);
            });
            onParallel();
        };
 
        local.dbReset = function (onError) {
        /*
         * this function will reset nedb's persistence
         */
            var onParallel;
            onParallel = function () {
                onParallel.counter -= 1;
                if (onParallel.counter === 0) {
                    onError();
                }
            };
            onParallel.counter = 0;
            onParallel.counter += 1;
            // drop all tables
            Object.keys(local.dbTableDict).forEach(function (key) {
                onParallel.counter += 1;
                local.dbTableDrop({ name: key }, onParallel);
            });
            onParallel.counter += 1;
            local.storeClear(onParallel);
            onParallel();
        };
 
        local.dbTableCreate = function (options, onError) {
            var self;
            self = local.dbTableDict[options.name];
            if (self) {
                setTimeout(function () {
                    self.load(options, onError);
                });
                return self;
            }
            return new local.Nedb(options, onError);
        };
 
        local.dbTableDict = {};
 
        local.dbTableDrop = function (options, onError) {
        /*
         * this function will drop the table with the given options.name
         */
            var self;
            self = local.dbTableDict[options.name];
            if (!self) {
                onError();
                return;
            }
            delete local.dbTableDict[options.name];
            self.persistence = self.prototype = self;
            self.persistCachedDatabase = self.persistNewState = function () {
                var ii;
                // coverage-hack
                for (ii = -1; ii < arguments.length; ii += 1) {
                    if (typeof arguments[ii] === 'function') {
                        arguments[ii]();
                        return;
                    }
                }
            };
            local.storeRemoveItem(self.name, onError);
        };
 
        local.fsDir = function () {
        /*
         * this function will return the persistence-dir
         */
            if (local.fsDirInitialized) {
                return local.fsDirInitialized;
            }
            local.fsDirInitialized = 'tmp/nedb.persistence.' + local.NODE_ENV;
            // mkdirp fsDirInitialized
            local.child_process.spawnSync('mkdir', ['-p', local.fsDirInitialized], {
                stdio: ['ignore', 1, 2]
            });
            return local.fsDirInitialized;
        };
 
        local.jsonStringifyOrdered = function (element, replacer, space) {
        /*
         * this function will JSON.stringify the element,
         * with object-keys sorted and circular-references removed
         */
            var circularList, stringify, tmp;
            stringify = function (element) {
            /*
             * this function will recursively JSON.stringify the element,
             * with object-keys sorted and circular-references removed
             */
                // if element is an object, then recurse its items with object-keys sorted
                if (element &&
                        typeof element === 'object' &&
                        typeof element.toJSON !== 'function') {
                    // ignore circular-reference
                    if (circularList.indexOf(element) >= 0) {
                        return;
                    }
                    circularList.push(element);
                    // if element is an array, then recurse its elements
                    if (Array.isArray(element)) {
                        return '[' + element.map(function (element) {
                            tmp = stringify(element);
                            return typeof tmp === 'string'
                                ? tmp
                                : 'null';
                        }).join(',') + ']';
                    }
                    return '{' + Object.keys(element)
                        // sort object-keys
                        .sort()
                        .map(function (key) {
                            tmp = stringify(element[key]);
                            return typeof tmp === 'string'
                                ? JSON.stringify(key) + ':' + tmp
                                : undefined;
                        })
                        .filter(function (element) {
                            return typeof element === 'string';
                        })
                        .join(',') + '}';
                }
                // else JSON.stringify as normal
                return JSON.stringify(element);
            };
            circularList = [];
            return JSON.stringify(element && typeof element === 'object'
                ? JSON.parse(stringify(element))
                : element, replacer, space);
        };
 
        local.nop = function () {
        /*
         * this function will do nothing
         */
            return;
        };
 
        local.prototype.export = function () {
        /*
         * this function will export the table as serialized-text
         */
            var data, self;
            self = this;
            data = '';
            data += JSON.stringify(String(this.name)) + '\n';
            self.getAllData().forEach(function (doc) {
                data += local.model.serialize(doc) + '\n';
            });
            Object.keys(self.indexes).forEach(function (fieldName) {
                if (fieldName === '_id') {
                    return;
                }
                data += local.model.serialize({ $$indexCreated: {
                    fieldName: fieldName,
                    unique: self.indexes[fieldName].unique,
                    sparse: self.indexes[fieldName].sparse
                } }) + '\n';
            });
            return data.slice(0, -1);
        };
 
        local.prototype.load = function (options, onError) {
            var data, modeNext, onNext, self;
            self = this;
            modeNext = 0;
            onNext = function (error) {
                modeNext = error
                    ? Infinity
                    : modeNext + 1;
                switch (modeNext) {
                case 1:
                    onError = onError || function (error) {
                        // validate no error occurred
                        local.assert(!error, error);
                    };
                    data = (options.persistenceData || '').trim();
                    if (options.reset) {
                        data = 'undefined';
                    }
                    if (!data) {
                        onNext();
                        return;
                    }
                    self.isLoaded = null;
                    data += '\n';
                    data = data.slice(data.indexOf('\n') + 1);
                    local.storeSetItem(self.name, data, onNext);
                    break;
                case 2:
                    if (self.isLoaded) {
                        onNext();
                        return;
                    }
                    self.isLoaded = true;
                    self.loadDatabase(onNext);
                    break;
                default:
                    onError(error, self);
                }
            };
            onNext(options.error);
            return self;
        };
 
        local.sortCompare = function (aa, bb) {
        /*
         * this function will sort-compare aa vs bb
         */
            var type1, type2;
            // compare equal
            if (aa === bb) {
                return 0;
            }
            // compare undefined
            Iif (aa === undefined) {
                return -1;
            }
            Iif (bb === undefined) {
                return 1;
            }
            // compare null
            Iif (aa === null) {
                return -1;
            }
            Iif (bb === null) {
                return 1;
            }
            // compare different-types
            type1 = typeof aa;
            type2 = typeof bb;
            Iif (type1 !== type2) {
                if (type1 === 'boolean') {
                    return -1;
                }
                if (type2 === 'boolean') {
                    return 1;
                }
                if (type1 === 'number') {
                    return -1;
                }
                if (type2 === 'number') {
                    return 1;
                }
                if (type1 === 'string') {
                    return -1;
                }
                if (type2 === 'string') {
                    return 1;
                }
            }
            // default compare
            return aa < bb
                ? -1
                : aa > bb
                ? 1
                : 0;
        };
 
        local.storeAction = function (options, onError) {
            var argList, data, done, onError2, request, store;
            if (!local.store) {
                argList = arguments;
                local.storePromiseList.push(function () {
                    local.storeAction.apply(null, argList);
                });
                return;
            }
            onError2 = function () {
                Iif (done) {
                    return;
                }
                done = true;
                onError(
                    request && (request.error || request.transaction.error),
                    data || request.result
                );
            };
            switch (options.action) {
            case 'clear':
            case 'removeItem':
            case 'setItem':
                store = local.store.transaction('nedbdata', 'readwrite').objectStore('nedbdata');
                break;
            default:
                store = local.store.transaction('nedbdata', 'readonly').objectStore('nedbdata');
            }
            switch (options.action) {
            case 'clear':
                request = store.clear();
                break;
            case 'getItem':
                request = store.get(options.key);
                break;
            case 'keys':
                data = [];
                request = store.openCursor();
                request.onsuccess = function () {
                    if (!request.result) {
                        onError2();
                        return;
                    }
                    data.push(request.result.key);
                    request.result.continue();
                };
                break;
            case 'length':
                request = store.count();
                break;
            case 'removeItem':
                request = store.delete(options.key);
                break;
            case 'setItem':
                request = store.put(options.value, options.key);
                break;
            }
            ['onabort', 'onerror', 'onsuccess'].forEach(function (handler) {
                request[handler] = request[handler] || onError2;
            });
        };
 
        local.storeClear = function (onError) {
            local.storeAction({ action: 'clear' }, onError);
        };
 
        local.storeGetItem = function (key, onError) {
            local.assert(typeof key === 'string');
            local.storeAction({ action: 'getItem', key: key }, onError);
        };
 
        local.storeInit = function () {
            var modeNext, onNext, request;
            if (!local.global.indexedDB) {
                return;
            }
            modeNext = 0;
            onNext = function (error) {
                local.store = local.global.nedbStore;
                // validate no error occurred
                local.assert(local.store || !error, error);
                modeNext += 1;
                switch (modeNext) {
                // init indexedDB
                case 1:
                    Iif (local.store) {
                        onNext();
                        return;
                    }
                    request = local.global.indexedDB.open('NeDB');
                    request.onerror = function () {
                        onNext(request.error);
                    };
                    request.onsuccess = function () {
                        local.global.nedbStore = request.result;
                        onNext();
                    };
                    request.onupgradeneeded = function () {
                        if (!request.result.objectStoreNames.contains('nedbdata')) {
                            request.result.createObjectStore('nedbdata');
                        }
                    };
                    break;
                // run promised actions
                case 2:
                    while (local.storePromiseList.length) {
                        local.storePromiseList.shift()();
                    }
                    break;
                }
            };
            onNext();
        };
 
        local.storeKeys = function (onError) {
            local.storeAction({ action: 'keys' }, onError);
        };
 
        local.storeLength = function (onError) {
            local.storeAction({ action: 'length' }, onError);
        };
 
        local.storePromiseList = [];
 
        local.storeRemoveItem = function (key, onError) {
            local.assert(typeof key === 'string');
            local.storeAction({ action: 'removeItem', key: key }, onError);
        };
 
        local.storeSetItem = function (key, value, onError) {
            local.assert(typeof key === 'string');
            local.assert(typeof value === 'string');
            local.storeAction({ action: 'setItem', key: key, value: value }, onError);
        };
 
        // legacy
        local.asyncEachSeries = function (arr, iterator, callback) {
            var completed, iterate;
            Eif (!arr.length) {
                return callback();
            }
            completed = 0;
            iterate = function () {
                iterator(arr[completed], function (error) {
                    if (error) {
                        callback(error);
                        callback = local.nop;
                    } else {
                        completed += 1;
                        if (completed >= arr.length) {
                            callback();
                        } else {
                            iterate();
                        }
                    }
                });
            };
            iterate();
        };
        local.asyncQueue = function (worker) {
            var self;
            function only_once(fn) {
                var called = false;
                return function () {
                    Iif (called) {
                        throw new Error("Callback was already called.");
                    }
                    called = true;
                    fn.apply(null, arguments);
                };
            }
            self = {
                tasks: [],
                push: function (data, callback) {
                    Eif (data.constructor !== Array) {
                        data = [data];
                    }
                    data.forEach(function (task) {
                        var item = {
                            data: task,
                            callback: typeof callback === 'function' ? callback : null
                        };
                        self.tasks.push(item);
                    });
                    setTimeout(self.process);
                },
                process: function () {
                    var task;
                    if (!self.isRunningTask && self.tasks.length) {
                        task = self.tasks.shift();
                        self.isRunningTask = true;
                        worker(task.data, only_once(function () {
                            self.isRunningTask = null;
                            Iif (task.callback) {
                                task.callback.apply(task, arguments);
                            }
                            self.process();
                        }));
                    }
                }
            };
            return self;
        };
        local.inherits = function (ctor, superCtor) {
            ctor.super_ = superCtor;
            ctor.prototype = Object.create(superCtor.prototype, {
                constructor: {
                    value: ctor,
                    enumerable: false,
                    writable: true,
                    configurable: true
                }
            });
        };
        local.isDate = function (obj) {
            return Object.prototype.toString.call(obj) === '[object Date]';
        };
        local.isRegExp = function (obj) {
            return Object.prototype.toString.call(obj) === '[object RegExp]';
        };
        local.listUnique = function (list) {
        /*
         * this function will remove duplicate elements from the array
         */
            var seen;
            seen = {};
            return list.filter(function (element) {
                if (seen.hasOwnProperty(element)) {
                    return;
                }
                seen[element] = true;
                return true;
            });
        };
    }());
    switch (local.modeJs) {
 
 
 
    // run node js-env code - function
    case 'node':
        local.storeClear = function (onError) {
            local.child_process.spawn('sh', ['-c', 'rm ' + local.fsDir() + '/*'], {
                stdio: ['ignore', 1, 2]
            }).once('exit', onError);
        };
 
        local.storeGetItem = function (key, onError) {
            local.assert(typeof key === 'string');
            local.fs.readFile(
                local.fsDir() + '/' + encodeURIComponent(key),
                'utf8',
                function (error, data) {
                    // jslint-hack
                    local.nop(error);
                    onError(null, data || '');
                }
            );
        };
 
        local.storeKeys = function (onError) {
            local.fs.readdir(local.fsDir(), function (error, data) {
                onError(error, data && data.map(decodeURIComponent));
            });
        };
 
        local.storeLength = function (onError) {
            local.fs.readdir(local.fsDir(), function (error, data) {
                onError(error, data && data.length);
            });
        };
 
        local.storeRemoveItem = function (key, onError) {
            local.assert(typeof key === 'string');
            local.fs.unlink(local.fsDir() + '/' + encodeURIComponent(key), function (error) {
                // jslint-hack
                local.nop(error);
                onError();
            });
        };
 
        local.storeSetItem = function (key, value, onError) {
            var tmp;
            local.assert(typeof key === 'string');
            local.assert(typeof value === 'string');
            tmp = local.os.tmpdir() + '/' + Date.now() + Math.random();
            // save to tmp
            local.fs.writeFile(tmp, value, function (error) {
                // jslint-hack
                local.nop(error);
                // rename tmp to key
                local.fs.rename(tmp, local.fsDir() + '/' + encodeURIComponent(key), onError);
            });
        };
        break;
    }
 
 
 
// init lib nedb
/* jslint-ignore-begin */
// https://github.com/louischatriot/nedb/blob/cadf4ef434e517e47c4e9ca1db5b89e892ff5981/browser-version/out/nedb.js
// replace 'return i(r?r:t)' with 'return local[t] = i(r?r:t)'
// replace 'seen = {}' with 'seen = local'
(function (e) {
    Iif ('function' == typeof bootstrap) bootstrap('nedb', e);
    else if ('object' == typeof exports) module.exports = e();
    else Iif ('function' == typeof define && define.amd) define(e);
    else Iif ('undefined' != typeof ses) {
        if (!ses.ok()) return;
        ses.makeNedb = e
    } else 'undefined' != typeof local.global ? local.global.Nedb = e() : global.Nedb = e()
})(function () {
    var define, ses, bootstrap, module, exports;
    return (function (e, t, n) {
        function i(n, s) {
            if (!t[n]) {
                Iif (!e[n]) {
                    var o = typeof require == 'function' && require;
                    if (!s && o) return o(n, !0);
                    if (r) return r(n, !0);
                    throw new Error("Cannot find module '" + n + "'")
                }
                var u = t[n] = {
                    exports: {}
                };
                e[n][0].call(u.exports, function (t) {
                    var r = e[n][1][t];
                    return local[t] = i(r ? r : t)
                }, u, u.exports)
            }
            return t[n].exports
        }
        var r = typeof require == 'function' && require;
        for (var s = 0; s < n.length; s++) i(n[s]);
        return i
    })({
        5: [function (require, module, exports) {
            /**
             * Manage access to data, be it to find, update or remove it
             */
            var model = require('./model');
 
 
 
            /**
             * Create a new cursor for this collection
             * @param {Datastore} db - The datastore this cursor is bound to
             * @param {Query} query - The query this cursor will operate on
             * @param {Function} execFn - Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove
             */
            function Cursor(db, query, execFn) {
                this.db = db;
                this.query = query || {};
                if (execFn) {
                    this.execFn = execFn;
                }
            }
 
 
            /**
             * Set a limit to the number of results
             */
            Cursor.prototype.limit = function (limit) {
                this._limit = limit;
                return this;
            };
 
 
            /**
             * Skip a the number of results
             */
            Cursor.prototype.skip = function (skip) {
                this._skip = skip;
                return this;
            };
 
 
            /**
             * Sort results of the query
             * @param {SortQuery} sortQuery - SortQuery is { field: order }, field can use the dot-notation, order is 1 for ascending and -1 for descending
             */
            Cursor.prototype.sort = function (sortQuery) {
                this._sort = sortQuery;
                return this;
            };
 
 
            /**
             * Add the use of a projection
             * @param {Object} projection - MongoDB-style projection. {} means take all fields. Then it's { key1: 1, key2: 1 } to take only key1 and key2
             *                              { key1: 0, key2: 0 } to omit only key1 and key2. Except _id, you can't mix takes and omits
             */
            Cursor.prototype.projection = function (projection) {
                this._projection = projection;
                return this;
            };
 
 
            /**
             * Apply the projection
             */
            Cursor.prototype.project = function (candidates) {
                var res = [],
                    self = this,
                    keepId, action, keys;
 
                Eif (self._projection === undefined || Object.keys(self._projection).length === 0) {
                    return candidates;
                }
 
                keepId = self._projection._id === 0 ? false : true;
 
                // Check for consistency
                keys = Object.keys(self._projection).filter(function (key) {
                    return key !== '_id';
                });
                keys.forEach(function (k) {
                    if (action !== undefined && self._projection[k] !== action) {
                        throw new Error("Can't both keep and omit fields except for _id");
                    }
                    action = self._projection[k];
                });
 
                // Do the actual projection
                candidates.forEach(function (candidate) {
                    var toPush;
                    if (action === 1) { // pick-type projection
                        toPush = {
                            $set: {}
                        };
                        keys.forEach(function (k) {
                            toPush.$set[k] = model.getDotValue(candidate, k);
                            if (toPush.$set[k] === undefined) {
                                delete toPush.$set[k];
                            }
                        });
                        toPush = model.modify({}, toPush);
                    } else { // omit-type projection
                        toPush = {
                            $unset: {}
                        };
                        keys.forEach(function (k) {
                            toPush.$unset[k] = true
                        });
                        toPush = model.modify(candidate, toPush);
                    }
                    if (keepId) {
                        toPush._id = candidate._id;
                    } else {
                        delete toPush._id;
                    }
                    res.push(toPush);
                });
 
                return res;
            };
 
 
            /**
             * Get all matching elements
             * Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne
             * This is an internal function, use exec which uses the executor
             *
             * @param {Function} callback - Signature: error, results
             */
            Cursor.prototype._exec = function (_callback) {
                var res = [],
                    added = 0,
                    skipped = 0,
                    self = this,
                    error = null,
                    i, keys, key;
 
                function callback(error, res) {
                    if (self.execFn) {
                        return self.execFn(error, res, _callback);
                    } else {
                        return _callback(error, res);
                    }
                }
 
                this.db.getCandidates(this.query, function (error, candidates) {
                    Iif (error) {
                        return callback(error);
                    }
 
                    try {
                        for (i = 0; i < candidates.length; i += 1) {
                            Eif (model.match(candidates[i], self.query)) {
                                // If a sort is defined, wait for the results to be sorted before applying limit and skip
                                Eif (!self._sort) {
                                    Iif (self._skip && self._skip > skipped) {
                                        skipped += 1;
                                    } else {
                                        res.push(candidates[i]);
                                        added += 1;
                                        Eif (self._limit && self._limit <= added) {
                                            break;
                                        }
                                    }
                                } else {
                                    res.push(candidates[i]);
                                }
                            }
                        }
                    } catch (error) {
                        return callback(error);
                    }
 
                    // Apply all sorts
                    Iif (self._sort) {
                        keys = Object.keys(self._sort);
 
                        // Sorting
                        var criteria = [];
                        for (i = 0; i < keys.length; i++) {
                            key = keys[i];
                            criteria.push({
                                key: key,
                                direction: self._sort[key]
                            });
                        }
                        res.sort(function (a, b) {
                            var criterion, compare, i;
                            for (i = 0; i < criteria.length; i++) {
                                criterion = criteria[i];
                                compare = criterion.direction * local.sortCompare(model.getDotValue(a, criterion.key), model.getDotValue(b, criterion.key));
                                if (compare !== 0) {
                                    return compare;
                                }
                            }
                            return 0;
                        });
 
                        // Applying limit and skip
                        var limit = self._limit || res.length,
                            skip = self._skip || 0;
 
                        res = res.slice(skip, skip + limit);
                    }
 
                    // Apply projection
                    try {
                        res = self.project(res);
                    } catch (e) {
                        error = e;
                        res = undefined;
                    }
 
                    return callback(error, res);
                });
            };
 
            Cursor.prototype.exec = function () {
                this.db.executor.push({
                    this: this,
                    fn: this._exec,
                    arguments: arguments
                });
            };
 
 
 
            // Interface
            module.exports = Cursor;
 
        }, {
            "./model": 10
        }],
        6: [function (require, module, exports) {
            /**
             * Specific customUtils for the browser, where we don't have access to the Crypto and Buffer modules
             */
 
            /**
             * Taken from the crypto-browserify module
             * https://github.com/dominictarr/crypto-browserify
             * NOTE: Math.random() does not guarantee "cryptographic quality" but we actually don't need it
             */
            function randomBytes(size) {
                var bytes = new Array(size);
                var r;
 
                for (var i = 0, r; i < size; i++) {
                    if ((i & 0x03) == 0) r = Math.random() * 0x100000000;
                    bytes[i] = r >>> ((i & 0x03) << 3) & 0xff;
                }
 
                return bytes;
            }
 
 
            /**
             * Taken from the base64-js module
             * https://github.com/beatgammit/base64-js/
             */
            function byteArrayToBase64(uint8) {
                var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
                    extraBytes = uint8.length % 3 // if we have 1 byte left, pad 2 bytes
                    ,
                    output = '',
                    temp, length, i;
 
                function tripletToBase64(num) {
                    return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
                };
 
                // go through the array every three bytes, we'll deal with trailing stuff later
                for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
                    temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
                    output += tripletToBase64(temp);
                }
 
                // pad the end with zeros, but make sure to not forget the extra bytes
                switch (extraBytes) {
                    case 1:
                        temp = uint8[uint8.length - 1];
                        output += lookup[temp >> 2];
                        output += lookup[(temp << 4) & 0x3F];
                        output += '==';
                        break;
                    case 2:
                        temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]);
                        output += lookup[temp >> 10];
                        output += lookup[(temp >> 4) & 0x3F];
                        output += lookup[(temp << 2) & 0x3F];
                        output += '=';
                        break;
                }
 
                return output;
            }
 
 
            /**
             * Return a random alphanumerical string of length len
             * There is a very small probability (less than 1/1,000,000) for the length to be less than len
             * (il the base64 conversion yields too many pluses and slashes) but
             * that's not an issue here
             * The probability of a collision is extremely small (need 3*10^12 documents to have one chance in a million of a collision)
             * See http://en.wikipedia.org/wiki/Birthday_problem
             */
            function uid(len) {
                return byteArrayToBase64(randomBytes(Math.ceil(Math.max(8, len * 2)))).replace(/[+\/]/g, '').slice(0, len);
            }
 
 
 
            module.exports.uid = uid;
 
        }, {}],
        7: [function (require, module, exports) {
            var Datastore,
                customUtils = require('./customUtils'),
                model = require('./model'),
                Executor = local.Executor = require('./executor'),
                Index = local.Index = require('./indexes'),
                Persistence = local.Persistence = require('./persistence'),
                Cursor = require('./cursor');
 
 
            Datastore = local;
 
            /**
             * Load the database from the datafile, and trigger the execution of buffered commands if any
             */
            Datastore.prototype.loadDatabase = function () {
                this.executor.push({
                    this: this.persistence,
                    fn: this.persistence.loadDatabase,
                    arguments: arguments
                }, true);
            };
 
 
            /**
             * Get an array of all the data in the database
             */
            Datastore.prototype.getAllData = function () {
                return this.indexes._id.getAll();
            };
 
 
            /**
             * Reset all currently defined indexes
             */
            Datastore.prototype.resetIndexes = function (newData) {
                var self = this;
 
                Object.keys(this.indexes).forEach(function (i) {
                    self.indexes[i].reset(newData);
                });
            };
 
 
            Datastore.prototype.ensureIndex = function (options, cb) {
            /**
             * Ensure an index is kept for this field. Same parameters as lib/indexes
             * For now this function is synchronous, we need to test how much time it takes
             * We use an async API for consistency with the rest of the code
             * @param {String} options.fieldName
             * @param {Boolean} options.unique
             * @param {Boolean} options.sparse
             * @param {Number} options.expireAfterSeconds - Optional, if set this index becomes a TTL index (only works on Date fields, not arrays of Date)
             * @param {Function} cb Optional callback, signature: error
             */
                var error, callback = cb;
                Iif (!options.fieldName) {
                    error = new Error("Cannot create an index without a fieldName");
                    error.missingFieldName = true;
                    return callback(error);
                }
                Iif (this.indexes[options.fieldName]) {
                    return callback();
                }
 
                this.indexes[options.fieldName] = new Index(options);
                if (options.expireAfterSeconds !== undefined) {
                    this.ttlIndexes[options.fieldName] = options.expireAfterSeconds;
                } // With this implementation index creation is not necessary to ensure TTL but we stick with MongoDB's API here
 
                try {
                    this.indexes[options.fieldName].insert(this.getAllData());
                } catch (e) {
                    delete this.indexes[options.fieldName];
                    return callback(e);
                }
 
                // We may want to force all options to be persisted including defaults, not just the ones passed the index creation function
                this.persistence.persistNewState([{
                    $$indexCreated: options
                }], function (error) {
                    Iif (error) {
                        return callback(error);
                    }
                    return callback();
                });
            };
 
 
            /**
             * Remove an index
             * @param {String} fieldName
             * @param {Function} cb Optional callback, signature: error
             */
            Datastore.prototype.removeIndex = function (fieldName, cb) {
                var callback = cb;
 
                delete this.indexes[fieldName];
 
                this.persistence.persistNewState([{
                    $$indexRemoved: fieldName
                }], function (error) {
                    Iif (error) {
                        return callback(error);
                    }
                    return callback();
                });
            };
 
 
            /**
             * Add one or several document(s) to all indexes
             */
            Datastore.prototype.addToIndexes = function (doc) {
                var i, failingIndex, error, keys = Object.keys(this.indexes);
 
                for (i = 0; i < keys.length; i += 1) {
                    try {
                        this.indexes[keys[i]].insert(doc);
                    } catch (e) {
                        failingIndex = i;
                        error = e;
                        break;
                    }
                }
 
                // If an error happened, we need to rollback the insert on all other indexes
                Iif (error) {
                    for (i = 0; i < failingIndex; i += 1) {
                        this.indexes[keys[i]].remove(doc);
                    }
 
                    throw error;
                }
            };
 
 
            /**
             * Remove one or several document(s) from all indexes
             */
            Datastore.prototype.removeFromIndexes = function (doc) {
                var self = this;
 
                Object.keys(this.indexes).forEach(function (i) {
                    self.indexes[i].remove(doc);
                });
            };
 
 
            /**
             * Update one or several documents in all indexes
             * To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs
             * If one update violates a constraint, all changes are rolled back
             */
            Datastore.prototype.updateIndexes = function (oldDoc, newDoc) {
                var i, failingIndex, error, keys = Object.keys(this.indexes);
 
                for (i = 0; i < keys.length; i += 1) {
                    try {
                        this.indexes[keys[i]].update(oldDoc, newDoc);
                    } catch (e) {
                        failingIndex = i;
                        error = e;
                        break;
                    }
                }
 
                // If an error happened, we need to rollback the update on all other indexes
                if (error) {
                    for (i = 0; i < failingIndex; i += 1) {
                        this.indexes[keys[i]].revertUpdate(oldDoc, newDoc);
                    }
 
                    throw error;
                }
            };
 
 
            Datastore.prototype.getCandidates = function (query, dontExpireStaleDocs, callback) {
            /**
             * Return the list of candidates for a given query
             * Crude implementation for now, we return the candidates given by the first usable index if any
             * We try the following query types, in this order: basic match, $in match, comparison match
             * One way to make it better would be to enable the use of multiple indexes if the first usable index
             * returns too much data. I may do it in the future.
             *
             * Returned candidates will be scanned to find and remove all expired documents
             *
             * @param {Query} query
             * @param {Boolean} dontExpireStaleDocs Optional, defaults to false, if true don't remove stale docs. Useful for the remove function which shouldn't be impacted by expirations
             * @param {Function} callback Signature error, candidates
             */
                var self = this,
                    usableQueryKeys;
 
                if (typeof dontExpireStaleDocs === 'function') {
                    callback = dontExpireStaleDocs;
                    dontExpireStaleDocs = false;
                }
 
 
                var modeNext, onNext;
                modeNext = 0;
                onNext = function (error, docs) {
                    modeNext = error
                        ? Infinity
                        : modeNext + 1;
                    switch (modeNext) {
                    // STEP 1: get candidates list by checking indexes from most to least frequent usecase
                    case 1:
                        // For a basic match
                        usableQueryKeys = [];
                        Object.keys(query).forEach(function (k) {
                            Eif (typeof query[k] === 'string' || typeof query[k] === 'number' || typeof query[k] === 'boolean' || local.isDate(query[k]) || query[k] === null) {
                                usableQueryKeys.push(k);
                            }
                        });
                        usableQueryKeys = usableQueryKeys.filter(function (element) {
                            return self.indexes.hasOwnProperty(element);
                        });
                        Eif (usableQueryKeys.length > 0) {
                            return onNext(null, self.indexes[usableQueryKeys[0]].getMatching(query[usableQueryKeys[0]]));
                        }
 
                        // For a $in match
                        usableQueryKeys = [];
                        Object.keys(query).forEach(function (k) {
                            if (query[k] && query[k].hasOwnProperty('$in')) {
                                usableQueryKeys.push(k);
                            }
                        });
                        usableQueryKeys = usableQueryKeys.filter(function (element) {
                            return self.indexes.hasOwnProperty(element);
                        });
                        if (usableQueryKeys.length > 0) {
                            return onNext(null, self.indexes[usableQueryKeys[0]].getMatching(query[usableQueryKeys[0]].$in));
                        }
 
                        // For a comparison match
                        usableQueryKeys = [];
                        Object.keys(query).forEach(function (k) {
                            if (query[k] && (query[k].hasOwnProperty('$lt') || query[k].hasOwnProperty('$lte') || query[k].hasOwnProperty('$gt') || query[k].hasOwnProperty('$gte'))) {
                                usableQueryKeys.push(k);
                            }
                        });
                        usableQueryKeys = usableQueryKeys.filter(function (element) {
                            return self.indexes.hasOwnProperty(element);
                        });
                        if (usableQueryKeys.length > 0) {
                            return onNext(null, self.indexes[usableQueryKeys[0]].getBetweenBounds(query[usableQueryKeys[0]]));
                        }
 
                        // By default, return all the DB data
                        return onNext(null, self.getAllData());
                    // STEP 2: remove all expired documents
                    default:
                        if (dontExpireStaleDocs) {
                            return callback(null, docs);
                        }
 
                        var expiredDocsIds = [],
                            validDocs = [],
                            ttlIndexesFieldNames = Object.keys(self.ttlIndexes);
 
                        docs.forEach(function (doc) {
                            var valid = true;
                            ttlIndexesFieldNames.forEach(function (i) {
                                Iif (doc[i] !== undefined && local.isDate(doc[i]) && Date.now() > doc[i].getTime() + self.ttlIndexes[i] * 1000) {
                                    valid = false;
                                }
                            });
                            Eif (valid) {
                                validDocs.push(doc);
                            } else {
                                expiredDocsIds.push(doc._id);
                            }
                        });
 
                        local.asyncEachSeries(expiredDocsIds, function (_id, cb) {
                            self._remove({
                                _id: _id
                            }, {}, function (error) {
                                if (error) {
                                    return callback(error);
                                }
                                return cb();
                            });
                        }, function (error) {
                            return callback(null, validDocs);
                        });
                    }
                };
                onNext();
            };
 
 
            /**
             * Insert a new document
             * @param {Function} cb Optional callback, signature: error, insertedDoc
             *
             * @api private Use Datastore.insert which has the same signature
             */
            Datastore.prototype._insert = function (newDoc, cb) {
                var callback = cb,
                    preparedDoc;
 
                try {
                    preparedDoc = this.prepareDocumentForInsertion(newDoc)
                    this._insertInCache(preparedDoc);
                } catch (e) {
                    return callback(e);
                }
 
                this.persistence.persistNewState(Array.isArray(preparedDoc) ? preparedDoc : [preparedDoc], function (error) {
                    Iif (error) {
                        return callback(error);
                    }
                    return callback(null, model.deepCopy(preparedDoc));
                });
            };
 
            /**
             * Create a new _id that's not already in use
             */
            Datastore.prototype.createNewId = function () {
                var tentativeId = customUtils.uid(16);
                // Try as many times as needed to get an unused _id. As explained in customUtils, the probability of this ever happening is extremely small, so this is O(1)
                Iif (this.indexes._id.getMatching(tentativeId).length > 0) {
                    tentativeId = this.createNewId();
                }
                return tentativeId;
            };
 
            /**
             * Prepare a document (or array of documents) to be inserted in a database
             * Meaning adds _id and timestamps if necessary on a copy of newDoc to avoid any side effect on user input
             * @api private
             */
            Datastore.prototype.prepareDocumentForInsertion = function (newDoc) {
                var preparedDoc, self = this;
 
                Iif (Array.isArray(newDoc)) {
                    preparedDoc = [];
                    newDoc.forEach(function (doc) {
                        preparedDoc.push(self.prepareDocumentForInsertion(doc));
                    });
                } else {
                    preparedDoc = model.deepCopy(newDoc);
                    Eif (preparedDoc._id === undefined) {
                        preparedDoc._id = this.createNewId();
                    }
                    var now = new Date().toISOString();
                    Eif (preparedDoc.createdAt === undefined) {
                        preparedDoc.createdAt = now;
                    }
                    Eif (preparedDoc.updatedAt === undefined) {
                        preparedDoc.updatedAt = now;
                    }
                    model.checkObject(preparedDoc);
                }
 
                return preparedDoc;
            };
 
            /**
             * If newDoc is an array of documents, this will insert all documents in the cache
             * @api private
             */
            Datastore.prototype._insertInCache = function (preparedDoc) {
                Iif (Array.isArray(preparedDoc)) {
                    this._insertMultipleDocsInCache(preparedDoc);
                } else {
                    this.addToIndexes(preparedDoc);
                }
            };
 
            /**
             * If one insertion fails (e.g. because of a unique constraint), roll back all previous
             * inserts and throws the error
             * @api private
             */
            Datastore.prototype._insertMultipleDocsInCache = function (preparedDocs) {
                var i, failingI, error;
 
                for (i = 0; i < preparedDocs.length; i += 1) {
                    try {
                        this.addToIndexes(preparedDocs[i]);
                    } catch (e) {
                        error = e;
                        failingI = i;
                        break;
                    }
                }
 
                if (error) {
                    for (i = 0; i < failingI; i += 1) {
                        this.removeFromIndexes(preparedDocs[i]);
                    }
 
                    throw error;
                }
            };
 
            Datastore.prototype.insert = function () {
                this.executor.push({
                    this: this,
                    fn: this._insert,
                    arguments: arguments
                });
            };
 
 
            /**
             * Count all documents matching the query
             * @param {Object} query MongoDB-style query
             */
            Datastore.prototype.count = function (query, callback) {
                var cursor = new Cursor(this, query, function (error, docs, callback) {
                    if (error) {
                        return callback(error);
                    }
                    return callback(null, docs.length);
                });
 
                if (typeof callback === 'function') {
                    cursor.exec(callback);
                } else {
                    return cursor;
                }
            };
 
 
            /**
             * Find all documents matching the query
             * If no callback is passed, we return the cursor so that user can limit, skip and finally exec
             * @param {Object} query MongoDB-style query
             * @param {Object} projection MongoDB-style projection
             */
            Datastore.prototype.find = function (query, projection, callback) {
                switch (arguments.length) {
                    case 1:
                        projection = {};
                        // callback is undefined, will return a cursor
                        break;
                    case 2:
                        if (typeof projection === 'function') {
                            callback = projection;
                            projection = {};
                        } // If not assume projection is an object and callback undefined
                        break;
                }
 
                var cursor = new Cursor(this, query, function (error, docs, callback) {
                    var res = [],
                        i;
 
                    if (error) {
                        return callback(error);
                    }
 
                    for (i = 0; i < docs.length; i += 1) {
                        res.push(model.deepCopy(docs[i]));
                    }
                    return callback(null, res);
                });
 
                cursor.projection(projection);
                if (typeof callback === 'function') {
                    cursor.exec(callback);
                } else {
                    return cursor;
                }
            };
 
 
            /**
             * Find one document matching the query
             * @param {Object} query MongoDB-style query
             * @param {Object} projection MongoDB-style projection
             */
            Datastore.prototype.findOne = function (query, projection, callback) {
                switch (arguments.length) {
                    case 1:
                        projection = {};
                        // callback is undefined, will return a cursor
                        break;
                    case 2:
                        Eif (typeof projection === 'function') {
                            callback = projection;
                            projection = {};
                        } // If not assume projection is an object and callback undefined
                        break;
                }
 
                var cursor = new Cursor(this, query, function (error, docs, callback) {
                    Iif (error) {
                        return callback(error);
                    }
                    if (docs.length === 1) {
                        return callback(null, model.deepCopy(docs[0]));
                    } else {
                        return callback(null, null);
                    }
                });
 
                cursor.projection(projection).limit(1);
                Eif (typeof callback === 'function') {
                    cursor.exec(callback);
                } else {
                    return cursor;
                }
            };
 
 
            /**
             * Update all docs matching query
             * @param {Object} query
             * @param {Object} updateQuery
             * @param {Object} options Optional options
             *                 options.multi If true, can update multiple documents (defaults to false)
             *                 options.upsert If true, document is inserted if the query doesn't match anything
             *                 options.returnUpdatedDocs Defaults to false, if true return as third argument the array of updated matched documents (even if no change actually took place)
             * @param {Function} cb Optional callback, signature: (error, numAffected, affectedDocuments, upsert)
             *                      If update was an upsert, upsert flag is set to true
             *                      affectedDocuments can be one of the following:
             *                        * For an upsert, the upserted document
             *                        * For an update with returnUpdatedDocs option false, null
             *                        * For an update with returnUpdatedDocs true and multi false, the updated document
             *                        * For an update with returnUpdatedDocs true and multi true, the array of updated documents
             *
             * WARNING: The API was changed between v1.7.4 and v1.8, for consistency and readability reasons. Prior and including to v1.7.4,
             *          the callback signature was (error, numAffected, updated) where updated was the updated document in case of an upsert
             *          or the array of updated documents for an update if the returnUpdatedDocs option was true. That meant that the type of
             *          affectedDocuments in a non multi update depended on whether there was an upsert or not, leaving only two ways for the
             *          user to check whether an upsert had occured: checking the type of affectedDocuments or running another find query on
             *          the whole dataset to check its size. Both options being ugly, the breaking change was necessary.
             *
             * @api private Use Datastore.update which has the same signature
             */
            Datastore.prototype._update = function (query, updateQuery, options, cb) {
                var callback, self = this,
                    numReplaced = 0,
                    multi, upsert, i;
 
                Iif (typeof options === 'function') {
                    cb = options;
                    options = {};
                }
                callback = cb;
                multi = options.multi !== undefined ? options.multi : false;
                upsert = options.upsert !== undefined ? options.upsert : false;
 
                var modeNext, onNext;
                modeNext = 0;
                onNext = function (error) {
                    modeNext = error
                        ? Infinity
                        : modeNext + 1;
                    switch (modeNext) {
                    case 1:
                        // If upsert option is set, check whether we need to insert the doc
                        Iif (!upsert) {
                            return onNext();
                        }
 
                        // Need to use an internal function not tied to the executor to avoid deadlock
                        var cursor = new Cursor(self, query);
                        cursor.limit(1)._exec(function (error, docs) {
                            Iif (error) {
                                return callback(error);
                            }
                            Iif (docs.length === 1) {
                                return onNext();
                            } else {
                                var toBeInserted;
 
                                try {
                                    model.checkObject(updateQuery);
                                    // updateQuery is a simple object with no modifier, use it as the document to insert
                                    toBeInserted = updateQuery;
                                } catch (e) {
                                    // updateQuery contains modifiers, use the find query as the base,
                                    // strip it from all operators and update it according to updateQuery
                                    try {
                                        toBeInserted = model.modify(model.deepCopy(query, true), updateQuery);
                                    } catch (error) {
                                        return callback(error);
                                    }
                                }
 
                                return self._insert(toBeInserted, function (error, newDoc) {
                                    Iif (error) {
                                        return callback(error);
                                    }
                                    return callback(null, 1, newDoc, true);
                                });
                            }
                        });
                        break;
                    default:
                        // Perform the update
                        var modifiedDoc, modifications = [],
                            createdAt;
 
                        self.getCandidates(query, function (error, candidates) {
                            if (error) {
                                return callback(error);
                            }
 
                            // Preparing update (if an error is thrown here neither the datafile nor
                            // the in-memory indexes are affected)
                            try {
                                for (i = 0; i < candidates.length; i += 1) {
                                    if (model.match(candidates[i], query) && (multi || numReplaced === 0)) {
                                        numReplaced += 1;
                                        createdAt = candidates[i].createdAt;
                                        modifiedDoc = model.modify(candidates[i], updateQuery);
                                        modifiedDoc.createdAt = createdAt;
                                        modifiedDoc.updatedAt = new Date().toISOString();
                                        modifications.push({
                                            oldDoc: candidates[i],
                                            newDoc: modifiedDoc
                                        });
                                    }
                                }
                            } catch (error) {
                                return callback(error);
                            }
 
                            // Change the docs in memory
                            try {
                                self.updateIndexes(modifications);
                            } catch (error) {
                                return callback(error);
                            }
 
                            // Update the datafile
                            var updatedDocs = modifications.map(function (element) {
                                return element.newDoc;
                            });
                            self.persistence.persistNewState(updatedDocs, function (error) {
                                if (error) {
                                    return callback(error);
                                }
                                if (!options.returnUpdatedDocs) {
                                    return callback(null, numReplaced);
                                } else {
                                    var updatedDocsDC = [];
                                    updatedDocs.forEach(function (doc) {
                                        updatedDocsDC.push(model.deepCopy(doc));
                                    });
                                    if (!multi) {
                                        updatedDocsDC = updatedDocsDC[0];
                                    }
                                    return callback(null, numReplaced, updatedDocsDC);
                                }
                            });
                        });
                    }
                };
                onNext();
            };
 
            Datastore.prototype.update = function () {
                this.executor.push({
                    this: this,
                    fn: this._update,
                    arguments: arguments
                });
            };
 
 
            /**
             * Remove all docs matching the query
             * For now very naive implementation (similar to update)
             * @param {Object} query
             * @param {Object} options Optional options
             *                 options.multi If true, can update multiple documents (defaults to false)
             * @param {Function} cb Optional callback, signature: error, numRemoved
             *
             * @api private Use Datastore.remove which has the same signature
             */
            Datastore.prototype._remove = function (query, options, cb) {
                var callback, self = this,
                    numRemoved = 0,
                    removedDocs = [],
                    multi;
 
                Eif (typeof options === 'function') {
                    cb = options;
                    options = {};
                }
                callback = cb;
                multi = options.multi !== undefined ? options.multi : false;
 
                this.getCandidates(query, true, function (error, candidates) {
                    Iif (error) {
                        return callback(error);
                    }
 
                    try {
                        candidates.forEach(function (d) {
                            Eif (model.match(d, query) && (multi || numRemoved === 0)) {
                                numRemoved += 1;
                                removedDocs.push({
                                    $$deleted: true,
                                    _id: d._id
                                });
                                self.removeFromIndexes(d);
                            }
                        });
                    } catch (error) {
                        return callback(error);
                    }
 
                    self.persistence.persistNewState(removedDocs, function (error) {
                        Iif (error) {
                            return callback(error);
                        }
                        return callback(null, numRemoved);
                    });
                });
            };
 
            Datastore.prototype.remove = function () {
                this.executor.push({
                    this: this,
                    fn: this._remove,
                    arguments: arguments
                });
            };
 
 
 
            module.exports = Datastore;
 
        }, {
            "./cursor": 5,
            "./customUtils": 6,
            "./executor": 8,
            "./indexes": 9,
            "./model": 10,
            "./persistence": 11
        }],
        8: [function (require, module, exports) {
            /**
             * Responsible for sequentially executing actions on the database
             */
 
            function Executor() {
                this.buffer = [];
                this.ready = false;
 
                // This queue will execute all commands, one-by-one in order
                this.queue = local.asyncQueue(function (task, cb) {
                    var newArguments = [];
 
                    // task.arguments is an array-like object on which adding a new field doesn't work, so we transform it into a real array
                    for (var i = 0; i < task.arguments.length; i += 1) {
                        newArguments.push(task.arguments[i]);
                    }
                    var lastArg = task.arguments[task.arguments.length - 1];
 
                    // Always tell the queue task is complete. Execute callback if any was given.
                    Eif (typeof lastArg === 'function') {
                        // Callback was supplied
                        newArguments[newArguments.length - 1] = function () {
                            if (typeof setImmediate === 'function') {
                                setImmediate(cb);
                            } else {
                                setTimeout(cb);
                            }
                            lastArg.apply(null, arguments);
                        };
                    } else if (!lastArg && task.arguments.length !== 0) {
                        // false/undefined/null supplied as callbback
                        newArguments[newArguments.length - 1] = function () {
                            cb();
                        };
                    } else {
                        // Nothing supplied as callback
                        newArguments.push(function () {
                            cb();
                        });
                    }
 
 
                    task.fn.apply(task.this, newArguments);
                });
            }
 
 
            /**
             * If executor is ready, queue task (and process it immediately if executor was idle)
             * If not, buffer task for later processing
             * @param {Object} task
             *                 task.this - Object to use as this
             *                 task.fn - Function to execute
             *                 task.arguments - Array of arguments, IMPORTANT: only the last argument may be a function (the callback)
             *                                                                 and the last argument cannot be false/undefined/null
             * @param {Boolean} forceQueuing Optional (defaults to false) force executor to queue task even if it is not ready
             */
            Executor.prototype.push = function (task, forceQueuing) {
                if (this.ready || forceQueuing) {
                    this.queue.push(task);
                } else {
                    this.buffer.push(task);
                }
            };
 
 
 
            // Interface
            module.exports = Executor;
 
        }, {}],
        9: [function (require, module, exports) {
            var BinarySearchTree = require('./lib/avltree'),
                model = require('./model');
 
            /**
             * Type-aware projection
             */
            function projectForUnique(elt) {
                if (elt === null) {
                    return '$null';
                }
                if (typeof elt === 'string') {
                    return '$string' + elt;
                }
                if (typeof elt === 'boolean') {
                    return '$boolean' + elt;
                }
                if (typeof elt === 'number') {
                    return '$number' + elt;
                }
                if (Array.isArray(elt)) {
                    return '$date' + elt.getTime();
                }
 
                return elt; // Arrays and objects, will check for pointer equality
            }
 
 
            /**
             * Create a new index
             * All methods on an index guarantee that either the whole operation was successful and the index changed
             * or the operation was unsuccessful and an error is thrown while the index is unchanged
             * @param {String} options.fieldName On which field should the index apply (can use dot notation to index on sub fields)
             * @param {Boolean} options.unique Optional, enforce a unique constraint (default: false)
             * @param {Boolean} options.sparse Optional, allow a sparse index (we can have documents for which fieldName is undefined) (default: false)
             */
            function Index(options) {
                this.fieldName = options.fieldName;
                this.unique = options.unique || false;
                this.sparse = options.sparse || false;
 
                this.treeOptions = { unique: this.unique };
 
                this.reset(); // No data in the beginning
            }
 
 
            /**
             * Reset an index
             * @param {Document or Array of documents} newData Optional, data to initialize the index with
             *                                                 If an error is thrown during insertion, the index is not modified
             */
            Index.prototype.reset = function (newData) {
                this.tree = new BinarySearchTree(this.treeOptions);
 
                if (newData) {
                    this.insert(newData);
                }
            };
 
 
            /**
             * Insert a new document in the index
             * If an array is passed, we insert all its elements (if one insertion fails the index is not modified)
             * O(log(n))
             */
            Index.prototype.insert = function (doc) {
                var key, self = this,
                    keys, i, failingI, error;
 
                if (Array.isArray(doc)) {
                    this.insertMultipleDocs(doc);
                    return;
                }
 
                key = model.getDotValue(doc, this.fieldName);
 
                // We don't index documents that don't contain the field if the index is sparse
                if (key === undefined && this.sparse) {
                    return;
                }
 
                Eif (!Array.isArray(key)) {
                    this.tree.insert(key, doc);
                } else {
                    // If an insert fails due to a unique constraint, roll back all inserts before it
                    keys = local.listUnique(key).map(projectForUnique);
 
                    for (i = 0; i < keys.length; i += 1) {
                        try {
                            this.tree.insert(keys[i], doc);
                        } catch (e) {
                            error = e;
                            failingI = i;
                            break;
                        }
                    }
 
                    if (error) {
                        for (i = 0; i < failingI; i += 1) {
                            this.tree.delete(keys[i], doc);
                        }
 
                        throw error;
                    }
                }
            };
 
 
            /**
             * Insert an array of documents in the index
             * If a constraint is violated, the changes should be rolled back and an error thrown
             *
             * @API private
             */
            Index.prototype.insertMultipleDocs = function (docs) {
                var i, error, failingI;
 
                for (i = 0; i < docs.length; i += 1) {
                    try {
                        this.insert(docs[i]);
                    } catch (e) {
                        error = e;
                        failingI = i;
                        break;
                    }
                }
 
                Iif (error) {
                    for (i = 0; i < failingI; i += 1) {
                        this.remove(docs[i]);
                    }
 
                    throw error;
                }
            };
 
 
            /**
             * Remove a document from the index
             * If an array is passed, we remove all its elements
             * The remove operation is safe with regards to the 'unique' constraint
             * O(log(n))
             */
            Index.prototype.remove = function (doc) {
                var key, self = this;
 
                Iif (Array.isArray(doc)) {
                    doc.forEach(function (d) {
                        self.remove(d);
                    });
                    return;
                }
 
                key = model.getDotValue(doc, this.fieldName);
 
                if (key === undefined && this.sparse) {
                    return;
                }
 
                Eif (!Array.isArray(key)) {
                    this.tree.delete(key, doc);
                } else {
                    local.listUnique(key).map(projectForUnique).forEach(function (_key) {
                        self.tree.delete(_key, doc);
                    });
                }
            };
 
 
            /**
             * Update a document in the index
             * If a constraint is violated, changes are rolled back and an error thrown
             * Naive implementation, still in O(log(n))
             */
            Index.prototype.update = function (oldDoc, newDoc) {
                if (Array.isArray(oldDoc)) {
                    this.updateMultipleDocs(oldDoc);
                    return;
                }
 
                this.remove(oldDoc);
 
                try {
                    this.insert(newDoc);
                } catch (e) {
                    this.insert(oldDoc);
                    throw e;
                }
            };
 
 
            /**
             * Update multiple documents in the index
             * If a constraint is violated, the changes need to be rolled back
             * and an error thrown
             * @param {Array of oldDoc, newDoc pairs} pairs
             *
             * @API private
             */
            Index.prototype.updateMultipleDocs = function (pairs) {
                var i, failingI, error;
 
                for (i = 0; i < pairs.length; i += 1) {
                    this.remove(pairs[i].oldDoc);
                }
 
                for (i = 0; i < pairs.length; i += 1) {
                    try {
                        this.insert(pairs[i].newDoc);
                    } catch (e) {
                        error = e;
                        failingI = i;
                        break;
                    }
                }
 
                // If an error was raised, roll back changes in the inverse order
                if (error) {
                    for (i = 0; i < failingI; i += 1) {
                        this.remove(pairs[i].newDoc);
                    }
 
                    for (i = 0; i < pairs.length; i += 1) {
                        this.insert(pairs[i].oldDoc);
                    }
 
                    throw error;
                }
            };
 
 
            /**
             * Revert an update
             */
            Index.prototype.revertUpdate = function (oldDoc, newDoc) {
                var revert = [];
 
                if (!Array.isArray(oldDoc)) {
                    this.update(newDoc, oldDoc);
                } else {
                    oldDoc.forEach(function (pair) {
                        revert.push({
                            oldDoc: pair.newDoc,
                            newDoc: pair.oldDoc
                        });
                    });
                    this.update(revert);
                }
            };
 
 
            /**
             * Get all documents in index whose key match value (if it is a Thing) or one of the elements of value (if it is an array of Things)
             * @param {Thing} value Value to match the key against
             * @return {Array of documents}
             */
            Index.prototype.getMatching = function (value) {
                var self = this;
 
                Eif (!Array.isArray(value)) {
                    return self.tree.search(value);
                } else {
                    var _res = {},
                        res = [];
 
                    value.forEach(function (v) {
                        self.getMatching(v).forEach(function (doc) {
                            _res[doc._id] = doc;
                        });
                    });
 
                    Object.keys(_res).forEach(function (_id) {
                        res.push(_res[_id]);
                    });
 
                    return res;
                }
            };
 
 
            /**
             * Get all documents in index whose key is between bounds are they are defined by query
             * Documents are sorted by key
             * @param {Query} query
             * @return {Array of documents}
             */
            Index.prototype.getBetweenBounds = function (query) {
                return this.tree.betweenBounds(query);
            };
 
 
            /**
             * Get all elements in the index
             * @return {Array of documents}
             */
            Index.prototype.getAll = function () {
                var res = [];
 
                this.tree.executeOnEveryNode(function (node) {
                    var i;
 
                    for (i = 0; i < node.data.length; i += 1) {
                        res.push(node.data[i]);
                    }
                });
 
                return res;
            };
 
 
 
 
            // Interface
            module.exports = Index;
 
        }, {
            "./model": 10,
            "./lib/avltree": 15
        }],
        10: [function(require, module, exports) {
            /**
             * Handle models (i.e. docs)
             * Serialization/deserialization
             * Copying
             * Querying, update
             */
 
            var modifierFunctions = {},
                lastStepModifierFunctions = {},
                comparisonFunctions = {},
                logicalOperators = {},
                arrayComparisonFunctions = {};
 
 
            /**
             * Check a key, throw an error if the key is non valid
             * @param {String} k key
             * @param {Model} v value, needed to treat the Date edge case
             * Non-treatable edge cases here: if part of the object if of the form { $$date: number } or { $$deleted: true }
             * Its serialized-then-deserialized version it will transformed into a Date object
             * But you really need to want it to trigger such behaviour, even when warned not to use '$' at the beginning of the field names...
             */
            function checkKey(k, v) {
                Iif (typeof k === 'number') {
                    k = k.toString();
                }
 
                Iif (k[0] === '$' && !(k === '$$date' && typeof v === 'number') && !(k === '$$deleted' && v === true) && !(k === '$$indexCreated') && !(k === '$$indexRemoved')) {
                    throw new Error('Field names cannot begin with the $ character');
                }
 
                Iif (k.indexOf('.') !== -1) {
                    throw new Error('Field names cannot contain a .');
                }
            }
 
 
            /**
             * Check a DB object and throw an error if it's not valid
             * Works by applying the above checkKey function to all fields recursively
             */
            function checkObject(obj) {
                Iif (Array.isArray(obj)) {
                    obj.forEach(function(o) {
                        checkObject(o);
                    });
                }
 
                if (typeof obj === 'object' && obj !== null) {
                    Object.keys(obj).forEach(function(k) {
                        checkKey(k, obj[k]);
                        checkObject(obj[k]);
                    });
                }
            }
 
 
            /**
             * Serialize an object to be persisted to a one-line string
             * For serialization/deserialization, we use the native JSON parser and not eval or Function
             * That gives us less freedom but data entered in the database may come from users
             * so eval and the like are not safe
             * Accepted primitive types: Number, String, Boolean, Date, null
             * Accepted secondary types: Objects, Arrays
             */
            function serialize(obj) {
                var res;
 
                res = JSON.stringify(obj, function(k, v) {
                    checkKey(k, v);
 
                    Iif (v === undefined) {
                        return undefined;
                    }
                    Iif (v === null) {
                        return null;
                    }
 
                    // Hackish way of checking if object is Date (this way it works between execution contexts in node-webkit).
                    // We can't use value directly because for dates it is already string in this function (date.toJSON was already called), so we use this
                    Iif (typeof this[k].getTime === 'function') {
                        return {
                            $$date: this[k].getTime()
                        };
                    }
 
                    return v;
                });
 
                return res;
            }
 
 
            /**
             * From a one-line representation of an object generate by the serialize function
             * Return the object itself
             */
            function deserialize(rawData) {
                return JSON.parse(rawData, function(k, v) {
                    Iif (k === '$$date') {
                        return new Date(v).toISOString();
                    }
                    if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null) {
                        return v;
                    }
                    Iif (v && v.$$date) {
                        return v.$$date;
                    }
 
                    return v;
                });
            }
 
 
            /**
             * Deep copy a DB object
             * The optional strictKeys flag (defaulting to false) indicates whether to copy everything or only fields
             * where the keys are valid, i.e. don't begin with $ and don't contain a .
             */
            function deepCopy(obj, strictKeys) {
                var res;
 
                if (typeof obj === 'boolean' ||
                    typeof obj === 'number' ||
                    typeof obj === 'string' ||
                    obj === null ||
                    (local.isDate(obj))) {
                    return obj;
                }
 
                Iif (Array.isArray(obj)) {
                    res = [];
                    obj.forEach(function(o) {
                        res.push(deepCopy(o, strictKeys));
                    });
                    return res;
                }
 
                Eif (typeof obj === 'object') {
                    res = {};
                    Object.keys(obj).forEach(function(k) {
                        Eif (!strictKeys || (k[0] !== '$' && k.indexOf('.') === -1)) {
                            res[k] = deepCopy(obj[k], strictKeys);
                        }
                    });
                    return res;
                }
 
                return undefined; // For now everything else is undefined. We should probably throw an error instead
            }
 
 
            /**
             * Tells if an object is a primitive type or a 'real' object
             * Arrays are considered primitive
             */
            function isPrimitiveType(obj) {
                return (typeof obj === 'boolean' ||
                    typeof obj === 'number' ||
                    typeof obj === 'string' ||
                    obj === null ||
                    local.isDate(obj) ||
                    Array.isArray(obj));
            }
 
 
 
            // ==============================================================
            // Updating documents
            // ==============================================================
 
            /**
             * The signature of modifier functions is as follows
             * Their structure is always the same: recursively follow the dot notation while creating
             * the nested documents if needed, then apply the "last step modifier"
             * @param {Object} obj The model to modify
             * @param {String} field Can contain dots, in that case that means we will set a subfield recursively
             * @param {Model} value
             */
 
            /**
             * Set a field to a new value
             */
            lastStepModifierFunctions.$set = function(obj, field, value) {
                obj[field] = value;
            };
 
 
            /**
             * Unset a field
             */
            lastStepModifierFunctions.$unset = function(obj, field, value) {
                delete obj[field];
            };
 
 
            /**
             * Push an element to the end of an array field
             * Optional modifier $each instead of value to push several values
             * Optional modifier $slice to slice the resulting array, see https://docs.mongodb.org/manual/reference/operator/update/slice/
             * Différeence with MongoDB: if $slice is specified and not $each, we act as if value is an empty array
             */
            lastStepModifierFunctions.$push = function(obj, field, value) {
                // Create the array if it doesn't exist
                if (!obj.hasOwnProperty(field)) {
                    obj[field] = [];
                }
 
                if (!Array.isArray(obj[field])) {
                    throw new Error("Can't $push an element on non-array values");
                }
 
                if (value !== null && typeof value === 'object' && value.$slice && value.$each === undefined) {
                    value.$each = [];
                }
 
                if (value !== null && typeof value === 'object' && value.$each) {
                    if (Object.keys(value).length >= 3 || (Object.keys(value).length === 2 && value.$slice === undefined)) {
                        throw new Error("Can only use $slice in cunjunction with $each when $push to array");
                    }
                    if (!Array.isArray(value.$each)) {
                        throw new Error("$each requires an array value");
                    }
 
                    value.$each.forEach(function(v) {
                        obj[field].push(v);
                    });
 
                    if (value.$slice === undefined || typeof value.$slice !== 'number') {
                        return;
                    }
 
                    if (value.$slice === 0) {
                        obj[field] = [];
                    } else {
                        var start, end, n = obj[field].length;
                        if (value.$slice < 0) {
                            start = Math.max(0, n + value.$slice);
                            end = n;
                        } else if (value.$slice > 0) {
                            start = 0;
                            end = Math.min(n, value.$slice);
                        }
                        obj[field] = obj[field].slice(start, end);
                    }
                } else {
                    obj[field].push(value);
                }
            };
 
 
            /**
             * Add an element to an array field only if it is not already in it
             * No modification if the element is already in the array
             * Note that it doesn't check whether the original array contains duplicates
             */
            lastStepModifierFunctions.$addToSet = function(obj, field, value) {
                var addToSet = true;
 
                // Create the array if it doesn't exist
                if (!obj.hasOwnProperty(field)) {
                    obj[field] = [];
                }
 
                if (!Array.isArray(obj[field])) {
                    throw new Error("Can't $addToSet an element on non-array values");
                }
 
                if (value !== null && typeof value === 'object' && value.$each) {
                    if (Object.keys(value).length > 1) {
                        throw new Error("Can't use another field in conjunction with $each");
                    }
                    if (!Array.isArray(value.$each)) {
                        throw new Error("$each requires an array value");
                    }
 
                    value.$each.forEach(function(v) {
                        lastStepModifierFunctions.$addToSet(obj, field, v);
                    });
                } else {
                    obj[field].forEach(function(v) {
                        if (local.sortCompare(v, value) === 0) {
                            addToSet = false;
                        }
                    });
                    if (addToSet) {
                        obj[field].push(value);
                    }
                }
            };
 
 
            /**
             * Remove the first or last element of an array
             */
            lastStepModifierFunctions.$pop = function(obj, field, value) {
                if (!Array.isArray(obj[field])) {
                    throw new Error("Can't $pop an element from non-array values");
                }
                if (typeof value !== 'number') {
                    throw new Error(value + " isn't an integer, can't use it with $pop");
                }
                if (value === 0) {
                    return;
                }
 
                if (value > 0) {
                    obj[field] = obj[field].slice(0, obj[field].length - 1);
                } else {
                    obj[field] = obj[field].slice(1);
                }
            };
 
 
            /**
             * Removes all instances of a value from an existing array
             */
            lastStepModifierFunctions.$pull = function(obj, field, value) {
                var arr, i;
 
                if (!Array.isArray(obj[field])) {
                    throw new Error("Can't $pull an element from non-array values");
                }
 
                arr = obj[field];
                for (i = arr.length - 1; i >= 0; i -= 1) {
                    if (match(arr[i], value)) {
                        arr.splice(i, 1);
                    }
                }
            };
 
 
            /**
             * Increment a numeric field's value
             */
            lastStepModifierFunctions.$inc = function(obj, field, value) {
                if (typeof value !== 'number') {
                    throw new Error(value + " must be a number");
                }
 
                if (typeof obj[field] !== 'number') {
                    if (!obj.hasOwnProperty(field)) {
                        obj[field] = value;
                    } else {
                        throw new Error("Don't use the $inc modifier on non-number fields");
                    }
                } else {
                    obj[field] += value;
                }
            };
 
            /**
             * Updates the value of the field, only if specified field is greater than the current value of the field
             */
            lastStepModifierFunctions.$max = function(obj, field, value) {
                if (typeof obj[field] === 'undefined') {
                    obj[field] = value;
                } else if (value > obj[field]) {
                    obj[field] = value;
                }
            };
 
            /**
             * Updates the value of the field, only if specified field is smaller than the current value of the field
             */
            lastStepModifierFunctions.$min = function(obj, field, value) {
                if (typeof obj[field] === 'undefined') {
                    obj[field] = value;
                } else if (value < obj[field]) {
                    obj[field] = value;
                }
            };
 
            // Given its name, create the complete modifier function
            function createModifierFunction(modifier) {
                return function(obj, field, value) {
                    var fieldParts = typeof field === 'string' ? field.split('.') : field;
 
                    if (fieldParts.length === 1) {
                        lastStepModifierFunctions[modifier](obj, field, value);
                    } else {
                        if (obj[fieldParts[0]] === undefined) {
                            if (modifier === '$unset') {
                                return;
                            } // Bad looking specific fix, needs to be generalized modifiers that behave like $unset are implemented
                            obj[fieldParts[0]] = {};
                        }
                        modifierFunctions[modifier](obj[fieldParts[0]], fieldParts.slice(1), value);
                    }
                };
            }
 
            // Actually create all modifier functions
            Object.keys(lastStepModifierFunctions).forEach(function(modifier) {
                modifierFunctions[modifier] = createModifierFunction(modifier);
            });
 
 
            /**
             * Modify a DB object according to an update query
             */
            function modify(obj, updateQuery) {
                var keys = Object.keys(updateQuery),
                    firstChars = keys.map(function(item) {
                        return item[0];
                    }),
                    dollarFirstChars = firstChars.filter(function(c) {
                        return c === '$';
                    }),
                    newDoc, modifiers;
 
                if (keys.indexOf('_id') !== -1 && updateQuery._id !== obj._id) {
                    throw new Error("You cannot change a document's _id");
                }
 
                if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) {
                    throw new Error("You cannot mix modifiers and normal fields");
                }
 
                if (dollarFirstChars.length === 0) {
                    // Simply replace the object with the update query contents
                    newDoc = deepCopy(updateQuery);
                    newDoc._id = obj._id;
                } else {
                    // Apply modifiers
                    modifiers = local.listUnique(keys);
                    newDoc = deepCopy(obj);
                    modifiers.forEach(function(m) {
                        var keys;
 
                        if (!modifierFunctions[m]) {
                            throw new Error("Unknown modifier " + m);
                        }
 
                        // Can't rely on Object.keys throwing on non objects since ES6
                        // Not 100% satisfying as non objects can be interpreted as objects but no false negatives so we can live with it
                        if (typeof updateQuery[m] !== 'object') {
                            throw new Error("Modifier " + m + "'s argument must be an object");
                        }
 
                        keys = Object.keys(updateQuery[m]);
                        keys.forEach(function(k) {
                            modifierFunctions[m](newDoc, k, updateQuery[m][k]);
                        });
                    });
                }
 
                // Check result is valid and return it
                checkObject(newDoc);
 
                if (obj._id !== newDoc._id) {
                    throw new Error("You can't change a document's _id");
                }
                return newDoc;
            };
 
 
            // ==============================================================
            // Finding documents
            // ==============================================================
 
            /**
             * Get a value from object with dot notation
             * @param {Object} obj
             * @param {String} field
             */
            function getDotValue(obj, field) {
                var fieldParts = typeof field === 'string' ? field.split('.') : field,
                    i, objs;
 
                Iif (!obj) {
                    return undefined;
                } // field cannot be empty so that means we should return undefined so that nothing can match
 
                Iif (fieldParts.length === 0) {
                    return obj;
                }
 
                Eif (fieldParts.length === 1) {
                    return obj[fieldParts[0]];
                }
 
                if (Array.isArray(obj[fieldParts[0]])) {
                    // If the next field is an integer, return only this item of the array
                    i = parseInt(fieldParts[1], 10);
                    if (typeof i === 'number' && !isNaN(i)) {
                        return getDotValue(obj[fieldParts[0]][i], fieldParts.slice(2))
                    }
 
                    // Return the array of values
                    objs = new Array();
                    for (i = 0; i < obj[fieldParts[0]].length; i += 1) {
                        objs.push(getDotValue(obj[fieldParts[0]][i], fieldParts.slice(1)));
                    }
                    return objs;
                } else {
                    return getDotValue(obj[fieldParts[0]], fieldParts.slice(1));
                }
            }
 
 
            /**
             * Check whether 'things' are equal
             * Things are defined as any native types (string, number, boolean, null, date) and objects
             * In the case of object, we check deep equality
             * Returns true if they are, false otherwise
             */
            function areThingsEqual(a, b) {
                var aKeys, bKeys, i;
 
                // Strings, booleans, numbers, null
                Eif (a === null || typeof a === 'string' || typeof a === 'boolean' || typeof a === 'number' ||
                    b === null || typeof b === 'string' || typeof b === 'boolean' || typeof b === 'number') {
                    return a === b;
                }
 
                // Dates
                if (local.isDate(a) || local.isDate(b)) {
                    return local.isDate(a) && local.isDate(b) && a.getTime() === b.getTime();
                }
 
                // Arrays (no match since arrays are used as a $in)
                // undefined (no match since they mean field doesn't exist and can't be serialized)
                if ((!(Array.isArray(a) && Array.isArray(b)) && (Array.isArray(a) || Array.isArray(b))) || a === undefined || b === undefined) {
                    return false;
                }
 
                // General objects (check for deep equality)
                // a and b should be objects at this point
                try {
                    aKeys = Object.keys(a);
                    bKeys = Object.keys(b);
                } catch (e) {
                    return false;
                }
 
                if (aKeys.length !== bKeys.length) {
                    return false;
                }
                for (i = 0; i < aKeys.length; i += 1) {
                    if (bKeys.indexOf(aKeys[i]) === -1) {
                        return false;
                    }
                    if (!areThingsEqual(a[aKeys[i]], b[aKeys[i]])) {
                        return false;
                    }
                }
                return true;
            }
 
 
            /**
             * Check that two values are comparable
             */
            function areComparable(a, b) {
                if (typeof a !== 'string' && typeof a !== 'number' && !local.isDate(a) &&
                    typeof b !== 'string' && typeof b !== 'number' && !local.isDate(b)) {
                    return false;
                }
 
                if (typeof a !== typeof b) {
                    return false;
                }
 
                return true;
            }
 
 
            /**
             * Arithmetic and comparison operators
             * @param {Native value} a Value in the object
             * @param {Native value} b Value in the query
             */
            comparisonFunctions.$lt = function(a, b) {
                return areComparable(a, b) && a < b;
            };
 
            comparisonFunctions.$lte = function(a, b) {
                return areComparable(a, b) && a <= b;
            };
 
            comparisonFunctions.$gt = function(a, b) {
                return areComparable(a, b) && a > b;
            };
 
            comparisonFunctions.$gte = function(a, b) {
                return areComparable(a, b) && a >= b;
            };
 
            comparisonFunctions.$ne = function(a, b) {
                if (a === undefined) {
                    return true;
                }
                return !areThingsEqual(a, b);
            };
 
            comparisonFunctions.$in = function(a, b) {
                var i;
 
                if (!Array.isArray(b)) {
                    throw new Error("$in operator called with a non-array");
                }
 
                for (i = 0; i < b.length; i += 1) {
                    if (areThingsEqual(a, b[i])) {
                        return true;
                    }
                }
 
                return false;
            };
 
            comparisonFunctions.$nin = function(a, b) {
                if (!Array.isArray(b)) {
                    throw new Error("$nin operator called with a non-array");
                }
 
                return !comparisonFunctions.$in(a, b);
            };
 
            comparisonFunctions.$regex = function(a, b) {
                if (!local.isRegExp(b)) {
                    throw new Error("$regex operator called with non regular expression");
                }
 
                if (typeof a !== 'string') {
                    return false
                } else {
                    return b.test(a);
                }
            };
 
            comparisonFunctions.$exists = function(value, exists) {
                if (exists || exists === '') { // This will be true for all values of exists except false, null, undefined and 0
                    exists = true; // That's strange behaviour (we should only use true/false) but that's the way Mongo does it...
                } else {
                    exists = false;
                }
 
                if (value === undefined) {
                    return !exists
                } else {
                    return exists;
                }
            };
 
            // Specific to arrays
            comparisonFunctions.$size = function(obj, value) {
                if (!Array.isArray(obj)) {
                    return false;
                }
                if (value % 1 !== 0) {
                    throw new Error("$size operator called without an integer");
                }
 
                return (obj.length == value);
            };
            comparisonFunctions.$elemMatch = function(obj, value) {
                if (!Array.isArray(obj)) {
                    return false;
                }
                var i = obj.length;
                var result = false; // Initialize result
                while (i--) {
                    if (match(obj[i], value)) { // If match for array element, return true
                        result = true;
                        break;
                    }
                }
                return result;
            };
            arrayComparisonFunctions.$size = true;
            arrayComparisonFunctions.$elemMatch = true;
 
 
            /**
             * Match any of the subqueries
             * @param {Model} obj
             * @param {Array of Queries} query
             */
            logicalOperators.$or = function(obj, query) {
                var i;
 
                if (!Array.isArray(query)) {
                    throw new Error("$or operator used without an array");
                }
 
                for (i = 0; i < query.length; i += 1) {
                    if (match(obj, query[i])) {
                        return true;
                    }
                }
 
                return false;
            };
 
 
            /**
             * Match all of the subqueries
             * @param {Model} obj
             * @param {Array of Queries} query
             */
            logicalOperators.$and = function(obj, query) {
                var i;
 
                if (!Array.isArray(query)) {
                    throw new Error("$and operator used without an array");
                }
 
                for (i = 0; i < query.length; i += 1) {
                    if (!match(obj, query[i])) {
                        return false;
                    }
                }
 
                return true;
            };
 
 
            /**
             * Inverted match of the query
             * @param {Model} obj
             * @param {Query} query
             */
            logicalOperators.$not = function(obj, query) {
                return !match(obj, query);
            };
 
 
            /**
             * Use a function to match
             * @param {Model} obj
             * @param {Query} query
             */
            logicalOperators.$where = function(obj, fn) {
                var result;
 
                if (typeof fn !== 'function') {
                    throw new Error("$where operator used without a function");
                }
 
                result = fn.call(obj);
                if (typeof result !== 'boolean') {
                    throw new Error("$where function must return boolean");
                }
 
                return result;
            };
 
 
            /**
             * Tell if a given document matches a query
             * @param {Object} obj Document to check
             * @param {Object} query
             */
            function match(obj, query) {
                var queryKeys, queryKey, queryValue, i;
 
                // Primitive query against a primitive type
                // This is a bit of a hack since we construct an object with an arbitrary key only to dereference it later
                // But I don't have time for a cleaner implementation now
                Iif (isPrimitiveType(obj) || isPrimitiveType(query)) {
                    return matchQueryPart({
                        needAKey: obj
                    }, 'needAKey', query);
                }
 
                // Normal query
                queryKeys = Object.keys(query);
                for (i = 0; i < queryKeys.length; i += 1) {
                    queryKey = queryKeys[i];
                    queryValue = query[queryKey];
 
                    Iif (queryKey[0] === '$') {
                        if (!logicalOperators[queryKey]) {
                            throw new Error("Unknown logical operator " + queryKey);
                        }
                        if (!logicalOperators[queryKey](obj, queryValue)) {
                            return false;
                        }
                    } else {
                        Iif (!matchQueryPart(obj, queryKey, queryValue)) {
                            return false;
                        }
                    }
                }
 
                return true;
            };
 
 
            /**
             * Match an object against a specific { key: value } part of a query
             * if the treatObjAsValue flag is set, don't try to match every part separately, but the array as a whole
             */
            function matchQueryPart(obj, queryKey, queryValue, treatObjAsValue) {
                var objValue = getDotValue(obj, queryKey),
                    i, keys, firstChars, dollarFirstChars;
 
                // Check if the value is an array if we don't force a treatment as value
                Iif (Array.isArray(objValue) && !treatObjAsValue) {
                    // If the queryValue is an array, try to perform an exact match
                    if (Array.isArray(queryValue)) {
                        return matchQueryPart(obj, queryKey, queryValue, true);
                    }
 
                    // Check if we are using an array-specific comparison function
                    if (queryValue !== null && typeof queryValue === 'object' && !local.isRegExp(queryValue)) {
                        keys = Object.keys(queryValue);
                        for (i = 0; i < keys.length; i += 1) {
                            if (arrayComparisonFunctions[keys[i]]) {
                                return matchQueryPart(obj, queryKey, queryValue, true);
                            }
                        }
                    }
 
                    // If not, treat it as an array of { obj, query } where there needs to be at least one match
                    for (i = 0; i < objValue.length; i += 1) {
                        if (matchQueryPart({
                                k: objValue[i]
                            }, 'k', queryValue)) {
                            return true;
                        } // k here could be any string
                    }
                    return false;
                }
 
                // queryValue is an actual object. Determine whether it contains comparison operators
                // or only normal fields. Mixed objects are not allowed
                Iif (queryValue !== null && typeof queryValue === 'object' && !local.isRegExp(queryValue) && !Array.isArray(queryValue)) {
                    keys = Object.keys(queryValue);
                    firstChars = keys.map(function(item) {
                        return item[0];
                    });
                    dollarFirstChars = firstChars.filter(function(c) {
                        return c === '$';
                    });
 
                    if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) {
                        throw new Error("You cannot mix operators and normal fields");
                    }
 
                    // queryValue is an object of this form: { $comparisonOperator1: value1, ... }
                    if (dollarFirstChars.length > 0) {
                        for (i = 0; i < keys.length; i += 1) {
                            if (!comparisonFunctions[keys[i]]) {
                                throw new Error("Unknown comparison function " + keys[i]);
                            }
 
                            if (!comparisonFunctions[keys[i]](objValue, queryValue[keys[i]])) {
                                return false;
                            }
                        }
                        return true;
                    }
                }
 
                // Using regular expressions with basic querying
                Iif (local.isRegExp(queryValue)) {
                    return comparisonFunctions.$regex(objValue, queryValue);
                }
 
                // queryValue is either a native value or a normal object
                // Basic matching is possible
                Iif (!areThingsEqual(objValue, queryValue)) {
                    return false;
                }
 
                return true;
            }
 
 
            // Interface
            module.exports.serialize = serialize;
            module.exports.deserialize = deserialize;
            module.exports.deepCopy = deepCopy;
            module.exports.checkObject = checkObject;
            module.exports.isPrimitiveType = isPrimitiveType;
            module.exports.modify = modify;
            module.exports.getDotValue = getDotValue;
            module.exports.match = match;
            module.exports.areThingsEqual = areThingsEqual;
 
        }, {}],
        11: [function(require, module, exports) {
            /**
             * Handle every persistence-related task
             * The interface Datastore expects to be implemented is
             * * Persistence.loadDatabase(callback) and callback has signature error
             * * Persistence.persistNewState(newDocs, callback) where newDocs is an array of documents and callback has signature error
             */
 
            var model = require('./model'),
                customUtils = require('./customUtils'),
                Index = require('./indexes');
 
 
            /**
             * Create a new Persistence object for database options.db
             * @param {Datastore} options.db
             */
            function Persistence(options) {
                var i, j, randomString;
 
                this.db = options.db;
            };
 
 
            /**
             * Persist cached database
             * This serves as a compaction function since the cache always contains only the number of documents in the collection
             * while the data file is append-only so it may grow larger
             * @param {Function} cb Optional callback, signature: error
             */
            Persistence.prototype.persistCachedDatabase = function(cb) {
                var callback = cb,
                    toPersist = '',
                    self = this;
 
                this.db.getAllData().forEach(function(doc) {
                    toPersist += model.serialize(doc) + '\n';
                });
                Object.keys(this.db.indexes).forEach(function(fieldName) {
                    if (fieldName != '_id') { // The special _id index is managed by datastore.js, the others need to be persisted
                        toPersist += model.serialize({
                            $$indexCreated: {
                                fieldName: fieldName,
                                unique: self.db.indexes[fieldName].unique,
                                sparse: self.db.indexes[fieldName].sparse
                            }
                        }) + '\n';
                    }
                });
 
                local.storeSetItem(this.db.name, toPersist, function(error) {
                    Iif (error) {
                        return callback(error);
                    }
                    return callback();
                });
            };
 
 
            /**
             * Queue a rewrite of the datafile
             */
            Persistence.prototype.compactDatafile = function() {
                this.db.executor.push({
                    this: this,
                    fn: this.persistCachedDatabase,
                    arguments: []
                });
            };
 
 
            Persistence.prototype.persistNewState = function(newDocs, cb) {
            /**
             * Persist new state for the given newDocs (can be insertion, update or removal)
             * Use an append-only format
             * @param {Array} newDocs Can be empty if no doc was updated/removed
             * @param {Function} cb Optional, signature: error
             */
                var self = this,
                    toPersist = '',
                    callback = cb;
 
                newDocs.forEach(function(doc) {
                    toPersist += model.serialize(doc) + '\n';
                });
 
                Iif (toPersist.length === 0) {
                    return callback();
                }
 
                local.storeGetItem(self.db.name, function (error, data) {
                    local.storeSetItem(self.db.name, (data || '') + toPersist, callback);
                });
            };
 
 
            /**
             * From a database's raw data, return the corresponding
             * machine understandable collection
             */
            Persistence.prototype.treatRawData = function(rawData) {
                var data = rawData.split('\n'),
                    dataById = {},
                    tdata = [],
                    i, indexes = {},
                    corruptItems = -1 // Last line of every data file is usually blank so not really corrupt
                ;
 
                for (i = 0; i < data.length; i += 1) {
                    var doc;
 
                    try {
                        doc = model.deserialize(data[i]);
                        Iif (doc._id) {
                            if (doc.$$deleted === true) {
                                delete dataById[doc._id];
                            } else {
                                dataById[doc._id] = doc;
                            }
                        } else if (doc.$$indexCreated && doc.$$indexCreated.fieldName != undefined) {
                            indexes[doc.$$indexCreated.fieldName] = doc.$$indexCreated;
                        } else Iif (typeof doc.$$indexRemoved === 'string') {
                            delete indexes[doc.$$indexRemoved];
                        }
                    } catch (errorCaught) {
                        corruptItems += 1;
                        // validate no error occurred
                        local.assert(!corruptItems, errorCaught);
                    }
                }
 
                Object.keys(dataById).forEach(function(k) {
                    tdata.push(dataById[k]);
                });
 
                return {
                    data: tdata,
                    indexes: indexes
                };
            };
 
 
            /**
             * Load the database
             * 1) Create all indexes
             * 2) Insert all data
             * 3) Compact the database
             * This means pulling data out of the data file or creating it if it doesn't exist
             * Also, all data is persisted right away, which has the effect of compacting the database file
             * This operation is very quick at startup for a big collection (60ms for ~10k docs)
             * @param {Function} cb Optional callback, signature: error
             */
            Persistence.prototype.loadDatabase = function(cb) {
                var callback = cb,
                    self = this;
 
                self.db.resetIndexes();
 
                var dir, modeNext, onNext;
                modeNext = 0;
                onNext = function (error) {
                    modeNext = error
                        ? Infinity
                        : modeNext + 1;
                    switch (modeNext) {
                    case 1:
                        local.storeGetItem(self.db.name, function(error, rawData) {
                            try {
                                var treatedData = self.treatRawData(rawData || '');
                            } catch (e) {
                                return onNext(e);
                            }
 
                            // Recreate all indexes in the datafile
                            Object.keys(treatedData.indexes).forEach(function(key) {
                                self.db.indexes[key] = new Index(treatedData.indexes[key]);
                            });
 
                            // Fill cached database (i.e. all indexes) with data
                            try {
                                self.db.resetIndexes(treatedData.data);
                            } catch (e) {
                                self.db.resetIndexes(); // Rollback any index which didn't fail
                                return onNext(e);
                            }
 
                            self.db.persistence.persistCachedDatabase(onNext);
                        });
                        break;
                    default:
                        Iif (error) {
                            return callback(error);
                        }
 
                        /**
                         * Queue all tasks in buffer (in the same order they came in)
                         * Automatically sets executor as ready
                         */
                        self.db.executor.ready = true;
                        while (self.db.executor.buffer.length) {
                            self.db.executor.queue.push(self.db.executor.buffer.shift());
                        }
 
                        return callback();
                    }
                };
                onNext();
            };
 
 
            // Interface
            module.exports = Persistence;
 
        }, {
            "./customUtils": 6,
            "./indexes": 9,
            "./model": 10
        }],
        15: [function(require, module, exports) {
            /**
             * Self-balancing binary search tree using the AVL implementation
             */
            var BinarySearchTree = require('./bst');
 
 
            /**
             * Constructor
             * We can't use a direct pointer to the root node (as in the simple binary search tree)
             * as the root will change during tree rotations
             * @param {Boolean}  options.unique Whether to enforce a 'unique' constraint on the key or not
             */
            function AVLTree(options) {
                this.tree = new _AVLTree(options);
            }
 
 
            /**
             * Constructor of the internal AVLTree
             * @param {Object} options Optional
             * @param {Boolean}  options.unique Whether to enforce a 'unique' constraint on the key or not
             * @param {Key}      options.key Initialize this BST's key with key
             * @param {Value}    options.value Initialize this BST's data with [value]
             */
            function _AVLTree(options) {
                options = options || {};
 
                this.left = null;
                this.right = null;
                this.parent = options.parent !== undefined ? options.parent : null;
                if (options.hasOwnProperty('key')) {
                    this.key = options.key;
                }
                this.data = options.hasOwnProperty('value') ? [options.value] : [];
                this.unique = options.unique || false;
 
            }
 
 
            /**
             * Inherit basic functions from the basic binary search tree
             */
            local.inherits(_AVLTree, BinarySearchTree);
 
            /**
             * Keep a pointer to the internal tree constructor for testing purposes
             */
            AVLTree._AVLTree = _AVLTree;
 
 
            /**
             * Check the recorded height is correct for every node
             * Throws if one height doesn't match
             */
            _AVLTree.prototype.checkHeightCorrect = function() {
                var leftH, rightH;
 
                if (!this.hasOwnProperty('key')) {
                    return;
                } // Empty tree
 
                if (this.left && this.left.height === undefined) {
                    throw new Error("Undefined height for node " + this.left.key);
                }
                if (this.right && this.right.height === undefined) {
                    throw new Error("Undefined height for node " + this.right.key);
                }
                if (this.height === undefined) {
                    throw new Error("Undefined height for node " + this.key);
                }
 
                leftH = this.left ? this.left.height : 0;
                rightH = this.right ? this.right.height : 0;
 
                if (this.height !== 1 + Math.max(leftH, rightH)) {
                    throw new Error("Height constraint failed for node " + this.key);
                }
                if (this.left) {
                    this.left.checkHeightCorrect();
                }
                if (this.right) {
                    this.right.checkHeightCorrect();
                }
            };
 
 
            /**
             * Return the balance factor
             */
            _AVLTree.prototype.balanceFactor = function() {
                var leftH = this.left ? this.left.height : 0,
                    rightH = this.right ? this.right.height : 0;
                return leftH - rightH;
            };
 
 
            /**
             * Check that the balance factors are all between -1 and 1
             */
            _AVLTree.prototype.checkBalanceFactors = function() {
                if (Math.abs(this.balanceFactor()) > 1) {
                    throw new Error('Tree is unbalanced at node ' + this.key);
                }
 
                if (this.left) {
                    this.left.checkBalanceFactors();
                }
                if (this.right) {
                    this.right.checkBalanceFactors();
                }
            };
 
 
            /**
             * When checking if the BST conditions are met, also check that the heights are correct
             * and the tree is balanced
             */
            _AVLTree.prototype.checkIsAVLT = function() {
                _AVLTree.super_.prototype.checkIsBST.call(this);
                this.checkHeightCorrect();
                this.checkBalanceFactors();
            };
            AVLTree.prototype.checkIsAVLT = function() {
                this.tree.checkIsAVLT();
            };
 
 
            /**
             * Perform a right rotation of the tree if possible
             * and return the root of the resulting tree
             * The resulting tree's nodes' heights are also updated
             */
            _AVLTree.prototype.rightRotation = function() {
                var q = this,
                    p = this.left,
                    b, ah, bh, ch;
 
                if (!p) {
                    return this;
                } // No change
 
                b = p.right;
 
                // Alter tree structure
                if (q.parent) {
                    p.parent = q.parent;
                    if (q.parent.left === q) {
                        q.parent.left = p;
                    } else {
                        q.parent.right = p;
                    }
                } else {
                    p.parent = null;
                }
                p.right = q;
                q.parent = p;
                q.left = b;
                if (b) {
                    b.parent = q;
                }
 
                // Update heights
                ah = p.left ? p.left.height : 0;
                bh = b ? b.height : 0;
                ch = q.right ? q.right.height : 0;
                q.height = Math.max(bh, ch) + 1;
                p.height = Math.max(ah, q.height) + 1;
 
                return p;
            };
 
 
            /**
             * Perform a left rotation of the tree if possible
             * and return the root of the resulting tree
             * The resulting tree's nodes' heights are also updated
             */
            _AVLTree.prototype.leftRotation = function() {
                var p = this,
                    q = this.right,
                    b, ah, bh, ch;
 
                if (!q) {
                    return this;
                } // No change
 
                b = q.left;
 
                // Alter tree structure
                if (p.parent) {
                    q.parent = p.parent;
                    if (p.parent.left === p) {
                        p.parent.left = q;
                    } else {
                        p.parent.right = q;
                    }
                } else {
                    q.parent = null;
                }
                q.left = p;
                p.parent = q;
                p.right = b;
                if (b) {
                    b.parent = p;
                }
 
                // Update heights
                ah = p.left ? p.left.height : 0;
                bh = b ? b.height : 0;
                ch = q.right ? q.right.height : 0;
                p.height = Math.max(ah, bh) + 1;
                q.height = Math.max(ch, p.height) + 1;
 
                return q;
            };
 
 
            /**
             * Modify the tree if its right subtree is too small compared to the left
             * Return the new root if any
             */
            _AVLTree.prototype.rightTooSmall = function() {
                if (this.balanceFactor() <= 1) {
                    return this;
                } // Right is not too small, don't change
 
                if (this.left.balanceFactor() < 0) {
                    this.left.leftRotation();
                }
 
                return this.rightRotation();
            };
 
 
            /**
             * Modify the tree if its left subtree is too small compared to the right
             * Return the new root if any
             */
            _AVLTree.prototype.leftTooSmall = function() {
                if (this.balanceFactor() >= -1) {
                    return this;
                } // Left is not too small, don't change
 
                if (this.right.balanceFactor() > 0) {
                    this.right.rightRotation();
                }
 
                return this.leftRotation();
            };
 
 
            /**
             * Rebalance the tree along the given path. The path is given reversed (as he was calculated
             * in the insert and delete functions).
             * Returns the new root of the tree
             * Of course, the first element of the path must be the root of the tree
             */
            _AVLTree.prototype.rebalanceAlongPath = function(path) {
                var newRoot = this,
                    rotated, i;
 
                Iif (!this.hasOwnProperty('key')) {
                    delete this.height;
                    return this;
                } // Empty tree
 
                // Rebalance the tree and update all heights
                for (i = path.length - 1; i >= 0; i -= 1) {
                    path[i].height = 1 + Math.max(path[i].left ? path[i].left.height : 0, path[i].right ? path[i].right.height : 0);
 
                    Iif (path[i].balanceFactor() > 1) {
                        rotated = path[i].rightTooSmall();
                        if (i === 0) {
                            newRoot = rotated;
                        }
                    }
 
                    Iif (path[i].balanceFactor() < -1) {
                        rotated = path[i].leftTooSmall();
                        if (i === 0) {
                            newRoot = rotated;
                        }
                    }
                }
 
                return newRoot;
            };
 
 
            /**
             * Insert a key, value pair in the tree while maintaining the AVL tree height constraint
             * Return a pointer to the root node, which may have changed
             */
            _AVLTree.prototype.insert = function(key, value) {
                var insertPath = [],
                    currentNode = this;
 
                // Empty tree, insert as root
                if (!this.hasOwnProperty('key')) {
                    this.key = key;
                    this.data.push(value);
                    this.height = 1;
                    return this;
                }
 
                // Insert new leaf at the right place
                while (true) {
                    // Same key: no change in the tree structure
                    Iif (local.sortCompare(currentNode.key, key) === 0) {
                        if (currentNode.unique) {
                            var error = new Error("Can't insert key " + key + ", it violates the unique constraint");
                            error.key = key;
                            error.errorType = 'uniqueViolated';
                            throw error;
                        } else {
                            currentNode.data.push(value);
                        }
                        return this;
                    }
 
                    insertPath.push(currentNode);
 
                    Iif (local.sortCompare(key, currentNode.key) < 0) {
                        if (!currentNode.left) {
                            insertPath.push(currentNode.createLeftChild({
                                key: key,
                                value: value
                            }));
                            break;
                        } else {
                            currentNode = currentNode.left;
                        }
                    } else {
                        Eif (!currentNode.right) {
                            insertPath.push(currentNode.createRightChild({
                                key: key,
                                value: value
                            }));
                            break;
                        } else {
                            currentNode = currentNode.right;
                        }
                    }
                }
 
                return this.rebalanceAlongPath(insertPath);
            };
 
            // Insert in the internal tree, update the pointer to the root if needed
            AVLTree.prototype.insert = function(key, value) {
                var newTree = this.tree.insert(key, value);
 
                // If newTree is undefined, that means its structure was not modified
                Eif (newTree) {
                    this.tree = newTree;
                }
            };
 
 
            /**
             * Delete a key or just a value and return the new root of the tree
             * @param {Key} key
             * @param {Value} value Optional. If not set, the whole key is deleted. If set, only this value is deleted
             */
            _AVLTree.prototype.delete = function(key, value) {
                var newData = [],
                    replaceWith, self = this,
                    currentNode = this,
                    deletePath = [];
 
                Iif (!this.hasOwnProperty('key')) {
                    return this;
                } // Empty tree
 
                // Either no match is found and the function will return from within the loop
                // Or a match is found and deletePath will contain the path from the root to the node to delete after the loop
                while (true) {
                    if (local.sortCompare(key, currentNode.key) === 0) {
                        break;
                    }
 
                    deletePath.push(currentNode);
 
                    Iif (local.sortCompare(key, currentNode.key) < 0) {
                        if (currentNode.left) {
                            currentNode = currentNode.left;
                        } else {
                            return this; // Key not found, no modification
                        }
                    } else {
                        // local.sortCompare(key, currentNode.key) is > 0
                        Eif (currentNode.right) {
                            currentNode = currentNode.right;
                        } else {
                            return this; // Key not found, no modification
                        }
                    }
                }
 
                // Delete only a value (no tree modification)
                Iif (currentNode.data.length > 1 && value) {
                    currentNode.data.forEach(function(d) {
                        if (d !== value) {
                            newData.push(d);
                        }
                    });
                    currentNode.data = newData;
                    return this;
                }
 
                // Delete a whole node
 
                // Leaf
                Eif (!currentNode.left && !currentNode.right) {
                    Iif (currentNode === this) { // This leaf is also the root
                        delete currentNode.key;
                        currentNode.data = [];
                        delete currentNode.height;
                        return this;
                    } else {
                        Iif (currentNode.parent.left === currentNode) {
                            currentNode.parent.left = null;
                        } else {
                            currentNode.parent.right = null;
                        }
                        return this.rebalanceAlongPath(deletePath);
                    }
                }
 
 
                // Node with only one child
                if (!currentNode.left || !currentNode.right) {
                    replaceWith = currentNode.left ? currentNode.left : currentNode.right;
 
                    if (currentNode === this) { // This node is also the root
                        replaceWith.parent = null;
                        return replaceWith; // height of replaceWith is necessarily 1 because the tree was balanced before deletion
                    } else {
                        if (currentNode.parent.left === currentNode) {
                            currentNode.parent.left = replaceWith;
                            replaceWith.parent = currentNode.parent;
                        } else {
                            currentNode.parent.right = replaceWith;
                            replaceWith.parent = currentNode.parent;
                        }
 
                        return this.rebalanceAlongPath(deletePath);
                    }
                }
 
 
                // Node with two children
                // Use the in-order predecessor (no need to randomize since we actively rebalance)
                deletePath.push(currentNode);
                replaceWith = currentNode.left;
 
                // Special case: the in-order predecessor is right below the node to delete
                if (!replaceWith.right) {
                    currentNode.key = replaceWith.key;
                    currentNode.data = replaceWith.data;
                    currentNode.left = replaceWith.left;
                    if (replaceWith.left) {
                        replaceWith.left.parent = currentNode;
                    }
                    return this.rebalanceAlongPath(deletePath);
                }
 
                // After this loop, replaceWith is the right-most leaf in the left subtree
                // and deletePath the path from the root (inclusive) to replaceWith (exclusive)
                while (true) {
                    if (replaceWith.right) {
                        deletePath.push(replaceWith);
                        replaceWith = replaceWith.right;
                    } else {
                        break;
                    }
                }
 
                currentNode.key = replaceWith.key;
                currentNode.data = replaceWith.data;
 
                replaceWith.parent.right = replaceWith.left;
                if (replaceWith.left) {
                    replaceWith.left.parent = replaceWith.parent;
                }
 
                return this.rebalanceAlongPath(deletePath);
            };
 
            // Delete a value
            AVLTree.prototype.delete = function(key, value) {
                var newTree = this.tree.delete(key, value);
 
                // If newTree is undefined, that means its structure was not modified
                Eif (newTree) {
                    this.tree = newTree;
                }
            };
 
 
            /**
             * Other functions we want to use on an AVLTree as if it were the internal _AVLTree
             */
            ['getNumberOfKeys', 'search', 'betweenBounds', 'prettyPrint', 'executeOnEveryNode'].forEach(function(fn) {
                AVLTree.prototype[fn] = function() {
                    return this.tree[fn].apply(this.tree, arguments);
                };
            });
 
 
            // Interface
            module.exports = AVLTree;
 
        }, {
            "./bst": 16
        }],
        16: [function(require, module, exports) {
            /**
             * Simple binary search tree
             */
 
            /**
             * Constructor
             * @param {Object} options Optional
             * @param {Boolean}  options.unique Whether to enforce a 'unique' constraint on the key or not
             * @param {Key}      options.key Initialize this BST's key with key
             * @param {Value}    options.value Initialize this BST's data with [value]
             */
            function BinarySearchTree(options) {
                options = options || {};
 
                this.left = null;
                this.right = null;
                this.parent = options.parent !== undefined ? options.parent : null;
                if (options.hasOwnProperty('key')) {
                    this.key = options.key;
                }
                this.data = options.hasOwnProperty('value') ? [options.value] : [];
                this.unique = options.unique || false;
 
            }
 
 
            // ================================
            // Methods used to test the tree
            // ================================
 
 
            /**
             * Get the descendant with max key
             */
            BinarySearchTree.prototype.getMaxKeyDescendant = function() {
                if (this.right) {
                    return this.right.getMaxKeyDescendant();
                } else {
                    return this;
                }
            };
 
 
            /**
             * Get the maximum key
             */
            BinarySearchTree.prototype.getMaxKey = function() {
                return this.getMaxKeyDescendant().key;
            };
 
 
            /**
             * Get the descendant with min key
             */
            BinarySearchTree.prototype.getMinKeyDescendant = function() {
                if (this.left) {
                    return this.left.getMinKeyDescendant()
                } else {
                    return this;
                }
            };
 
 
            /**
             * Get the minimum key
             */
            BinarySearchTree.prototype.getMinKey = function() {
                return this.getMinKeyDescendant().key;
            };
 
 
            /**
             * Check that all nodes (incl. leaves) fullfil condition given by fn
             * test is a function passed every (key, data) and which throws if the condition is not met
             */
            BinarySearchTree.prototype.checkAllNodesFullfillCondition = function(test) {
                if (!this.hasOwnProperty('key')) {
                    return;
                }
 
                test(this.key, this.data);
                if (this.left) {
                    this.left.checkAllNodesFullfillCondition(test);
                }
                if (this.right) {
                    this.right.checkAllNodesFullfillCondition(test);
                }
            };
 
 
            /**
             * Check that the core BST properties on node ordering are verified
             * Throw if they aren't
             */
            BinarySearchTree.prototype.checkNodeOrdering = function() {
                var self = this;
 
                if (!this.hasOwnProperty('key')) {
                    return;
                }
 
                if (this.left) {
                    this.left.checkAllNodesFullfillCondition(function(k) {
                        if (local.sortCompare(k, self.key) >= 0) {
                            throw new Error('Tree with root ' + self.key + ' is not a binary search tree');
                        }
                    });
                    this.left.checkNodeOrdering();
                }
 
                if (this.right) {
                    this.right.checkAllNodesFullfillCondition(function(k) {
                        if (local.sortCompare(k, self.key) <= 0) {
                            throw new Error('Tree with root ' + self.key + ' is not a binary search tree');
                        }
                    });
                    this.right.checkNodeOrdering();
                }
            };
 
 
            /**
             * Check that all pointers are coherent in this tree
             */
            BinarySearchTree.prototype.checkInternalPointers = function() {
                if (this.left) {
                    if (this.left.parent !== this) {
                        throw new Error('Parent pointer broken for key ' + this.key);
                    }
                    this.left.checkInternalPointers();
                }
 
                if (this.right) {
                    if (this.right.parent !== this) {
                        throw new Error('Parent pointer broken for key ' + this.key);
                    }
                    this.right.checkInternalPointers();
                }
            };
 
 
            /**
             * Check that a tree is a BST as defined here (node ordering and pointer references)
             */
            BinarySearchTree.prototype.checkIsBST = function() {
                this.checkNodeOrdering();
                this.checkInternalPointers();
                if (this.parent) {
                    throw new Error("The root shouldn't have a parent");
                }
            };
 
 
            /**
             * Get number of keys inserted
             */
            BinarySearchTree.prototype.getNumberOfKeys = function() {
                var res;
 
                if (!this.hasOwnProperty('key')) {
                    return 0;
                }
 
                res = 1;
                if (this.left) {
                    res += this.left.getNumberOfKeys();
                }
                if (this.right) {
                    res += this.right.getNumberOfKeys();
                }
 
                return res;
            };
 
 
 
            // ============================================
            // Methods used to actually work on the tree
            // ============================================
 
            /**
             * Create a BST similar (i.e. same options except for key and value) to the current one
             * Use the same constructor (i.e. BinarySearchTree, AVLTree etc)
             * @param {Object} options see constructor
             */
            BinarySearchTree.prototype.createSimilar = function(options) {
                options = options || {};
                options.unique = this.unique;
 
                return new this.constructor(options);
            };
 
 
            /**
             * Create the left child of this BST and return it
             */
            BinarySearchTree.prototype.createLeftChild = function(options) {
                var leftChild = this.createSimilar(options);
                leftChild.parent = this;
                this.left = leftChild;
 
                return leftChild;
            };
 
 
            /**
             * Create the right child of this BST and return it
             */
            BinarySearchTree.prototype.createRightChild = function(options) {
                var rightChild = this.createSimilar(options);
                rightChild.parent = this;
                this.right = rightChild;
 
                return rightChild;
            };
 
 
            /**
             * Insert a new element
             */
            BinarySearchTree.prototype.insert = function(key, value) {
                // Empty tree, insert as root
                if (!this.hasOwnProperty('key')) {
                    this.key = key;
                    this.data.push(value);
                    return;
                }
 
                // Same key as root
                if (local.sortCompare(this.key, key) === 0) {
                    if (this.unique) {
                        var error = new Error("Can't insert key " + key + ", it violates the unique constraint");
                        error.key = key;
                        error.errorType = 'uniqueViolated';
                        throw error;
                    } else {
                        this.data.push(value);
                    }
                    return;
                }
 
                if (local.sortCompare(key, this.key) < 0) {
                    // Insert in left subtree
                    if (this.left) {
                        this.left.insert(key, value);
                    } else {
                        this.createLeftChild({
                            key: key,
                            value: value
                        });
                    }
                } else {
                    // Insert in right subtree
                    if (this.right) {
                        this.right.insert(key, value);
                    } else {
                        this.createRightChild({
                            key: key,
                            value: value
                        });
                    }
                }
            };
 
 
            /**
             * Search for all data corresponding to a key
             */
            BinarySearchTree.prototype.search = function(key) {
                if (!this.hasOwnProperty('key')) {
                    return [];
                }
 
                if (local.sortCompare(this.key, key) === 0) {
                    return this.data;
                }
 
                Iif (local.sortCompare(key, this.key) < 0) {
                    if (this.left) {
                        return this.left.search(key);
                    } else {
                        return [];
                    }
                } else {
                    if (this.right) {
                        return this.right.search(key);
                    } else {
                        return [];
                    }
                }
            };
 
 
            /**
             * Return a function that tells whether a given key matches a lower bound
             */
            BinarySearchTree.prototype.getLowerBoundMatcher = function(query) {
                var self = this;
 
                // No lower bound
                if (!query.hasOwnProperty('$gt') && !query.hasOwnProperty('$gte')) {
                    return function() {
                        return true;
                    };
                }
 
                if (query.hasOwnProperty('$gt') && query.hasOwnProperty('$gte')) {
                    if (local.sortCompare(query.$gte, query.$gt) === 0) {
                        return function(key) {
                            return local.sortCompare(key, query.$gt) > 0;
                        };
                    }
 
                    if (local.sortCompare(query.$gte, query.$gt) > 0) {
                        return function(key) {
                            return local.sortCompare(key, query.$gte) >= 0;
                        };
                    } else {
                        return function(key) {
                            return local.sortCompare(key, query.$gt) > 0;
                        };
                    }
                }
 
                if (query.hasOwnProperty('$gt')) {
                    return function(key) {
                        return local.sortCompare(key, query.$gt) > 0;
                    };
                } else {
                    return function(key) {
                        return local.sortCompare(key, query.$gte) >= 0;
                    };
                }
            };
 
 
            /**
             * Return a function that tells whether a given key matches an upper bound
             */
            BinarySearchTree.prototype.getUpperBoundMatcher = function(query) {
                var self = this;
 
                // No lower bound
                if (!query.hasOwnProperty('$lt') && !query.hasOwnProperty('$lte')) {
                    return function() {
                        return true;
                    };
                }
 
                if (query.hasOwnProperty('$lt') && query.hasOwnProperty('$lte')) {
                    if (local.sortCompare(query.$lte, query.$lt) === 0) {
                        return function(key) {
                            return local.sortCompare(key, query.$lt) < 0;
                        };
                    }
 
                    if (local.sortCompare(query.$lte, query.$lt) < 0) {
                        return function(key) {
                            return local.sortCompare(key, query.$lte) <= 0;
                        };
                    } else {
                        return function(key) {
                            return local.sortCompare(key, query.$lt) < 0;
                        };
                    }
                }
 
                if (query.hasOwnProperty('$lt')) {
                    return function(key) {
                        return local.sortCompare(key, query.$lt) < 0;
                    };
                } else {
                    return function(key) {
                        return local.sortCompare(key, query.$lte) <= 0;
                    };
                }
            };
 
 
            // Append all elements in toAppend to array
            function append(array, toAppend) {
                var i;
 
                for (i = 0; i < toAppend.length; i += 1) {
                    array.push(toAppend[i]);
                }
            }
 
 
            /**
             * Get all data for a key between bounds
             * Return it in key order
             * @param {Object} query Mongo-style query where keys are $lt, $lte, $gt or $gte (other keys are not considered)
             * @param {Functions} lbm/ubm matching functions calculated at the first recursive step
             */
            BinarySearchTree.prototype.betweenBounds = function(query, lbm, ubm) {
                var res = [];
 
                if (!this.hasOwnProperty('key')) {
                    return [];
                } // Empty tree
 
                lbm = lbm || this.getLowerBoundMatcher(query);
                ubm = ubm || this.getUpperBoundMatcher(query);
 
                if (lbm(this.key) && this.left) {
                    append(res, this.left.betweenBounds(query, lbm, ubm));
                }
                if (lbm(this.key) && ubm(this.key)) {
                    append(res, this.data);
                }
                if (ubm(this.key) && this.right) {
                    append(res, this.right.betweenBounds(query, lbm, ubm));
                }
 
                return res;
            };
 
 
            /**
             * Delete the current node if it is a leaf
             * Return true if it was deleted
             */
            BinarySearchTree.prototype.deleteIfLeaf = function() {
                if (this.left || this.right) {
                    return false;
                }
 
                // The leaf is itself a root
                if (!this.parent) {
                    delete this.key;
                    this.data = [];
                    return true;
                }
 
                if (this.parent.left === this) {
                    this.parent.left = null;
                } else {
                    this.parent.right = null;
                }
 
                return true;
            };
 
 
            /**
             * Delete the current node if it has only one child
             * Return true if it was deleted
             */
            BinarySearchTree.prototype.deleteIfOnlyOneChild = function() {
                var child;
 
                if (this.left && !this.right) {
                    child = this.left;
                }
                if (!this.left && this.right) {
                    child = this.right;
                }
                if (!child) {
                    return false;
                }
 
                // Root
                if (!this.parent) {
                    this.key = child.key;
                    this.data = child.data;
 
                    this.left = null;
                    if (child.left) {
                        this.left = child.left;
                        child.left.parent = this;
                    }
 
                    this.right = null;
                    if (child.right) {
                        this.right = child.right;
                        child.right.parent = this;
                    }
 
                    return true;
                }
 
                if (this.parent.left === this) {
                    this.parent.left = child;
                    child.parent = this.parent;
                } else {
                    this.parent.right = child;
                    child.parent = this.parent;
                }
 
                return true;
            };
 
 
            /**
             * Delete a key or just a value
             * @param {Key} key
             * @param {Value} value Optional. If not set, the whole key is deleted. If set, only this value is deleted
             */
            BinarySearchTree.prototype.delete = function(key, value) {
                var newData = [],
                    replaceWith, self = this;
 
                if (!this.hasOwnProperty('key')) {
                    return;
                }
 
                if (local.sortCompare(key, this.key) < 0) {
                    if (this.left) {
                        this.left.delete(key, value);
                    }
                    return;
                }
 
                if (local.sortCompare(key, this.key) > 0) {
                    if (this.right) {
                        this.right.delete(key, value);
                    }
                    return;
                }
 
                if (!local.sortCompare(key, this.key) === 0) {
                    return;
                }
 
                // Delete only a value
                if (this.data.length > 1 && value !== undefined) {
                    this.data.forEach(function(d) {
                        if (d !== value) {
                            newData.push(d);
                        }
                    });
                    self.data = newData;
                    return;
                }
 
                // Delete the whole node
                if (this.deleteIfLeaf()) {
                    return;
                }
                if (this.deleteIfOnlyOneChild()) {
                    return;
                }
 
                // We are in the case where the node to delete has two children
                if (Math.random() >= 0.5) { // Randomize replacement to avoid unbalancing the tree too much
                    // Use the in-order predecessor
                    replaceWith = this.left.getMaxKeyDescendant();
 
                    this.key = replaceWith.key;
                    this.data = replaceWith.data;
 
                    if (this === replaceWith.parent) { // Special case
                        this.left = replaceWith.left;
                        if (replaceWith.left) {
                            replaceWith.left.parent = replaceWith.parent;
                        }
                    } else {
                        replaceWith.parent.right = replaceWith.left;
                        if (replaceWith.left) {
                            replaceWith.left.parent = replaceWith.parent;
                        }
                    }
                } else {
                    // Use the in-order successor
                    replaceWith = this.right.getMinKeyDescendant();
 
                    this.key = replaceWith.key;
                    this.data = replaceWith.data;
 
                    if (this === replaceWith.parent) { // Special case
                        this.right = replaceWith.right;
                        if (replaceWith.right) {
                            replaceWith.right.parent = replaceWith.parent;
                        }
                    } else {
                        replaceWith.parent.left = replaceWith.right;
                        if (replaceWith.right) {
                            replaceWith.right.parent = replaceWith.parent;
                        }
                    }
                }
            };
 
 
            /**
             * Execute a function on every node of the tree, in key order
             * @param {Function} fn Signature: node. Most useful will probably be node.key and node.data
             */
            BinarySearchTree.prototype.executeOnEveryNode = function(fn) {
                Iif (this.left) {
                    this.left.executeOnEveryNode(fn);
                }
                fn(this);
                if (this.right) {
                    this.right.executeOnEveryNode(fn);
                }
            };
 
 
            /**
             * Pretty print a tree
             * @param {Boolean} printData To print the nodes' data along with the key
             */
            BinarySearchTree.prototype.prettyPrint = function(printData, spacing) {
                spacing = spacing || '';
 
                console.log(spacing + "* " + this.key);
                if (printData) {
                    console.log(spacing + "* " + this.data);
                }
 
                if (!this.left && !this.right) {
                    return;
                }
 
                if (this.left) {
                    this.left.prettyPrint(printData, spacing + "  ");
                } else {
                    console.log(spacing + "  *");
                }
                if (this.right) {
                    this.right.prettyPrint(printData, spacing + "  ");
                } else {
                    console.log(spacing + "  *");
                }
            };
 
 
 
 
            // Interface
            module.exports = BinarySearchTree;
        }, {}]
    }, {}, [7])(7)
});
/* jslint-ignore-end */
 
 
 
    // run shared js-env code - post-init
    (function () {
        // init indexedDB store
        local.storeInit();
        // re-init local
        Object.keys(local).forEach(function (key) {
            local[key.replace((/.*\//), '')] = local[key];
        });
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - post-init
    case 'browser':
        // init exports
        local.global.Nedb = local.global.utility2_nedb = local;
        local.NODE_ENV = 'undefined';
        break;
 
 
 
    // run node js-env code - post-init
    case 'node':
        // require modules
        local.child_process = require('child_process');
        local.fs = require('fs');
        local.os = require('os');
        // init exports
        module.exports = module['./lib.nedb.js'] = local;
        local.__dirname = __dirname;
        local.NODE_ENV = process.env.NODE_ENV;
        break;
    }
}());