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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use strict";
/*!
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateDocumentReference = exports.validateQueryOperator = exports.validateQueryOrder = exports.AggregateQuerySnapshot = exports.AggregateQuery = exports.CollectionReference = exports.Query = exports.QueryOptions = exports.QuerySnapshot = exports.FieldOrder = exports.DocumentReference = void 0;
const stream_1 = require("stream");
const deepEqual = require("fast-deep-equal");
const document_1 = require("./document");
const document_change_1 = require("./document-change");
const logger_1 = require("./logger");
const order_1 = require("./order");
const path_1 = require("./path");
const serializer_1 = require("./serializer");
const timestamp_1 = require("./timestamp");
const types_1 = require("./types");
const util_1 = require("./util");
const validate_1 = require("./validate");
const write_batch_1 = require("./write-batch");
const filter_1 = require("./filter");
/**
 * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc'
 * (descending or ascending).
 *
 * @private
 * @internal
 */
const directionOperators = {
    asc: 'ASCENDING',
    desc: 'DESCENDING',
};
/**
 * Filter conditions in a `Query.where()` clause are specified using the
 * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', 'not-in',
 * and 'array-contains-any'.
 *
 * @private
 * @internal
 */
const comparisonOperators = {
    '<': 'LESS_THAN',
    '<=': 'LESS_THAN_OR_EQUAL',
    '==': 'EQUAL',
    '!=': 'NOT_EQUAL',
    '>': 'GREATER_THAN',
    '>=': 'GREATER_THAN_OR_EQUAL',
    'array-contains': 'ARRAY_CONTAINS',
    in: 'IN',
    'not-in': 'NOT_IN',
    'array-contains-any': 'ARRAY_CONTAINS_ANY',
};
const NOOP_MESSAGE = Symbol('a noop message');
/**
 * onSnapshot() callback that receives a QuerySnapshot.
 *
 * @callback querySnapshotCallback
 * @param {QuerySnapshot} snapshot A query snapshot.
 */
/**
 * onSnapshot() callback that receives a DocumentSnapshot.
 *
 * @callback documentSnapshotCallback
 * @param {DocumentSnapshot} snapshot A document snapshot.
 */
/**
 * onSnapshot() callback that receives an error.
 *
 * @callback errorCallback
 * @param {Error} err An error from a listen.
 */
/**
 * A DocumentReference refers to a document location in a Firestore database
 * and can be used to write, read, or listen to the location. The document at
 * the referenced location may or may not exist. A DocumentReference can
 * also be used to create a
 * [CollectionReference]{@link CollectionReference} to a
 * subcollection.
 *
 * @class DocumentReference
 */
class DocumentReference {
    /**
     * @private
     *
     * @private
     * @param _firestore The Firestore Database client.
     * @param _path The Path of this reference.
     * @param _converter The converter to use when serializing data.
     */
    constructor(_firestore, 
    /** @private */
    _path, 
    /** @private */
    _converter = (0, types_1.defaultConverter)()) {
        this._firestore = _firestore;
        this._path = _path;
        this._converter = _converter;
    }
    /**
     * The string representation of the DocumentReference's location.
     * @private
     * @internal
     * @type {string}
     * @name DocumentReference#formattedName
     */
    get formattedName() {
        const projectId = this.firestore.projectId;
        const databaseId = this.firestore.databaseId;
        return this._path.toQualifiedResourcePath(projectId, databaseId)
            .formattedName;
    }
    /**
     * The [Firestore]{@link Firestore} instance for the Firestore
     * database (useful for performing transactions, etc.).
     *
     * @type {Firestore}
     * @name DocumentReference#firestore
     * @readonly
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col');
     *
     * collectionRef.add({foo: 'bar'}).then(documentReference => {
     *   let firestore = documentReference.firestore;
     *   console.log(`Root location for document is ${firestore.formattedName}`);
     * });
     * ```
     */
    get firestore() {
        return this._firestore;
    }
    /**
     * A string representing the path of the referenced document (relative
     * to the root of the database).
     *
     * @type {string}
     * @name DocumentReference#path
     * @readonly
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col');
     *
     * collectionRef.add({foo: 'bar'}).then(documentReference => {
     *   console.log(`Added document at '${documentReference.path}'`);
     * });
     * ```
     */
    get path() {
        return this._path.relativeName;
    }
    /**
     * The last path element of the referenced document.
     *
     * @type {string}
     * @name DocumentReference#id
     * @readonly
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col');
     *
     * collectionRef.add({foo: 'bar'}).then(documentReference => {
     *   console.log(`Added document with name '${documentReference.id}'`);
     * });
     * ```
     */
    get id() {
        return this._path.id;
    }
    /**
     * Returns a resource path for this document.
     * @private
     * @internal
     */
    get _resourcePath() {
        return this._path;
    }
    /**
     * A reference to the collection to which this DocumentReference belongs.
     *
     * @name DocumentReference#parent
     * @type {CollectionReference}
     * @readonly
     *
     * @example
     * ```
     * let documentRef = firestore.doc('col/doc');
     * let collectionRef = documentRef.parent;
     *
     * collectionRef.where('foo', '==', 'bar').get().then(results => {
     *   console.log(`Found ${results.size} matches in parent collection`);
     * }):
     * ```
     */
    get parent() {
        return new CollectionReference(this._firestore, this._path.parent(), this._converter);
    }
    /**
     * Reads the document referred to by this DocumentReference.
     *
     * @returns {Promise.<DocumentSnapshot>} A Promise resolved with a
     * DocumentSnapshot for the retrieved document on success. For missing
     * documents, DocumentSnapshot.exists will be false. If the get() fails for
     * other reasons, the Promise will be rejected.
     *
     * @example
     * ```
     * let documentRef = firestore.doc('col/doc');
     *
     * documentRef.get().then(documentSnapshot => {
     *   if (documentSnapshot.exists) {
     *     console.log('Document retrieved successfully.');
     *   }
     * });
     * ```
     */
    get() {
        return this._firestore.getAll(this).then(([result]) => result);
    }
    /**
     * Gets a [CollectionReference]{@link CollectionReference} instance
     * that refers to the collection at the specified path.
     *
     * @param {string} collectionPath A slash-separated path to a collection.
     * @returns {CollectionReference} A reference to the new
     * subcollection.
     *
     * @example
     * ```
     * let documentRef = firestore.doc('col/doc');
     * let subcollection = documentRef.collection('subcollection');
     * console.log(`Path to subcollection: ${subcollection.path}`);
     * ```
     */
    collection(collectionPath) {
        (0, path_1.validateResourcePath)('collectionPath', collectionPath);
        const path = this._path.append(collectionPath);
        if (!path.isCollection) {
            throw new Error(`Value for argument "collectionPath" must point to a collection, but was "${collectionPath}". Your path does not contain an odd number of components.`);
        }
        return new CollectionReference(this._firestore, path);
    }
    /**
     * Fetches the subcollections that are direct children of this document.
     *
     * @returns {Promise.<Array.<CollectionReference>>} A Promise that resolves
     * with an array of CollectionReferences.
     *
     * @example
     * ```
     * let documentRef = firestore.doc('col/doc');
     *
     * documentRef.listCollections().then(collections => {
     *   for (let collection of collections) {
     *     console.log(`Found subcollection with id: ${collection.id}`);
     *   }
     * });
     * ```
     */
    listCollections() {
        const tag = (0, util_1.requestTag)();
        return this.firestore.initializeIfNeeded(tag).then(() => {
            const request = {
                parent: this.formattedName,
                // Setting `pageSize` to an arbitrarily large value lets the backend cap
                // the page size (currently to 300). Note that the backend rejects
                // MAX_INT32 (b/146883794).
                pageSize: Math.pow(2, 16) - 1,
            };
            return this._firestore
                .request('listCollectionIds', request, tag)
                .then(collectionIds => {
                const collections = [];
                // We can just sort this list using the default comparator since it
                // will only contain collection ids.
                collectionIds.sort();
                for (const collectionId of collectionIds) {
                    collections.push(this.collection(collectionId));
                }
                return collections;
            });
        });
    }
    /**
     * Create a document with the provided object values. This will fail the write
     * if a document exists at its location.
     *
     * @param {DocumentData} data An object that contains the fields and data to
     * serialize as the document.
     * @throws {Error} If the provided input is not a valid Firestore document.
     * @returns {Promise.<WriteResult>} A Promise that resolves with the
     * write time of this create.
     *
     * @example
     * ```
     * let documentRef = firestore.collection('col').doc();
     *
     * documentRef.create({foo: 'bar'}).then((res) => {
     *   console.log(`Document created at ${res.updateTime}`);
     * }).catch((err) => {
     *   console.log(`Failed to create document: ${err}`);
     * });
     * ```
     */
    create(data) {
        const writeBatch = new write_batch_1.WriteBatch(this._firestore);
        return writeBatch
            .create(this, data)
            .commit()
            .then(([writeResult]) => writeResult);
    }
    /**
     * Deletes the document referred to by this `DocumentReference`.
     *
     * A delete for a non-existing document is treated as a success (unless
     * lastUptimeTime is provided).
     *
     * @param {Precondition=} precondition A precondition to enforce for this
     * delete.
     * @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
     * document was last updated at lastUpdateTime. Fails the delete if the
     * document was last updated at a different time.
     * @param {boolean=} precondition.exists If set, enforces that the target
     * document must or must not exist.
     * @returns {Promise.<WriteResult>} A Promise that resolves with the
     * delete time.
     *
     * @example
     * ```
     * let documentRef = firestore.doc('col/doc');
     *
     * documentRef.delete().then(() => {
     *   console.log('Document successfully deleted.');
     * });
     * ```
     */
    delete(precondition) {
        const writeBatch = new write_batch_1.WriteBatch(this._firestore);
        return writeBatch
            .delete(this, precondition)
            .commit()
            .then(([writeResult]) => writeResult);
    }
    /**
     * Writes to the document referred to by this DocumentReference. If the
     * document does not yet exist, it will be created. If you pass
     * [SetOptions]{@link SetOptions}, the provided data can be merged into an
     * existing document.
     *
     * @param {T|Partial<T>} data A map of the fields and values for the document.
     * @param {SetOptions=} options An object to configure the set behavior.
     * @param {boolean=} options.merge If true, set() merges the values specified
     * in its data argument. Fields omitted from this set() call remain untouched.
     * If your input sets any field to an empty map, all nested fields are
     * overwritten.
     * @param {Array.<string|FieldPath>=} options.mergeFields If provided,
     * set() only replaces the specified field paths. Any field path that is not
     * specified is ignored and remains untouched. If your input sets any field to
     * an empty map, all nested fields are overwritten.
     * @throws {Error} If the provided input is not a valid Firestore document.
     * @returns {Promise.<WriteResult>} A Promise that resolves with the
     * write time of this set.
     *
     * @example
     * ```
     * let documentRef = firestore.doc('col/doc');
     *
     * documentRef.set({foo: 'bar'}).then(res => {
     *   console.log(`Document written at ${res.updateTime}`);
     * });
     * ```
     */
    set(data, options) {
        let writeBatch = new write_batch_1.WriteBatch(this._firestore);
        if (options) {
            writeBatch = writeBatch.set(this, data, options);
        }
        else {
            writeBatch = writeBatch.set(this, data);
        }
        return writeBatch.commit().then(([writeResult]) => writeResult);
    }
    /**
     * Updates fields in the document referred to by this DocumentReference.
     * If the document doesn't yet exist, the update fails and the returned
     * Promise will be rejected.
     *
     * The update() method accepts either an object with field paths encoded as
     * keys and field values encoded as values, or a variable number of arguments
     * that alternate between field paths and field values.
     *
     * A Precondition restricting this update can be specified as the last
     * argument.
     *
     * @param {UpdateData|string|FieldPath} dataOrField An object containing the
     * fields and values with which to update the document or the path of the
     * first field to update.
     * @param {
     * ...(*|string|FieldPath|Precondition)} preconditionOrValues An alternating
     * list of field paths and values to update or a Precondition to restrict
     * this update.
     * @throws {Error} If the provided input is not valid Firestore data.
     * @returns {Promise.<WriteResult>} A Promise that resolves once the
     * data has been successfully written to the backend.
     *
     * @example
     * ```
     * let documentRef = firestore.doc('col/doc');
     *
     * documentRef.update({foo: 'bar'}).then(res => {
     *   console.log(`Document updated at ${res.updateTime}`);
     * });
     * ```
     */
    update(dataOrField, ...preconditionOrValues) {
        // eslint-disable-next-line prefer-rest-params
        (0, validate_1.validateMinNumberOfArguments)('DocumentReference.update', arguments, 1);
        const writeBatch = new write_batch_1.WriteBatch(this._firestore);
        return writeBatch
            .update(this, dataOrField, ...preconditionOrValues)
            .commit()
            .then(([writeResult]) => writeResult);
    }
    /**
     * Attaches a listener for DocumentSnapshot events.
     *
     * @param {documentSnapshotCallback} onNext A callback to be called every
     * time a new `DocumentSnapshot` is available.
     * @param {errorCallback=} onError A callback to be called if the listen fails
     * or is cancelled. No further callbacks will occur. If unset, errors will be
     * logged to the console.
     *
     * @returns {function()} An unsubscribe function that can be called to cancel
     * the snapshot listener.
     *
     * @example
     * ```
     * let documentRef = firestore.doc('col/doc');
     *
     * let unsubscribe = documentRef.onSnapshot(documentSnapshot => {
     *   if (documentSnapshot.exists) {
     *     console.log(documentSnapshot.data());
     *   }
     * }, err => {
     *   console.log(`Encountered error: ${err}`);
     * });
     *
     * // Remove this listener.
     * unsubscribe();
     * ```
     */
    onSnapshot(onNext, onError) {
        (0, validate_1.validateFunction)('onNext', onNext);
        (0, validate_1.validateFunction)('onError', onError, { optional: true });
        const watch = new (require('./watch').DocumentWatch)(this.firestore, this);
        return watch.onSnapshot((readTime, size, docs) => {
            for (const document of docs()) {
                if (document.ref.path === this.path) {
                    onNext(document);
                    return;
                }
            }
            // The document is missing.
            const ref = new DocumentReference(this._firestore, this._path, this._converter);
            const document = new document_1.DocumentSnapshotBuilder(ref);
            document.readTime = readTime;
            onNext(document.build());
        }, onError || console.error);
    }
    /**
     * Returns true if this `DocumentReference` is equal to the provided value.
     *
     * @param {*} other The value to compare against.
     * @return {boolean} true if this `DocumentReference` is equal to the provided
     * value.
     */
    isEqual(other) {
        return (this === other ||
            (other instanceof DocumentReference &&
                this._firestore === other._firestore &&
                this._path.isEqual(other._path) &&
                this._converter === other._converter));
    }
    /**
     * Converts this DocumentReference to the Firestore Proto representation.
     *
     * @private
     * @internal
     */
    toProto() {
        return { referenceValue: this.formattedName };
    }
    /**
     * Applies a custom data converter to this DocumentReference, allowing you to
     * use your own custom model objects with Firestore. When you call set(),
     * get(), etc. on the returned DocumentReference instance, the provided
     * converter will convert between Firestore data and your custom type U.
     *
     * Using the converter allows you to specify generic type arguments when
     * storing and retrieving objects from Firestore.
     *
     * Passing in `null` as the converter parameter removes the current
     * converter.
     *
     * @example
     * ```
     * class Post {
     *   constructor(readonly title: string, readonly author: string) {}
     *
     *   toString(): string {
     *     return this.title + ', by ' + this.author;
     *   }
     * }
     *
     * const postConverter = {
     *   toFirestore(post: Post): FirebaseFirestore.DocumentData {
     *     return {title: post.title, author: post.author};
     *   },
     *   fromFirestore(
     *     snapshot: FirebaseFirestore.QueryDocumentSnapshot
     *   ): Post {
     *     const data = snapshot.data();
     *     return new Post(data.title, data.author);
     *   }
     * };
     *
     * const postSnap = await Firestore()
     *   .collection('posts')
     *   .withConverter(postConverter)
     *   .doc().get();
     * const post = postSnap.data();
     * if (post !== undefined) {
     *   post.title; // string
     *   post.toString(); // Should be defined
     *   post.someNonExistentProperty; // TS error
     * }
     *
     * ```
     * @param {FirestoreDataConverter | null} converter Converts objects to and
     * from Firestore. Passing in `null` removes the current converter.
     * @return A DocumentReference<U> that uses the provided converter.
     */
    withConverter(converter) {
        return new DocumentReference(this.firestore, this._path, converter !== null && converter !== void 0 ? converter : (0, types_1.defaultConverter)());
    }
}
exports.DocumentReference = DocumentReference;
/**
 * A Query order-by field.
 *
 * @private
 * @internal
 * @class
 */
class FieldOrder {
    /**
     * @param field The name of a document field (member) on which to order query
     * results.
     * @param direction One of 'ASCENDING' (default) or 'DESCENDING' to
     * set the ordering direction to ascending or descending, respectively.
     */
    constructor(field, direction = 'ASCENDING') {
        this.field = field;
        this.direction = direction;
    }
    /**
     * Generates the proto representation for this field order.
     * @private
     * @internal
     */
    toProto() {
        return {
            field: {
                fieldPath: this.field.formattedName,
            },
            direction: this.direction,
        };
    }
}
exports.FieldOrder = FieldOrder;
class FilterInternal {
}
class CompositeFilterInternal extends FilterInternal {
    constructor(filters, operator) {
        super();
        this.filters = filters;
        this.operator = operator;
        // Memoized list of all field filters that can be found by traversing the tree of filters
        // contained in this composite filter.
        this.memoizedFlattenedFilters = null;
    }
    getFilters() {
        return this.filters;
    }
    isConjunction() {
        return this.operator === 'AND';
    }
    getFlattenedFilters() {
        if (this.memoizedFlattenedFilters !== null) {
            return this.memoizedFlattenedFilters;
        }
        this.memoizedFlattenedFilters = this.filters.reduce((allFilters, subfilter) => allFilters.concat(subfilter.getFlattenedFilters()), []);
        return this.memoizedFlattenedFilters;
    }
    toProto() {
        if (this.filters.length === 1) {
            return this.filters[0].toProto();
        }
        const proto = {
            compositeFilter: {
                op: this.operator,
                filters: this.filters.map(filter => filter.toProto()),
            },
        };
        return proto;
    }
    isEqual(other) {
        if (other instanceof CompositeFilterInternal) {
            const otherFilters = other.getFilters();
            return (this.operator === other.operator &&
                this.getFilters().length === other.getFilters().length &&
                this.getFilters().every((filter, index) => filter.isEqual(otherFilters[index])));
        }
        else {
            return false;
        }
    }
}
/**
 * A field constraint for a Query where clause.
 *
 * @private
 * @internal
 * @class
 */
class FieldFilterInternal extends FilterInternal {
    /**
     * @param serializer The Firestore serializer
     * @param field The path of the property value to compare.
     * @param op A comparison operation.
     * @param value The value to which to compare the field for inclusion in a
     * query.
     */
    constructor(serializer, field, op, value) {
        super();
        this.serializer = serializer;
        this.field = field;
        this.op = op;
        this.value = value;
    }
    getFlattenedFilters() {
        return [this];
    }
    getFilters() {
        return [this];
    }
    /**
     * Returns whether this FieldFilter uses an equals comparison.
     *
     * @private
     * @internal
     */
    isInequalityFilter() {
        switch (this.op) {
            case 'GREATER_THAN':
            case 'GREATER_THAN_OR_EQUAL':
            case 'LESS_THAN':
            case 'LESS_THAN_OR_EQUAL':
            case 'NOT_EQUAL':
            case 'NOT_IN':
                return true;
            default:
                return false;
        }
    }
    /**
     * Generates the proto representation for this field filter.
     *
     * @private
     * @internal
     */
    toProto() {
        if (typeof this.value === 'number' && isNaN(this.value)) {
            return {
                unaryFilter: {
                    field: {
                        fieldPath: this.field.formattedName,
                    },
                    op: this.op === 'EQUAL' ? 'IS_NAN' : 'IS_NOT_NAN',
                },
            };
        }
        if (this.value === null) {
            return {
                unaryFilter: {
                    field: {
                        fieldPath: this.field.formattedName,
                    },
                    op: this.op === 'EQUAL' ? 'IS_NULL' : 'IS_NOT_NULL',
                },
            };
        }
        return {
            fieldFilter: {
                field: {
                    fieldPath: this.field.formattedName,
                },
                op: this.op,
                value: this.serializer.encodeValue(this.value),
            },
        };
    }
    isEqual(other) {
        return (other instanceof FieldFilterInternal &&
            this.field.isEqual(other.field) &&
            this.op === other.op &&
            deepEqual(this.value, other.value));
    }
}
/**
 * A QuerySnapshot contains zero or more
 * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} objects
 * representing the results of a query. The documents can be accessed as an
 * array via the [documents]{@link QuerySnapshot#documents} property
 * or enumerated using the [forEach]{@link QuerySnapshot#forEach}
 * method. The number of documents can be determined via the
 * [empty]{@link QuerySnapshot#empty} and
 * [size]{@link QuerySnapshot#size} properties.
 *
 * @class QuerySnapshot
 */
class QuerySnapshot {
    /**
     * @private
     *
     * @param _query The originating query.
     * @param _readTime The time when this query snapshot was obtained.
     * @param _size The number of documents in the result set.
     * @param docs A callback returning a sorted array of documents matching
     * this query
     * @param changes A callback returning a sorted array of document change
     * events for this snapshot.
     */
    constructor(_query, _readTime, _size, docs, changes) {
        this._query = _query;
        this._readTime = _readTime;
        this._size = _size;
        this._materializedDocs = null;
        this._materializedChanges = null;
        this._docs = null;
        this._changes = null;
        this._docs = docs;
        this._changes = changes;
    }
    /**
     * The query on which you called get() or onSnapshot() in order to get this
     * QuerySnapshot.
     *
     * @type {Query}
     * @name QuerySnapshot#query
     * @readonly
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '==', 'bar');
     *
     * query.limit(10).get().then(querySnapshot => {
     *   console.log(`Returned first batch of results`);
     *   let query = querySnapshot.query;
     *   return query.offset(10).get();
     * }).then(() => {
     *   console.log(`Returned second batch of results`);
     * });
     * ```
     */
    get query() {
        return this._query;
    }
    /**
     * An array of all the documents in this QuerySnapshot.
     *
     * @type {Array.<QueryDocumentSnapshot>}
     * @name QuerySnapshot#docs
     * @readonly
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '==', 'bar');
     *
     * query.get().then(querySnapshot => {
     *   let docs = querySnapshot.docs;
     *   for (let doc of docs) {
     *     console.log(`Document found at path: ${doc.ref.path}`);
     *   }
     * });
     * ```
     */
    get docs() {
        if (this._materializedDocs) {
            return this._materializedDocs;
        }
        this._materializedDocs = this._docs();
        this._docs = null;
        return this._materializedDocs;
    }
    /**
     * True if there are no documents in the QuerySnapshot.
     *
     * @type {boolean}
     * @name QuerySnapshot#empty
     * @readonly
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '==', 'bar');
     *
     * query.get().then(querySnapshot => {
     *   if (querySnapshot.empty) {
     *     console.log('No documents found.');
     *   }
     * });
     * ```
     */
    get empty() {
        return this._size === 0;
    }
    /**
     * The number of documents in the QuerySnapshot.
     *
     * @type {number}
     * @name QuerySnapshot#size
     * @readonly
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '==', 'bar');
     *
     * query.get().then(querySnapshot => {
     *   console.log(`Found ${querySnapshot.size} documents.`);
     * });
     * ```
     */
    get size() {
        return this._size;
    }
    /**
     * The time this query snapshot was obtained.
     *
     * @type {Timestamp}
     * @name QuerySnapshot#readTime
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '==', 'bar');
     *
     * query.get().then((querySnapshot) => {
     *   let readTime = querySnapshot.readTime;
     *   console.log(`Query results returned at '${readTime.toDate()}'`);
     * });
     * ```
     */
    get readTime() {
        return this._readTime;
    }
    /**
     * Returns an array of the documents changes since the last snapshot. If
     * this is the first snapshot, all documents will be in the list as added
     * changes.
     *
     * @return {Array.<DocumentChange>}
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '==', 'bar');
     *
     * query.onSnapshot(querySnapshot => {
     *   let changes = querySnapshot.docChanges();
     *   for (let change of changes) {
     *     console.log(`A document was ${change.type}.`);
     *   }
     * });
     * ```
     */
    docChanges() {
        if (this._materializedChanges) {
            return this._materializedChanges;
        }
        this._materializedChanges = this._changes();
        this._changes = null;
        return this._materializedChanges;
    }
    /**
     * Enumerates all of the documents in the QuerySnapshot. This is a convenience
     * method for running the same callback on each {@link QueryDocumentSnapshot}
     * that is returned.
     *
     * @param {function} callback A callback to be called with a
     * [QueryDocumentSnapshot]{@link QueryDocumentSnapshot} for each document in
     * the snapshot.
     * @param {*=} thisArg The `this` binding for the callback..
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '==', 'bar');
     *
     * query.get().then(querySnapshot => {
     *   querySnapshot.forEach(documentSnapshot => {
     *     console.log(`Document found at path: ${documentSnapshot.ref.path}`);
     *   });
     * });
     * ```
     */
    forEach(callback, thisArg) {
        (0, validate_1.validateFunction)('callback', callback);
        for (const doc of this.docs) {
            callback.call(thisArg, doc);
        }
    }
    /**
     * Returns true if the document data in this `QuerySnapshot` is equal to the
     * provided value.
     *
     * @param {*} other The value to compare against.
     * @return {boolean} true if this `QuerySnapshot` is equal to the provided
     * value.
     */
    isEqual(other) {
        // Since the read time is different on every query read, we explicitly
        // ignore all metadata in this comparison.
        if (this === other) {
            return true;
        }
        if (!(other instanceof QuerySnapshot)) {
            return false;
        }
        if (this._size !== other._size) {
            return false;
        }
        if (!this._query.isEqual(other._query)) {
            return false;
        }
        if (this._materializedDocs && !this._materializedChanges) {
            // If we have only materialized the documents, we compare them first.
            return (isArrayEqual(this.docs, other.docs) &&
                isArrayEqual(this.docChanges(), other.docChanges()));
        }
        // Otherwise, we compare the changes first as we expect there to be fewer.
        return (isArrayEqual(this.docChanges(), other.docChanges()) &&
            isArrayEqual(this.docs, other.docs));
    }
}
exports.QuerySnapshot = QuerySnapshot;
/*!
 * Denotes whether a provided limit is applied to the beginning or the end of
 * the result set.
 */
var LimitType;
(function (LimitType) {
    LimitType[LimitType["First"] = 0] = "First";
    LimitType[LimitType["Last"] = 1] = "Last";
})(LimitType || (LimitType = {}));
/**
 * Internal class representing custom Query options.
 *
 * These options are immutable. Modified options can be created using `with()`.
 * @private
 * @internal
 */
class QueryOptions {
    constructor(parentPath, collectionId, converter, allDescendants, filters, fieldOrders, startAt, endAt, limit, limitType, offset, projection, 
    // Whether to select all documents under `parentPath`. By default, only
    // collections that match `collectionId` are selected.
    kindless = false, 
    // Whether to require consistent documents when restarting the query. By
    // default, restarting the query uses the readTime offset of the original
    // query to provide consistent results.
    requireConsistency = true) {
        this.parentPath = parentPath;
        this.collectionId = collectionId;
        this.converter = converter;
        this.allDescendants = allDescendants;
        this.filters = filters;
        this.fieldOrders = fieldOrders;
        this.startAt = startAt;
        this.endAt = endAt;
        this.limit = limit;
        this.limitType = limitType;
        this.offset = offset;
        this.projection = projection;
        this.kindless = kindless;
        this.requireConsistency = requireConsistency;
    }
    /**
     * Returns query options for a collection group query.
     * @private
     * @internal
     */
    static forCollectionGroupQuery(collectionId, converter = (0, types_1.defaultConverter)()) {
        return new QueryOptions(
        /*parentPath=*/ path_1.ResourcePath.EMPTY, collectionId, converter, 
        /*allDescendants=*/ true, 
        /*fieldFilters=*/ [], 
        /*fieldOrders=*/ []);
    }
    /**
     * Returns query options for a single-collection query.
     * @private
     * @internal
     */
    static forCollectionQuery(collectionRef, converter = (0, types_1.defaultConverter)()) {
        return new QueryOptions(collectionRef.parent(), collectionRef.id, converter, 
        /*allDescendants=*/ false, 
        /*fieldFilters=*/ [], 
        /*fieldOrders=*/ []);
    }
    /**
     * Returns query options for a query that fetches all descendants under the
     * specified reference.
     *
     * @private
     * @internal
     */
    static forKindlessAllDescendants(parent, id, requireConsistency = true) {
        let options = new QueryOptions(parent, id, (0, types_1.defaultConverter)(), 
        /*allDescendants=*/ true, 
        /*fieldFilters=*/ [], 
        /*fieldOrders=*/ []);
        options = options.with({
            kindless: true,
            requireConsistency,
        });
        return options;
    }
    /**
     * Returns the union of the current and the provided options.
     * @private
     * @internal
     */
    with(settings) {
        return new QueryOptions(coalesce(settings.parentPath, this.parentPath), coalesce(settings.collectionId, this.collectionId), this.converter, coalesce(settings.allDescendants, this.allDescendants), coalesce(settings.filters, this.filters), coalesce(settings.fieldOrders, this.fieldOrders), coalesce(settings.startAt, this.startAt), coalesce(settings.endAt, this.endAt), coalesce(settings.limit, this.limit), coalesce(settings.limitType, this.limitType), coalesce(settings.offset, this.offset), coalesce(settings.projection, this.projection), coalesce(settings.kindless, this.kindless), coalesce(settings.requireConsistency, this.requireConsistency));
    }
    withConverter(converter) {
        return new QueryOptions(this.parentPath, this.collectionId, converter, this.allDescendants, this.filters, this.fieldOrders, this.startAt, this.endAt, this.limit, this.limitType, this.offset, this.projection);
    }
    hasFieldOrders() {
        return this.fieldOrders.length > 0;
    }
    isEqual(other) {
        if (this === other) {
            return true;
        }
        return (other instanceof QueryOptions &&
            this.parentPath.isEqual(other.parentPath) &&
            this.filtersEqual(other.filters) &&
            this.collectionId === other.collectionId &&
            this.converter === other.converter &&
            this.allDescendants === other.allDescendants &&
            this.limit === other.limit &&
            this.offset === other.offset &&
            deepEqual(this.fieldOrders, other.fieldOrders) &&
            deepEqual(this.startAt, other.startAt) &&
            deepEqual(this.endAt, other.endAt) &&
            deepEqual(this.projection, other.projection) &&
            this.kindless === other.kindless &&
            this.requireConsistency === other.requireConsistency);
    }
    filtersEqual(other) {
        if (this.filters.length !== other.length) {
            return false;
        }
        for (let i = 0; i < other.length; i++) {
            if (!this.filters[i].isEqual(other[i])) {
                return false;
            }
        }
        return true;
    }
}
exports.QueryOptions = QueryOptions;
/**
 * A Query refers to a query which you can read or stream from. You can also
 * construct refined Query objects by adding filters and ordering.
 *
 * @class Query
 */
class Query {
    /**
     * @private
     *
     * @param _firestore The Firestore Database client.
     * @param _queryOptions Options that define the query.
     */
    constructor(
    /** @private */
    _firestore, 
    /** @private */
    _queryOptions) {
        this._firestore = _firestore;
        this._queryOptions = _queryOptions;
        this._serializer = new serializer_1.Serializer(_firestore);
        this._allowUndefined =
            !!this._firestore._settings.ignoreUndefinedProperties;
    }
    /**
     * Extracts field values from the DocumentSnapshot based on the provided
     * field order.
     *
     * @private
     * @internal
     * @param documentSnapshot The document to extract the fields from.
     * @param fieldOrders The field order that defines what fields we should
     * extract.
     * @return {Array.<*>} The field values to use.
     * @private
     * @internal
     */
    static _extractFieldValues(documentSnapshot, fieldOrders) {
        const fieldValues = [];
        for (const fieldOrder of fieldOrders) {
            if (path_1.FieldPath.documentId().isEqual(fieldOrder.field)) {
                fieldValues.push(documentSnapshot.ref);
            }
            else {
                const fieldValue = documentSnapshot.get(fieldOrder.field);
                if (fieldValue === undefined) {
                    throw new Error(`Field "${fieldOrder.field}" is missing in the provided DocumentSnapshot. ` +
                        'Please provide a document that contains values for all specified ' +
                        'orderBy() and where() constraints.');
                }
                else {
                    fieldValues.push(fieldValue);
                }
            }
        }
        return fieldValues;
    }
    /**
     * The [Firestore]{@link Firestore} instance for the Firestore
     * database (useful for performing transactions, etc.).
     *
     * @type {Firestore}
     * @name Query#firestore
     * @readonly
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col');
     *
     * collectionRef.add({foo: 'bar'}).then(documentReference => {
     *   let firestore = documentReference.firestore;
     *   console.log(`Root location for document is ${firestore.formattedName}`);
     * });
     * ```
     */
    get firestore() {
        return this._firestore;
    }
    where(fieldPathOrFilter, opStr, value) {
        let filter;
        if (fieldPathOrFilter instanceof filter_1.Filter) {
            filter = fieldPathOrFilter;
        }
        else {
            filter = filter_1.Filter.where(fieldPathOrFilter, opStr, value);
        }
        if (this._queryOptions.startAt || this._queryOptions.endAt) {
            throw new Error('Cannot specify a where() filter after calling startAt(), ' +
                'startAfter(), endBefore() or endAt().');
        }
        const parsedFilter = this._parseFilter(filter);
        if (parsedFilter.getFilters().length === 0) {
            // Return the existing query if not adding any more filters (e.g. an empty composite filter).
            return this;
        }
        const options = this._queryOptions.with({
            filters: this._queryOptions.filters.concat(parsedFilter),
        });
        return new Query(this._firestore, options);
    }
    _parseFilter(filter) {
        if (filter instanceof filter_1.UnaryFilter) {
            return this._parseFieldFilter(filter);
        }
        return this._parseCompositeFilter(filter);
    }
    _parseFieldFilter(fieldFilterData) {
        let value = fieldFilterData._getValue();
        let operator = fieldFilterData._getOperator();
        const fieldPath = fieldFilterData._getField();
        (0, path_1.validateFieldPath)('fieldPath', fieldPath);
        operator = validateQueryOperator('opStr', operator, value);
        validateQueryValue('value', value, this._allowUndefined);
        const path = path_1.FieldPath.fromArgument(fieldPath);
        if (path_1.FieldPath.documentId().isEqual(path)) {
            if (operator === 'array-contains' || operator === 'array-contains-any') {
                throw new Error(`Invalid Query. You can't perform '${operator}' ` +
                    'queries on FieldPath.documentId().');
            }
            else if (operator === 'in' || operator === 'not-in') {
                if (!Array.isArray(value) || value.length === 0) {
                    throw new Error(`Invalid Query. A non-empty array is required for '${operator}' filters.`);
                }
                value = value.map(el => this.validateReference(el));
            }
            else {
                value = this.validateReference(value);
            }
        }
        return new FieldFilterInternal(this._serializer, path, comparisonOperators[operator], value);
    }
    _parseCompositeFilter(compositeFilterData) {
        const parsedFilters = compositeFilterData
            ._getFilters()
            .map(filter => this._parseFilter(filter))
            .filter(parsedFilter => parsedFilter.getFilters().length > 0);
        // For composite filters containing 1 filter, return the only filter.
        // For example: AND(FieldFilter1) == FieldFilter1
        if (parsedFilters.length === 1) {
            return parsedFilters[0];
        }
        return new CompositeFilterInternal(parsedFilters, compositeFilterData._getOperator() === 'AND' ? 'AND' : 'OR');
    }
    /**
     * Creates and returns a new [Query]{@link Query} instance that applies a
     * field mask to the result and returns only the specified subset of fields.
     * You can specify a list of field paths to return, or use an empty list to
     * only return the references of matching documents.
     *
     * Queries that contain field masks cannot be listened to via `onSnapshot()`
     * listeners.
     *
     * This function returns a new (immutable) instance of the Query (rather than
     * modify the existing instance) to impose the field mask.
     *
     * @param {...(string|FieldPath)} fieldPaths The field paths to return.
     * @returns {Query} The created Query.
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col');
     * let documentRef = collectionRef.doc('doc');
     *
     * return documentRef.set({x:10, y:5}).then(() => {
     *   return collectionRef.where('x', '>', 5).select('y').get();
     * }).then((res) => {
     *   console.log(`y is ${res.docs[0].get('y')}.`);
     * });
     * ```
     */
    select(...fieldPaths) {
        const fields = [];
        if (fieldPaths.length === 0) {
            fields.push({ fieldPath: path_1.FieldPath.documentId().formattedName });
        }
        else {
            for (let i = 0; i < fieldPaths.length; ++i) {
                (0, path_1.validateFieldPath)(i, fieldPaths[i]);
                fields.push({
                    fieldPath: path_1.FieldPath.fromArgument(fieldPaths[i]).formattedName,
                });
            }
        }
        // By specifying a field mask, the query result no longer conforms to type
        // `T`. We there return `Query<DocumentData>`;
        const options = this._queryOptions.with({
            projection: { fields },
        });
        return new Query(this._firestore, options);
    }
    /**
     * Creates and returns a new [Query]{@link Query} that's additionally sorted
     * by the specified field, optionally in descending order instead of
     * ascending.
     *
     * This function returns a new (immutable) instance of the Query (rather than
     * modify the existing instance) to impose the field mask.
     *
     * @param {string|FieldPath} fieldPath The field to sort by.
     * @param {string=} directionStr Optional direction to sort by ('asc' or
     * 'desc'). If not specified, order will be ascending.
     * @returns {Query} The created Query.
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '>', 42);
     *
     * query.orderBy('foo', 'desc').get().then(querySnapshot => {
     *   querySnapshot.forEach(documentSnapshot => {
     *     console.log(`Found document at ${documentSnapshot.ref.path}`);
     *   });
     * });
     * ```
     */
    orderBy(fieldPath, directionStr) {
        (0, path_1.validateFieldPath)('fieldPath', fieldPath);
        directionStr = validateQueryOrder('directionStr', directionStr);
        if (this._queryOptions.startAt || this._queryOptions.endAt) {
            throw new Error('Cannot specify an orderBy() constraint after calling ' +
                'startAt(), startAfter(), endBefore() or endAt().');
        }
        const newOrder = new FieldOrder(path_1.FieldPath.fromArgument(fieldPath), directionOperators[directionStr || 'asc']);
        const options = this._queryOptions.with({
            fieldOrders: this._queryOptions.fieldOrders.concat(newOrder),
        });
        return new Query(this._firestore, options);
    }
    /**
     * Creates and returns a new [Query]{@link Query} that only returns the
     * first matching documents.
     *
     * This function returns a new (immutable) instance of the Query (rather than
     * modify the existing instance) to impose the limit.
     *
     * @param {number} limit The maximum number of items to return.
     * @returns {Query} The created Query.
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '>', 42);
     *
     * query.limit(1).get().then(querySnapshot => {
     *   querySnapshot.forEach(documentSnapshot => {
     *     console.log(`Found document at ${documentSnapshot.ref.path}`);
     *   });
     * });
     * ```
     */
    limit(limit) {
        (0, validate_1.validateInteger)('limit', limit);
        const options = this._queryOptions.with({
            limit,
            limitType: LimitType.First,
        });
        return new Query(this._firestore, options);
    }
    /**
     * Creates and returns a new [Query]{@link Query} that only returns the
     * last matching documents.
     *
     * You must specify at least one orderBy clause for limitToLast queries,
     * otherwise an exception will be thrown during execution.
     *
     * Results for limitToLast queries cannot be streamed via the `stream()` API.
     *
     * @param limit The maximum number of items to return.
     * @return The created Query.
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '>', 42);
     *
     * query.limitToLast(1).get().then(querySnapshot => {
     *   querySnapshot.forEach(documentSnapshot => {
     *     console.log(`Last matching document is ${documentSnapshot.ref.path}`);
     *   });
     * });
     * ```
     */
    limitToLast(limit) {
        (0, validate_1.validateInteger)('limitToLast', limit);
        const options = this._queryOptions.with({ limit, limitType: LimitType.Last });
        return new Query(this._firestore, options);
    }
    /**
     * Specifies the offset of the returned results.
     *
     * This function returns a new (immutable) instance of the
     * [Query]{@link Query} (rather than modify the existing instance)
     * to impose the offset.
     *
     * @param {number} offset The offset to apply to the Query results
     * @returns {Query} The created Query.
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '>', 42);
     *
     * query.limit(10).offset(20).get().then(querySnapshot => {
     *   querySnapshot.forEach(documentSnapshot => {
     *     console.log(`Found document at ${documentSnapshot.ref.path}`);
     *   });
     * });
     * ```
     */
    offset(offset) {
        (0, validate_1.validateInteger)('offset', offset);
        const options = this._queryOptions.with({ offset });
        return new Query(this._firestore, options);
    }
    /**
     * Returns a query that counts the documents in the result set of this
     * query.
     *
     * The returned query, when executed, counts the documents in the result set
     * of this query without actually downloading the documents.
     *
     * Using the returned query to count the documents is efficient because only
     * the final count, not the documents' data, is downloaded. The returned
     * query can even count the documents if the result set would be
     * prohibitively large to download entirely (e.g. thousands of documents).
     *
     * @return a query that counts the documents in the result set of this
     * query. The count can be retrieved from `snapshot.data().count`, where
     * `snapshot` is the `AggregateQuerySnapshot` resulting from running the
     * returned query.
     */
    count() {
        return new AggregateQuery(this, { count: {} });
    }
    /**
     * Returns true if this `Query` is equal to the provided value.
     *
     * @param {*} other The value to compare against.
     * @return {boolean} true if this `Query` is equal to the provided value.
     */
    isEqual(other) {
        if (this === other) {
            return true;
        }
        return (other instanceof Query && this._queryOptions.isEqual(other._queryOptions));
    }
    /**
     * Returns the sorted array of inequality filter fields used in this query.
     *
     * @return An array of inequality filter fields sorted lexicographically by FieldPath.
     */
    getInequalityFilterFields() {
        const inequalityFields = [];
        for (const filter of this._queryOptions.filters) {
            for (const subFilter of filter.getFlattenedFilters()) {
                if (subFilter.isInequalityFilter()) {
                    inequalityFields.push(subFilter.field);
                }
            }
        }
        return inequalityFields.sort((a, b) => a.compareTo(b));
    }
    /**
     * Computes the backend ordering semantics for DocumentSnapshot cursors.
     *
     * @private
     * @internal
     * @param cursorValuesOrDocumentSnapshot The snapshot of the document or the
     * set of field values to use as the boundary.
     * @returns The implicit ordering semantics.
     */
    createImplicitOrderBy(cursorValuesOrDocumentSnapshot) {
        // Add an implicit orderBy if the only cursor value is a DocumentSnapshot
        // or a DocumentReference.
        if (cursorValuesOrDocumentSnapshot.length !== 1 ||
            !(cursorValuesOrDocumentSnapshot[0] instanceof document_1.DocumentSnapshot ||
                cursorValuesOrDocumentSnapshot[0] instanceof DocumentReference)) {
            return this._queryOptions.fieldOrders;
        }
        // TODO(b/296435819): Remove this warning message.
        if (cursorValuesOrDocumentSnapshot[0] instanceof DocumentReference) {
            // eslint-disable-next-line no-console
            console.warn(`Warning: Passing DocumentReference into a cursor without orderBy clause is not an intended
        behavior. Please use DocumentSnapshot or add an explicit orderBy on document key field.`);
        }
        const fieldOrders = this._queryOptions.fieldOrders.slice();
        const fieldsNormalized = new Set([
            ...fieldOrders.map(item => item.field.toString()),
        ]);
        /** The order of the implicit ordering always matches the last explicit order by. */
        const lastDirection = fieldOrders.length === 0
            ? directionOperators.ASC
            : fieldOrders[fieldOrders.length - 1].direction;
        /**
         * Any inequality fields not explicitly ordered should be implicitly ordered in a
         * lexicographical order. When there are multiple inequality filters on the same field, the
         * field should be added only once.
         * Note: getInequalityFilterFields function sorts the key field before
         * other fields. However, we want the key field to be sorted last.
         */
        const inequalityFields = this.getInequalityFilterFields();
        for (const field of inequalityFields) {
            if (!fieldsNormalized.has(field.toString()) &&
                !field.isEqual(path_1.FieldPath.documentId())) {
                fieldOrders.push(new FieldOrder(field, lastDirection));
                fieldsNormalized.add(field.toString());
            }
        }
        // Add the document key field to the last if it is not explicitly ordered.
        if (!fieldsNormalized.has(path_1.FieldPath.documentId().toString())) {
            fieldOrders.push(new FieldOrder(path_1.FieldPath.documentId(), lastDirection));
        }
        return fieldOrders;
    }
    /**
     * Builds a Firestore 'Position' proto message.
     *
     * @private
     * @internal
     * @param {Array.<FieldOrder>} fieldOrders The field orders to use for this
     * cursor.
     * @param {Array.<DocumentSnapshot|*>} cursorValuesOrDocumentSnapshot The
     * snapshot of the document or the set of field values to use as the boundary.
     * @param before Whether the query boundary lies just before or after the
     * provided data.
     * @returns {Object} The proto message.
     */
    createCursor(fieldOrders, cursorValuesOrDocumentSnapshot, before) {
        let fieldValues;
        if (cursorValuesOrDocumentSnapshot.length === 1 &&
            cursorValuesOrDocumentSnapshot[0] instanceof document_1.DocumentSnapshot) {
            fieldValues = Query._extractFieldValues(cursorValuesOrDocumentSnapshot[0], fieldOrders);
        }
        else {
            fieldValues = cursorValuesOrDocumentSnapshot;
        }
        if (fieldValues.length > fieldOrders.length) {
            throw new Error('Too many cursor values specified. The specified ' +
                'values must match the orderBy() constraints of the query.');
        }
        const options = { values: [], before };
        for (let i = 0; i < fieldValues.length; ++i) {
            let fieldValue = fieldValues[i];
            if (path_1.FieldPath.documentId().isEqual(fieldOrders[i].field)) {
                fieldValue = this.validateReference(fieldValue);
            }
            validateQueryValue(i, fieldValue, this._allowUndefined);
            options.values.push(this._serializer.encodeValue(fieldValue));
        }
        return options;
    }
    /**
     * Validates that a value used with FieldValue.documentId() is either a
     * string or a DocumentReference that is part of the query`s result set.
     * Throws a validation error or returns a DocumentReference that can
     * directly be used in the Query.
     *
     * @param val The value to validate.
     * @throws If the value cannot be used for this query.
     * @return If valid, returns a DocumentReference that can be used with the
     * query.
     * @private
     * @internal
     */
    validateReference(val) {
        const basePath = this._queryOptions.allDescendants
            ? this._queryOptions.parentPath
            : this._queryOptions.parentPath.append(this._queryOptions.collectionId);
        let reference;
        if (typeof val === 'string') {
            const path = basePath.append(val);
            if (this._queryOptions.allDescendants) {
                if (!path.isDocument) {
                    throw new Error('When querying a collection group and ordering by ' +
                        'FieldPath.documentId(), the corresponding value must result in ' +
                        `a valid document path, but '${val}' is not because it ` +
                        'contains an odd number of segments.');
                }
            }
            else if (val.indexOf('/') !== -1) {
                throw new Error('When querying a collection and ordering by FieldPath.documentId(), ' +
                    `the corresponding value must be a plain document ID, but '${val}' ` +
                    'contains a slash.');
            }
            reference = new DocumentReference(this._firestore, basePath.append(val), this._queryOptions.converter);
        }
        else if (val instanceof DocumentReference) {
            reference = val;
            if (!basePath.isPrefixOf(reference._path)) {
                throw new Error(`"${reference.path}" is not part of the query result set and ` +
                    'cannot be used as a query boundary.');
            }
        }
        else {
            throw new Error('The corresponding value for FieldPath.documentId() must be a ' +
                `string or a DocumentReference, but was "${val}".`);
        }
        if (!this._queryOptions.allDescendants &&
            reference._path.parent().compareTo(basePath) !== 0) {
            throw new Error('Only a direct child can be used as a query boundary. ' +
                `Found: "${reference.path}".`);
        }
        return reference;
    }
    /**
     * Creates and returns a new [Query]{@link Query} that starts at the provided
     * set of field values relative to the order of the query. The order of the
     * provided values must match the order of the order by clauses of the query.
     *
     * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot
     * of the document the query results should start at or the field values to
     * start this query at, in order of the query's order by.
     * @returns {Query} A query with the new starting point.
     *
     * @example
     * ```
     * let query = firestore.collection('col');
     *
     * query.orderBy('foo').startAt(42).get().then(querySnapshot => {
     *   querySnapshot.forEach(documentSnapshot => {
     *     console.log(`Found document at ${documentSnapshot.ref.path}`);
     *   });
     * });
     * ```
     */
    startAt(...fieldValuesOrDocumentSnapshot) {
        (0, validate_1.validateMinNumberOfArguments)('Query.startAt', fieldValuesOrDocumentSnapshot, 1);
        const fieldOrders = this.createImplicitOrderBy(fieldValuesOrDocumentSnapshot);
        const startAt = this.createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, true);
        const options = this._queryOptions.with({ fieldOrders, startAt });
        return new Query(this._firestore, options);
    }
    /**
     * Creates and returns a new [Query]{@link Query} that starts after the
     * provided set of field values relative to the order of the query. The order
     * of the provided values must match the order of the order by clauses of the
     * query.
     *
     * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot
     * of the document the query results should start after or the field values to
     * start this query after, in order of the query's order by.
     * @returns {Query} A query with the new starting point.
     *
     * @example
     * ```
     * let query = firestore.collection('col');
     *
     * query.orderBy('foo').startAfter(42).get().then(querySnapshot => {
     *   querySnapshot.forEach(documentSnapshot => {
     *     console.log(`Found document at ${documentSnapshot.ref.path}`);
     *   });
     * });
     * ```
     */
    startAfter(...fieldValuesOrDocumentSnapshot) {
        (0, validate_1.validateMinNumberOfArguments)('Query.startAfter', fieldValuesOrDocumentSnapshot, 1);
        const fieldOrders = this.createImplicitOrderBy(fieldValuesOrDocumentSnapshot);
        const startAt = this.createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, false);
        const options = this._queryOptions.with({ fieldOrders, startAt });
        return new Query(this._firestore, options);
    }
    /**
     * Creates and returns a new [Query]{@link Query} that ends before the set of
     * field values relative to the order of the query. The order of the provided
     * values must match the order of the order by clauses of the query.
     *
     * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot
     * of the document the query results should end before or the field values to
     * end this query before, in order of the query's order by.
     * @returns {Query} A query with the new ending point.
     *
     * @example
     * ```
     * let query = firestore.collection('col');
     *
     * query.orderBy('foo').endBefore(42).get().then(querySnapshot => {
     *   querySnapshot.forEach(documentSnapshot => {
     *     console.log(`Found document at ${documentSnapshot.ref.path}`);
     *   });
     * });
     * ```
     */
    endBefore(...fieldValuesOrDocumentSnapshot) {
        (0, validate_1.validateMinNumberOfArguments)('Query.endBefore', fieldValuesOrDocumentSnapshot, 1);
        const fieldOrders = this.createImplicitOrderBy(fieldValuesOrDocumentSnapshot);
        const endAt = this.createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, true);
        const options = this._queryOptions.with({ fieldOrders, endAt });
        return new Query(this._firestore, options);
    }
    /**
     * Creates and returns a new [Query]{@link Query} that ends at the provided
     * set of field values relative to the order of the query. The order of the
     * provided values must match the order of the order by clauses of the query.
     *
     * @param {...*|DocumentSnapshot} fieldValuesOrDocumentSnapshot The snapshot
     * of the document the query results should end at or the field values to end
     * this query at, in order of the query's order by.
     * @returns {Query} A query with the new ending point.
     *
     * @example
     * ```
     * let query = firestore.collection('col');
     *
     * query.orderBy('foo').endAt(42).get().then(querySnapshot => {
     *   querySnapshot.forEach(documentSnapshot => {
     *     console.log(`Found document at ${documentSnapshot.ref.path}`);
     *   });
     * });
     * ```
     */
    endAt(...fieldValuesOrDocumentSnapshot) {
        (0, validate_1.validateMinNumberOfArguments)('Query.endAt', fieldValuesOrDocumentSnapshot, 1);
        const fieldOrders = this.createImplicitOrderBy(fieldValuesOrDocumentSnapshot);
        const endAt = this.createCursor(fieldOrders, fieldValuesOrDocumentSnapshot, false);
        const options = this._queryOptions.with({ fieldOrders, endAt });
        return new Query(this._firestore, options);
    }
    /**
     * Executes the query and returns the results as a
     * [QuerySnapshot]{@link QuerySnapshot}.
     *
     * @returns {Promise.<QuerySnapshot>} A Promise that resolves with the results
     * of the Query.
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '==', 'bar');
     *
     * query.get().then(querySnapshot => {
     *   querySnapshot.forEach(documentSnapshot => {
     *     console.log(`Found document at ${documentSnapshot.ref.path}`);
     *   });
     * });
     * ```
     */
    get() {
        return this._get();
    }
    /**
     * Internal get() method that accepts an optional transaction id.
     *
     * @private
     * @internal
     * @param {bytes=} transactionId A transaction ID.
     */
    _get(transactionId) {
        const docs = [];
        // Capture the error stack to preserve stack tracing across async calls.
        const stack = Error().stack;
        return new Promise((resolve, reject) => {
            let readTime;
            this._stream(transactionId)
                .on('error', err => {
                reject((0, util_1.wrapError)(err, stack));
            })
                .on('data', result => {
                readTime = result.readTime;
                if (result.document) {
                    docs.push(result.document);
                }
            })
                .on('end', () => {
                if (this._queryOptions.limitType === LimitType.Last) {
                    // The results for limitToLast queries need to be flipped since
                    // we reversed the ordering constraints before sending the query
                    // to the backend.
                    docs.reverse();
                }
                resolve(new QuerySnapshot(this, readTime, docs.length, () => docs, () => {
                    const changes = [];
                    for (let i = 0; i < docs.length; ++i) {
                        changes.push(new document_change_1.DocumentChange('added', docs[i], -1, i));
                    }
                    return changes;
                }));
            });
        });
    }
    /**
     * Executes the query and streams the results as
     * [QueryDocumentSnapshots]{@link QueryDocumentSnapshot}.
     *
     * @returns {Stream.<QueryDocumentSnapshot>} A stream of
     * QueryDocumentSnapshots.
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '==', 'bar');
     *
     * let count = 0;
     *
     * query.stream().on('data', (documentSnapshot) => {
     *   console.log(`Found document with name '${documentSnapshot.id}'`);
     *   ++count;
     * }).on('end', () => {
     *   console.log(`Total count is ${count}`);
     * });
     * ```
     */
    stream() {
        if (this._queryOptions.limitType === LimitType.Last) {
            throw new Error('Query results for queries that include limitToLast() ' +
                'constraints cannot be streamed. Use Query.get() instead.');
        }
        const responseStream = this._stream();
        const transform = new stream_1.Transform({
            objectMode: true,
            transform(chunk, encoding, callback) {
                callback(undefined, chunk.document);
            },
        });
        responseStream.pipe(transform);
        responseStream.on('error', e => transform.destroy(e));
        return transform;
    }
    /**
     * Converts a QueryCursor to its proto representation.
     *
     * @param cursor The original cursor value
     * @private
     * @internal
     */
    toCursor(cursor) {
        if (cursor) {
            return cursor.before
                ? { before: true, values: cursor.values }
                : { values: cursor.values };
        }
        return undefined;
    }
    /**
     * Internal method for serializing a query to its RunQuery proto
     * representation with an optional transaction id or read time.
     *
     * @param transactionIdOrReadTime A transaction ID or the read time at which
     * to execute the query.
     * @private
     * @internal
     * @returns Serialized JSON for the query.
     */
    toProto(transactionIdOrReadTime) {
        const projectId = this.firestore.projectId;
        const databaseId = this.firestore.databaseId;
        const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(projectId, databaseId);
        const structuredQuery = this.toStructuredQuery();
        // For limitToLast queries, the structured query has to be translated to a version with
        // reversed ordered, and flipped startAt/endAt to work properly.
        if (this._queryOptions.limitType === LimitType.Last) {
            if (!this._queryOptions.hasFieldOrders()) {
                throw new Error('limitToLast() queries require specifying at least one orderBy() clause.');
            }
            structuredQuery.orderBy = this._queryOptions.fieldOrders.map(order => {
                // Flip the orderBy directions since we want the last results
                const dir = order.direction === 'DESCENDING' ? 'ASCENDING' : 'DESCENDING';
                return new FieldOrder(order.field, dir).toProto();
            });
            // Swap the cursors to match the now-flipped query ordering.
            structuredQuery.startAt = this._queryOptions.endAt
                ? this.toCursor({
                    values: this._queryOptions.endAt.values,
                    before: !this._queryOptions.endAt.before,
                })
                : undefined;
            structuredQuery.endAt = this._queryOptions.startAt
                ? this.toCursor({
                    values: this._queryOptions.startAt.values,
                    before: !this._queryOptions.startAt.before,
                })
                : undefined;
        }
        const runQueryRequest = {
            parent: parentPath.formattedName,
            structuredQuery,
        };
        if (transactionIdOrReadTime instanceof Uint8Array) {
            runQueryRequest.transaction = transactionIdOrReadTime;
        }
        else if (transactionIdOrReadTime instanceof timestamp_1.Timestamp) {
            runQueryRequest.readTime =
                transactionIdOrReadTime.toProto().timestampValue;
        }
        return runQueryRequest;
    }
    /**
     * Converts current Query to an IBundledQuery.
     *
     * @private
     * @internal
     */
    _toBundledQuery() {
        const projectId = this.firestore.projectId;
        const databaseId = this.firestore.databaseId;
        const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(projectId, databaseId);
        const structuredQuery = this.toStructuredQuery();
        const bundledQuery = {
            parent: parentPath.formattedName,
            structuredQuery,
        };
        if (this._queryOptions.limitType === LimitType.First) {
            bundledQuery.limitType = 'FIRST';
        }
        else if (this._queryOptions.limitType === LimitType.Last) {
            bundledQuery.limitType = 'LAST';
        }
        return bundledQuery;
    }
    toStructuredQuery() {
        const structuredQuery = {
            from: [{}],
        };
        if (this._queryOptions.allDescendants) {
            structuredQuery.from[0].allDescendants = true;
        }
        // Kindless queries select all descendant documents, so we remove the
        // collectionId field.
        if (!this._queryOptions.kindless) {
            structuredQuery.from[0].collectionId = this._queryOptions.collectionId;
        }
        if (this._queryOptions.filters.length >= 1) {
            structuredQuery.where = new CompositeFilterInternal(this._queryOptions.filters, 'AND').toProto();
        }
        if (this._queryOptions.hasFieldOrders()) {
            structuredQuery.orderBy = this._queryOptions.fieldOrders.map(o => o.toProto());
        }
        structuredQuery.startAt = this.toCursor(this._queryOptions.startAt);
        structuredQuery.endAt = this.toCursor(this._queryOptions.endAt);
        if (this._queryOptions.limit) {
            structuredQuery.limit = { value: this._queryOptions.limit };
        }
        structuredQuery.offset = this._queryOptions.offset;
        structuredQuery.select = this._queryOptions.projection;
        return structuredQuery;
    }
    // This method exists solely to enable unit tests to mock it.
    _isPermanentRpcError(err, methodName) {
        return (0, util_1.isPermanentRpcError)(err, methodName);
    }
    /**
     * Internal streaming method that accepts an optional transaction ID.
     *
     * @param transactionId A transaction ID.
     * @private
     * @internal
     * @returns A stream of document results.
     */
    _stream(transactionId) {
        const tag = (0, util_1.requestTag)();
        let lastReceivedDocument = null;
        let backendStream;
        const stream = new stream_1.Transform({
            objectMode: true,
            transform: (proto, enc, callback) => {
                if (proto === NOOP_MESSAGE) {
                    callback(undefined);
                    return;
                }
                const readTime = timestamp_1.Timestamp.fromProto(proto.readTime);
                if (proto.document) {
                    const document = this.firestore.snapshot_(proto.document, proto.readTime);
                    const finalDoc = new document_1.DocumentSnapshotBuilder(document.ref.withConverter(this._queryOptions.converter));
                    // Recreate the QueryDocumentSnapshot with the DocumentReference
                    // containing the original converter.
                    finalDoc.fieldsProto = document._fieldsProto;
                    finalDoc.readTime = document.readTime;
                    finalDoc.createTime = document.createTime;
                    finalDoc.updateTime = document.updateTime;
                    lastReceivedDocument = finalDoc.build();
                    callback(undefined, { document: lastReceivedDocument, readTime });
                    if (proto.done) {
                        (0, logger_1.logger)('Query._stream', tag, 'Trigger Logical Termination.');
                        backendStream.unpipe(stream);
                        backendStream.resume();
                        backendStream.end();
                        stream.end();
                    }
                }
                else {
                    callback(undefined, { readTime });
                }
            },
        });
        this.firestore
            .initializeIfNeeded(tag)
            .then(async () => {
            // `toProto()` might throw an exception. We rely on the behavior of an
            // async function to convert this exception into the rejected Promise we
            // catch below.
            let request = this.toProto(transactionId);
            let streamActive;
            do {
                streamActive = new util_1.Deferred();
                backendStream = await this._firestore.requestStream('runQuery', 
                /* bidirectional= */ false, request, tag);
                backendStream.on('error', err => {
                    backendStream.unpipe(stream);
                    // If a non-transactional query failed, attempt to restart.
                    // Transactional queries are retried via the transaction runner.
                    if (!transactionId && !this._isPermanentRpcError(err, 'runQuery')) {
                        (0, logger_1.logger)('Query._stream', tag, 'Query failed with retryable stream error:', err);
                        // Enqueue a "no-op" write into the stream and resume the query
                        // once it is processed. This allows any enqueued results to be
                        // consumed before resuming the query so that the query resumption
                        // can start at the correct document.
                        stream.write(NOOP_MESSAGE, () => {
                            if (lastReceivedDocument) {
                                // Restart the query but use the last document we received as
                                // the query cursor. Note that we do not use backoff here. The
                                // call to `requestStream()` will backoff should the restart
                                // fail before delivering any results.
                                if (this._queryOptions.requireConsistency) {
                                    request = this.startAfter(lastReceivedDocument).toProto(lastReceivedDocument.readTime);
                                }
                                else {
                                    request = this.startAfter(lastReceivedDocument).toProto();
                                }
                            }
                            streamActive.resolve(/* active= */ true);
                        });
                    }
                    else {
                        (0, logger_1.logger)('Query._stream', tag, 'Query failed with stream error:', err);
                        stream.destroy(err);
                        streamActive.resolve(/* active= */ false);
                    }
                });
                backendStream.on('end', () => {
                    streamActive.resolve(/* active= */ false);
                });
                backendStream.resume();
                backendStream.pipe(stream);
            } while (await streamActive.promise);
        })
            .catch(e => stream.destroy(e));
        return stream;
    }
    /**
     * Attaches a listener for QuerySnapshot events.
     *
     * @param {querySnapshotCallback} onNext A callback to be called every time
     * a new [QuerySnapshot]{@link QuerySnapshot} is available.
     * @param {errorCallback=} onError A callback to be called if the listen
     * fails or is cancelled. No further callbacks will occur.
     *
     * @returns {function()} An unsubscribe function that can be called to cancel
     * the snapshot listener.
     *
     * @example
     * ```
     * let query = firestore.collection('col').where('foo', '==', 'bar');
     *
     * let unsubscribe = query.onSnapshot(querySnapshot => {
     *   console.log(`Received query snapshot of size ${querySnapshot.size}`);
     * }, err => {
     *   console.log(`Encountered error: ${err}`);
     * });
     *
     * // Remove this listener.
     * unsubscribe();
     * ```
     */
    onSnapshot(onNext, onError) {
        (0, validate_1.validateFunction)('onNext', onNext);
        (0, validate_1.validateFunction)('onError', onError, { optional: true });
        const watch = new (require('./watch').QueryWatch)(this.firestore, this, this._queryOptions.converter);
        return watch.onSnapshot((readTime, size, docs, changes) => {
            onNext(new QuerySnapshot(this, readTime, size, docs, changes));
        }, onError || console.error);
    }
    /**
     * Returns a function that can be used to sort QueryDocumentSnapshots
     * according to the sort criteria of this query.
     *
     * @private
     * @internal
     */
    comparator() {
        return (doc1, doc2) => {
            // Add implicit sorting by name, using the last specified direction.
            const lastDirection = this._queryOptions.hasFieldOrders()
                ? this._queryOptions.fieldOrders[this._queryOptions.fieldOrders.length - 1].direction
                : 'ASCENDING';
            const orderBys = this._queryOptions.fieldOrders.concat(new FieldOrder(path_1.FieldPath.documentId(), lastDirection));
            for (const orderBy of orderBys) {
                let comp;
                if (path_1.FieldPath.documentId().isEqual(orderBy.field)) {
                    comp = doc1.ref._path.compareTo(doc2.ref._path);
                }
                else {
                    const v1 = doc1.protoField(orderBy.field);
                    const v2 = doc2.protoField(orderBy.field);
                    if (v1 === undefined || v2 === undefined) {
                        throw new Error('Trying to compare documents on fields that ' +
                            "don't exist. Please include the fields you are ordering on " +
                            'in your select() call.');
                    }
                    comp = (0, order_1.compare)(v1, v2);
                }
                if (comp !== 0) {
                    const direction = orderBy.direction === 'ASCENDING' ? 1 : -1;
                    return direction * comp;
                }
            }
            return 0;
        };
    }
    /**
     * Applies a custom data converter to this Query, allowing you to use your
     * own custom model objects with Firestore. When you call get() on the
     * returned Query, the provided converter will convert between Firestore
     * data and your custom type U.
     *
     * Using the converter allows you to specify generic type arguments when
     * storing and retrieving objects from Firestore.
     *
     * Passing in `null` as the converter parameter removes the current
     * converter.
     *
     * @example
     * ```
     * class Post {
     *   constructor(readonly title: string, readonly author: string) {}
     *
     *   toString(): string {
     *     return this.title + ', by ' + this.author;
     *   }
     * }
     *
     * const postConverter = {
     *   toFirestore(post: Post): FirebaseFirestore.DocumentData {
     *     return {title: post.title, author: post.author};
     *   },
     *   fromFirestore(
     *     snapshot: FirebaseFirestore.QueryDocumentSnapshot
     *   ): Post {
     *     const data = snapshot.data();
     *     return new Post(data.title, data.author);
     *   }
     * };
     *
     * const postSnap = await Firestore()
     *   .collection('posts')
     *   .withConverter(postConverter)
     *   .doc().get();
     * const post = postSnap.data();
     * if (post !== undefined) {
     *   post.title; // string
     *   post.toString(); // Should be defined
     *   post.someNonExistentProperty; // TS error
     * }
     *
     * ```
     * @param {FirestoreDataConverter | null} converter Converts objects to and
     * from Firestore. Passing in `null` removes the current converter.
     * @return A Query<U> that uses the provided converter.
     */
    withConverter(converter) {
        return new Query(this.firestore, this._queryOptions.withConverter(converter !== null && converter !== void 0 ? converter : (0, types_1.defaultConverter)()));
    }
}
exports.Query = Query;
/**
 * A CollectionReference object can be used for adding documents, getting
 * document references, and querying for documents (using the methods
 * inherited from [Query]{@link Query}).
 *
 * @class CollectionReference
 * @extends Query
 */
class CollectionReference extends Query {
    /**
     * @private
     *
     * @param firestore The Firestore Database client.
     * @param path The Path of this collection.
     */
    constructor(firestore, path, converter) {
        super(firestore, QueryOptions.forCollectionQuery(path, converter));
    }
    /**
     * Returns a resource path for this collection.
     * @private
     * @internal
     */
    get _resourcePath() {
        return this._queryOptions.parentPath.append(this._queryOptions.collectionId);
    }
    /**
     * The last path element of the referenced collection.
     *
     * @type {string}
     * @name CollectionReference#id
     * @readonly
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col/doc/subcollection');
     * console.log(`ID of the subcollection: ${collectionRef.id}`);
     * ```
     */
    get id() {
        return this._queryOptions.collectionId;
    }
    /**
     * A reference to the containing Document if this is a subcollection, else
     * null.
     *
     * @type {DocumentReference|null}
     * @name CollectionReference#parent
     * @readonly
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col/doc/subcollection');
     * let documentRef = collectionRef.parent;
     * console.log(`Parent name: ${documentRef.path}`);
     * ```
     */
    get parent() {
        if (this._queryOptions.parentPath.isDocument) {
            return new DocumentReference(this.firestore, this._queryOptions.parentPath);
        }
        return null;
    }
    /**
     * A string representing the path of the referenced collection (relative
     * to the root of the database).
     *
     * @type {string}
     * @name CollectionReference#path
     * @readonly
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col/doc/subcollection');
     * console.log(`Path of the subcollection: ${collectionRef.path}`);
     * ```
     */
    get path() {
        return this._resourcePath.relativeName;
    }
    /**
     * Retrieves the list of documents in this collection.
     *
     * The document references returned may include references to "missing
     * documents", i.e. document locations that have no document present but
     * which contain subcollections with documents. Attempting to read such a
     * document reference (e.g. via `.get()` or `.onSnapshot()`) will return a
     * `DocumentSnapshot` whose `.exists` property is false.
     *
     * @return {Promise<DocumentReference[]>} The list of documents in this
     * collection.
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col');
     *
     * return collectionRef.listDocuments().then(documentRefs => {
     *    return firestore.getAll(...documentRefs);
     * }).then(documentSnapshots => {
     *    for (let documentSnapshot of documentSnapshots) {
     *       if (documentSnapshot.exists) {
     *         console.log(`Found document with data: ${documentSnapshot.id}`);
     *       } else {
     *         console.log(`Found missing document: ${documentSnapshot.id}`);
     *       }
     *    }
     * });
     * ```
     */
    listDocuments() {
        const tag = (0, util_1.requestTag)();
        return this.firestore.initializeIfNeeded(tag).then(() => {
            const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath(this.firestore.projectId, this.firestore.databaseId);
            const request = {
                parent: parentPath.formattedName,
                collectionId: this.id,
                showMissing: true,
                // Setting `pageSize` to an arbitrarily large value lets the backend cap
                // the page size (currently to 300). Note that the backend rejects
                // MAX_INT32 (b/146883794).
                pageSize: Math.pow(2, 16) - 1,
                mask: { fieldPaths: [] },
            };
            return this.firestore
                .request('listDocuments', request, tag)
                .then(documents => {
                // Note that the backend already orders these documents by name,
                // so we do not need to manually sort them.
                return documents.map(doc => {
                    const path = path_1.QualifiedResourcePath.fromSlashSeparatedString(doc.name);
                    return this.doc(path.id);
                });
            });
        });
    }
    /**
     * Gets a [DocumentReference]{@link DocumentReference} instance that
     * refers to the document at the specified path. If no path is specified, an
     * automatically-generated unique ID will be used for the returned
     * DocumentReference.
     *
     * @param {string=} documentPath A slash-separated path to a document.
     * @returns {DocumentReference} The `DocumentReference`
     * instance.
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col');
     * let documentRefWithName = collectionRef.doc('doc');
     * let documentRefWithAutoId = collectionRef.doc();
     * console.log(`Reference with name: ${documentRefWithName.path}`);
     * console.log(`Reference with auto-id: ${documentRefWithAutoId.path}`);
     * ```
     */
    doc(documentPath) {
        if (arguments.length === 0) {
            documentPath = (0, util_1.autoId)();
        }
        else {
            (0, path_1.validateResourcePath)('documentPath', documentPath);
        }
        const path = this._resourcePath.append(documentPath);
        if (!path.isDocument) {
            throw new Error(`Value for argument "documentPath" must point to a document, but was "${documentPath}". Your path does not contain an even number of components.`);
        }
        return new DocumentReference(this.firestore, path, this._queryOptions.converter);
    }
    /**
     * Add a new document to this collection with the specified data, assigning
     * it a document ID automatically.
     *
     * @param {DocumentData} data An Object containing the data for the new
     * document.
     * @throws {Error} If the provided input is not a valid Firestore document.
     * @returns {Promise.<DocumentReference>} A Promise resolved with a
     * [DocumentReference]{@link DocumentReference} pointing to the
     * newly created document.
     *
     * @example
     * ```
     * let collectionRef = firestore.collection('col');
     * collectionRef.add({foo: 'bar'}).then(documentReference => {
     *   console.log(`Added document with name: ${documentReference.id}`);
     * });
     * ```
     */
    add(data) {
        const firestoreData = this._queryOptions.converter.toFirestore(data);
        (0, write_batch_1.validateDocumentData)('data', firestoreData, 
        /*allowDeletes=*/ false, this._allowUndefined);
        const documentRef = this.doc();
        return documentRef.create(data).then(() => documentRef);
    }
    /**
     * Returns true if this `CollectionReference` is equal to the provided value.
     *
     * @param {*} other The value to compare against.
     * @return {boolean} true if this `CollectionReference` is equal to the
     * provided value.
     */
    isEqual(other) {
        return (this === other ||
            (other instanceof CollectionReference && super.isEqual(other)));
    }
    /**
     * Applies a custom data converter to this CollectionReference, allowing you
     * to use your own custom model objects with Firestore. When you call add() on
     * the returned CollectionReference instance, the provided converter will
     * convert between Firestore data and your custom type U.
     *
     * Using the converter allows you to specify generic type arguments when
     * storing and retrieving objects from Firestore.
     *
     * Passing in `null` as the converter parameter removes the current
     * converter.
     *
     * @example
     * ```
     * class Post {
     *   constructor(readonly title: string, readonly author: string) {}
     *
     *   toString(): string {
     *     return this.title + ', by ' + this.author;
     *   }
     * }
     *
     * const postConverter = {
     *   toFirestore(post: Post): FirebaseFirestore.DocumentData {
     *     return {title: post.title, author: post.author};
     *   },
     *   fromFirestore(
     *     snapshot: FirebaseFirestore.QueryDocumentSnapshot
     *   ): Post {
     *     const data = snapshot.data();
     *     return new Post(data.title, data.author);
     *   }
     * };
     *
     * const postSnap = await Firestore()
     *   .collection('posts')
     *   .withConverter(postConverter)
     *   .doc().get();
     * const post = postSnap.data();
     * if (post !== undefined) {
     *   post.title; // string
     *   post.toString(); // Should be defined
     *   post.someNonExistentProperty; // TS error
     * }
     *
     * ```
     * @param {FirestoreDataConverter | null} converter Converts objects to and
     * from Firestore. Passing in `null` removes the current converter.
     * @return A CollectionReference<U> that uses the provided converter.
     */
    withConverter(converter) {
        return new CollectionReference(this.firestore, this._resourcePath, converter !== null && converter !== void 0 ? converter : (0, types_1.defaultConverter)());
    }
}
exports.CollectionReference = CollectionReference;
/**
 * A query that calculates aggregations over an underlying query.
 */
class AggregateQuery {
    /**
     * @private
     * @internal
     *
     * @param _query The query whose aggregations will be calculated by this
     * object.
     * @param _aggregates The aggregations that will be performed by this query.
     */
    constructor(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    _query, _aggregates) {
        this._query = _query;
        this._aggregates = _aggregates;
    }
    /** The query whose aggregations will be calculated by this object. */
    get query() {
        return this._query;
    }
    /**
     * Executes this query.
     *
     * @return A promise that will be resolved with the results of the query.
     */
    get() {
        return this._get();
    }
    /**
     * Internal get() method that accepts an optional transaction id.
     *
     * @private
     * @internal
     * @param {bytes=} transactionId A transaction ID.
     */
    _get(transactionId) {
        // Capture the error stack to preserve stack tracing across async calls.
        const stack = Error().stack;
        return new Promise((resolve, reject) => {
            const stream = this._stream(transactionId);
            stream.on('error', err => {
                reject((0, util_1.wrapError)(err, stack));
            });
            stream.once('data', result => {
                stream.destroy();
                resolve(result);
            });
            stream.on('end', () => {
                reject('No AggregateQuery results');
            });
        });
    }
    /**
     * Internal streaming method that accepts an optional transaction ID.
     *
     * @private
     * @internal
     * @param transactionId A transaction ID.
     * @returns A stream of document results.
     */
    _stream(transactionId) {
        const tag = (0, util_1.requestTag)();
        const firestore = this._query.firestore;
        const stream = new stream_1.Transform({
            objectMode: true,
            transform: (proto, enc, callback) => {
                if (proto.result) {
                    const readTime = timestamp_1.Timestamp.fromProto(proto.readTime);
                    const data = this.decodeResult(proto.result);
                    callback(undefined, new AggregateQuerySnapshot(this, readTime, data));
                }
                else {
                    callback(Error('RunAggregationQueryResponse is missing result'));
                }
            },
        });
        firestore
            .initializeIfNeeded(tag)
            .then(async () => {
            // `toProto()` might throw an exception. We rely on the behavior of an
            // async function to convert this exception into the rejected Promise we
            // catch below.
            const request = this.toProto(transactionId);
            let streamActive;
            do {
                streamActive = new util_1.Deferred();
                const backendStream = await firestore.requestStream('runAggregationQuery', 
                /* bidirectional= */ false, request, tag);
                stream.on('close', () => {
                    backendStream.resume();
                    backendStream.end();
                });
                backendStream.on('error', err => {
                    backendStream.unpipe(stream);
                    // If a non-transactional query failed, attempt to restart.
                    // Transactional queries are retried via the transaction runner.
                    if (!transactionId &&
                        !(0, util_1.isPermanentRpcError)(err, 'runAggregationQuery')) {
                        (0, logger_1.logger)('AggregateQuery._stream', tag, 'AggregateQuery failed with retryable stream error:', err);
                        streamActive.resolve(/* active= */ true);
                    }
                    else {
                        (0, logger_1.logger)('AggregateQuery._stream', tag, 'AggregateQuery failed with stream error:', err);
                        stream.destroy(err);
                        streamActive.resolve(/* active= */ false);
                    }
                });
                backendStream.resume();
                backendStream.pipe(stream);
            } while (await streamActive.promise);
        })
            .catch(e => stream.destroy(e));
        return stream;
    }
    /**
     * Internal method to decode values within result.
     * @private
     */
    decodeResult(proto) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const data = {};
        const fields = proto.aggregateFields;
        if (fields) {
            const serializer = this._query.firestore._serializer;
            for (const prop of Object.keys(fields)) {
                if (this._aggregates[prop] === undefined) {
                    throw new Error(`Unexpected alias [${prop}] in result aggregate result`);
                }
                data[prop] = serializer.decodeValue(fields[prop]);
            }
        }
        return data;
    }
    /**
     * Internal method for serializing a query to its RunAggregationQuery proto
     * representation with an optional transaction id.
     *
     * @private
     * @internal
     * @returns Serialized JSON for the query.
     */
    toProto(transactionId) {
        const queryProto = this._query.toProto();
        //TODO(tomandersen) inspect _query to build request - this is just hard
        // coded count right now.
        const runQueryRequest = {
            parent: queryProto.parent,
            structuredAggregationQuery: {
                structuredQuery: queryProto.structuredQuery,
                aggregations: [
                    {
                        alias: 'count',
                        count: {},
                    },
                ],
            },
        };
        if (transactionId instanceof Uint8Array) {
            runQueryRequest.transaction = transactionId;
        }
        return runQueryRequest;
    }
    /**
     * Compares this object with the given object for equality.
     *
     * This object is considered "equal" to the other object if and only if
     * `other` performs the same aggregations as this `AggregateQuery` and
     * the underlying Query of `other` compares equal to that of this object
     * using `Query.isEqual()`.
     *
     * @param other The object to compare to this object for equality.
     * @return `true` if this object is "equal" to the given object, as
     * defined above, or `false` otherwise.
     */
    isEqual(other) {
        if (this === other) {
            return true;
        }
        if (!(other instanceof AggregateQuery)) {
            return false;
        }
        if (!this.query.isEqual(other.query)) {
            return false;
        }
        return deepEqual(this._aggregates, other._aggregates);
    }
}
exports.AggregateQuery = AggregateQuery;
/**
 * The results of executing an aggregation query.
 */
class AggregateQuerySnapshot {
    /**
     * @private
     * @internal
     *
     * @param _query The query that was executed to produce this result.
     * @param _readTime The time this snapshot was read.
     * @param _data The results of the aggregations performed over the underlying
     * query.
     */
    constructor(_query, _readTime, _data) {
        this._query = _query;
        this._readTime = _readTime;
        this._data = _data;
    }
    /** The query that was executed to produce this result. */
    get query() {
        return this._query;
    }
    /** The time this snapshot was read. */
    get readTime() {
        return this._readTime;
    }
    /**
     * Returns the results of the aggregations performed over the underlying
     * query.
     *
     * The keys of the returned object will be the same as those of the
     * `AggregateSpec` object specified to the aggregation method, and the
     * values will be the corresponding aggregation result.
     *
     * @returns The results of the aggregations performed over the underlying
     * query.
     */
    data() {
        return this._data;
    }
    /**
     * Compares this object with the given object for equality.
     *
     * Two `AggregateQuerySnapshot` instances are considered "equal" if they
     * have the same data and their underlying queries compare "equal" using
     * `AggregateQuery.isEqual()`.
     *
     * @param other The object to compare to this object for equality.
     * @return `true` if this object is "equal" to the given object, as
     * defined above, or `false` otherwise.
     */
    isEqual(other) {
        if (this === other) {
            return true;
        }
        if (!(other instanceof AggregateQuerySnapshot)) {
            return false;
        }
        // Since the read time is different on every read, we explicitly ignore all
        // document metadata in this comparison, just like
        // `DocumentSnapshot.isEqual()` does.
        if (!this.query.isEqual(other.query)) {
            return false;
        }
        return deepEqual(this._data, other._data);
    }
}
exports.AggregateQuerySnapshot = AggregateQuerySnapshot;
/**
 * Validates the input string as a field order direction.
 *
 * @private
 * @internal
 * @param arg The argument name or argument index (for varargs methods).
 * @param op Order direction to validate.
 * @throws when the direction is invalid
 * @return a validated input value, which may be different from the provided
 * value.
 */
function validateQueryOrder(arg, op) {
    // For backwards compatibility, we support both lower and uppercase values.
    op = typeof op === 'string' ? op.toLowerCase() : op;
    (0, validate_1.validateEnumValue)(arg, op, Object.keys(directionOperators), { optional: true });
    return op;
}
exports.validateQueryOrder = validateQueryOrder;
/**
 * Validates the input string as a field comparison operator.
 *
 * @private
 * @internal
 * @param arg The argument name or argument index (for varargs methods).
 * @param op Field comparison operator to validate.
 * @param fieldValue Value that is used in the filter.
 * @throws when the comparison operation is invalid
 * @return a validated input value, which may be different from the provided
 * value.
 */
function validateQueryOperator(arg, op, fieldValue) {
    // For backwards compatibility, we support both `=` and `==` for "equals".
    if (op === '=') {
        op = '==';
    }
    (0, validate_1.validateEnumValue)(arg, op, Object.keys(comparisonOperators));
    if (typeof fieldValue === 'number' &&
        isNaN(fieldValue) &&
        op !== '==' &&
        op !== '!=') {
        throw new Error("Invalid query. You can only perform '==' and '!=' comparisons on NaN.");
    }
    if (fieldValue === null && op !== '==' && op !== '!=') {
        throw new Error("Invalid query. You can only perform '==' and '!=' comparisons on Null.");
    }
    return op;
}
exports.validateQueryOperator = validateQueryOperator;
/**
 * Validates that 'value' is a DocumentReference.
 *
 * @private
 * @internal
 * @param arg The argument name or argument index (for varargs methods).
 * @param value The argument to validate.
 * @return the DocumentReference if valid
 */
function validateDocumentReference(arg, value) {
    if (!(value instanceof DocumentReference)) {
        throw new Error((0, validate_1.invalidArgumentMessage)(arg, 'DocumentReference'));
    }
    return value;
}
exports.validateDocumentReference = validateDocumentReference;
/**
 * Validates that 'value' can be used as a query value.
 *
 * @private
 * @internal
 * @param arg The argument name or argument index (for varargs methods).
 * @param value The argument to validate.
 * @param allowUndefined Whether to allow nested properties that are `undefined`.
 */
function validateQueryValue(arg, value, allowUndefined) {
    (0, serializer_1.validateUserInput)(arg, value, 'query constraint', {
        allowDeletes: 'none',
        allowTransforms: false,
        allowUndefined,
    });
}
/**
 * Verifies equality for an array of objects using the `isEqual` interface.
 *
 * @private
 * @internal
 * @param left Array of objects supporting `isEqual`.
 * @param right Array of objects supporting `isEqual`.
 * @return True if arrays are equal.
 */
function isArrayEqual(left, right) {
    if (left.length !== right.length) {
        return false;
    }
    for (let i = 0; i < left.length; ++i) {
        if (!left[i].isEqual(right[i])) {
            return false;
        }
    }
    return true;
}
/**
 * Returns the first non-undefined value or `undefined` if no such value exists.
 * @private
 * @internal
 */
function coalesce(...values) {
    return values.find(value => value !== undefined);
}
//# sourceMappingURL=reference.js.map