1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var app = require('@firebase/app');
var util = require('@firebase/util');
var component = require('@firebase/component');
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* @fileoverview Constants used in the Firebase Storage library.
*/
/**
* Domain name for firebase storage.
*/
const DEFAULT_HOST = 'firebasestorage.googleapis.com';
/**
* The key in Firebase config json for the storage bucket.
*/
const CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';
/**
* 2 minutes
*
* The timeout for all operations except upload.
*/
const DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;
/**
* 10 minutes
*
* The timeout for upload.
*/
const DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1000;
/**
* 1 second
*/
const DEFAULT_MIN_SLEEP_TIME_MILLIS = 1000;
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* An error returned by the Firebase Storage SDK.
* @public
*/
class StorageError extends util.FirebaseError {
/**
* @param code - A `StorageErrorCode` string to be prefixed with 'storage/' and
* added to the end of the message.
* @param message - Error message.
* @param status_ - Corresponding HTTP Status Code
*/
constructor(code, message, status_ = 0) {
super(prependCode(code), `Firebase Storage: ${message} (${prependCode(code)})`);
this.status_ = status_;
/**
* Stores custom error data unique to the `StorageError`.
*/
this.customData = { serverResponse: null };
this._baseMessage = this.message;
// Without this, `instanceof StorageError`, in tests for example,
// returns false.
Object.setPrototypeOf(this, StorageError.prototype);
}
get status() {
return this.status_;
}
set status(status) {
this.status_ = status;
}
/**
* Compares a `StorageErrorCode` against this error's code, filtering out the prefix.
*/
_codeEquals(code) {
return prependCode(code) === this.code;
}
/**
* Optional response message that was added by the server.
*/
get serverResponse() {
return this.customData.serverResponse;
}
set serverResponse(serverResponse) {
this.customData.serverResponse = serverResponse;
if (this.customData.serverResponse) {
this.message = `${this._baseMessage}\n${this.customData.serverResponse}`;
}
else {
this.message = this._baseMessage;
}
}
}
/**
* @public
* Error codes that can be attached to `StorageError` objects.
*/
exports.StorageErrorCode = void 0;
(function (StorageErrorCode) {
// Shared between all platforms
StorageErrorCode["UNKNOWN"] = "unknown";
StorageErrorCode["OBJECT_NOT_FOUND"] = "object-not-found";
StorageErrorCode["BUCKET_NOT_FOUND"] = "bucket-not-found";
StorageErrorCode["PROJECT_NOT_FOUND"] = "project-not-found";
StorageErrorCode["QUOTA_EXCEEDED"] = "quota-exceeded";
StorageErrorCode["UNAUTHENTICATED"] = "unauthenticated";
StorageErrorCode["UNAUTHORIZED"] = "unauthorized";
StorageErrorCode["UNAUTHORIZED_APP"] = "unauthorized-app";
StorageErrorCode["RETRY_LIMIT_EXCEEDED"] = "retry-limit-exceeded";
StorageErrorCode["INVALID_CHECKSUM"] = "invalid-checksum";
StorageErrorCode["CANCELED"] = "canceled";
// JS specific
StorageErrorCode["INVALID_EVENT_NAME"] = "invalid-event-name";
StorageErrorCode["INVALID_URL"] = "invalid-url";
StorageErrorCode["INVALID_DEFAULT_BUCKET"] = "invalid-default-bucket";
StorageErrorCode["NO_DEFAULT_BUCKET"] = "no-default-bucket";
StorageErrorCode["CANNOT_SLICE_BLOB"] = "cannot-slice-blob";
StorageErrorCode["SERVER_FILE_WRONG_SIZE"] = "server-file-wrong-size";
StorageErrorCode["NO_DOWNLOAD_URL"] = "no-download-url";
StorageErrorCode["INVALID_ARGUMENT"] = "invalid-argument";
StorageErrorCode["INVALID_ARGUMENT_COUNT"] = "invalid-argument-count";
StorageErrorCode["APP_DELETED"] = "app-deleted";
StorageErrorCode["INVALID_ROOT_OPERATION"] = "invalid-root-operation";
StorageErrorCode["INVALID_FORMAT"] = "invalid-format";
StorageErrorCode["INTERNAL_ERROR"] = "internal-error";
StorageErrorCode["UNSUPPORTED_ENVIRONMENT"] = "unsupported-environment";
})(exports.StorageErrorCode || (exports.StorageErrorCode = {}));
function prependCode(code) {
return 'storage/' + code;
}
function unknown() {
const message = 'An unknown error occurred, please check the error payload for ' +
'server response.';
return new StorageError(exports.StorageErrorCode.UNKNOWN, message);
}
function objectNotFound(path) {
return new StorageError(exports.StorageErrorCode.OBJECT_NOT_FOUND, "Object '" + path + "' does not exist.");
}
function quotaExceeded(bucket) {
return new StorageError(exports.StorageErrorCode.QUOTA_EXCEEDED, "Quota for bucket '" +
bucket +
"' exceeded, please view quota on " +
'https://firebase.google.com/pricing/.');
}
function unauthenticated() {
const message = 'User is not authenticated, please authenticate using Firebase ' +
'Authentication and try again.';
return new StorageError(exports.StorageErrorCode.UNAUTHENTICATED, message);
}
function unauthorizedApp() {
return new StorageError(exports.StorageErrorCode.UNAUTHORIZED_APP, 'This app does not have permission to access Firebase Storage on this project.');
}
function unauthorized(path) {
return new StorageError(exports.StorageErrorCode.UNAUTHORIZED, "User does not have permission to access '" + path + "'.");
}
function retryLimitExceeded() {
return new StorageError(exports.StorageErrorCode.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');
}
function canceled() {
return new StorageError(exports.StorageErrorCode.CANCELED, 'User canceled the upload/download.');
}
function invalidUrl(url) {
return new StorageError(exports.StorageErrorCode.INVALID_URL, "Invalid URL '" + url + "'.");
}
function invalidDefaultBucket(bucket) {
return new StorageError(exports.StorageErrorCode.INVALID_DEFAULT_BUCKET, "Invalid default bucket '" + bucket + "'.");
}
function noDefaultBucket() {
return new StorageError(exports.StorageErrorCode.NO_DEFAULT_BUCKET, 'No default bucket ' +
"found. Did you set the '" +
CONFIG_STORAGE_BUCKET_KEY +
"' property when initializing the app?");
}
function cannotSliceBlob() {
return new StorageError(exports.StorageErrorCode.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');
}
function serverFileWrongSize() {
return new StorageError(exports.StorageErrorCode.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');
}
function noDownloadURL() {
return new StorageError(exports.StorageErrorCode.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');
}
function missingPolyFill(polyFill) {
return new StorageError(exports.StorageErrorCode.UNSUPPORTED_ENVIRONMENT, `${polyFill} is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.`);
}
/**
* @internal
*/
function invalidArgument(message) {
return new StorageError(exports.StorageErrorCode.INVALID_ARGUMENT, message);
}
function appDeleted() {
return new StorageError(exports.StorageErrorCode.APP_DELETED, 'The Firebase app was deleted.');
}
/**
* @param name - The name of the operation that was invalid.
*
* @internal
*/
function invalidRootOperation(name) {
return new StorageError(exports.StorageErrorCode.INVALID_ROOT_OPERATION, "The operation '" +
name +
"' cannot be performed on a root reference, create a non-root " +
"reference using child, such as .child('file.png').");
}
/**
* @param format - The format that was not valid.
* @param message - A message describing the format violation.
*/
function invalidFormat(format, message) {
return new StorageError(exports.StorageErrorCode.INVALID_FORMAT, "String does not match format '" + format + "': " + message);
}
/**
* @param message - A message describing the internal error.
*/
function internalError(message) {
throw new StorageError(exports.StorageErrorCode.INTERNAL_ERROR, 'Internal error: ' + message);
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* Firebase Storage location data.
*
* @internal
*/
class Location {
constructor(bucket, path) {
this.bucket = bucket;
this.path_ = path;
}
get path() {
return this.path_;
}
get isRoot() {
return this.path.length === 0;
}
fullServerUrl() {
const encode = encodeURIComponent;
return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);
}
bucketOnlyServerUrl() {
const encode = encodeURIComponent;
return '/b/' + encode(this.bucket) + '/o';
}
static makeFromBucketSpec(bucketString, host) {
let bucketLocation;
try {
bucketLocation = Location.makeFromUrl(bucketString, host);
}
catch (e) {
// Not valid URL, use as-is. This lets you put bare bucket names in
// config.
return new Location(bucketString, '');
}
if (bucketLocation.path === '') {
return bucketLocation;
}
else {
throw invalidDefaultBucket(bucketString);
}
}
static makeFromUrl(url, host) {
let location = null;
const bucketDomain = '([A-Za-z0-9.\\-_]+)';
function gsModify(loc) {
if (loc.path.charAt(loc.path.length - 1) === '/') {
loc.path_ = loc.path_.slice(0, -1);
}
}
const gsPath = '(/(.*))?$';
const gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');
const gsIndices = { bucket: 1, path: 3 };
function httpModify(loc) {
loc.path_ = decodeURIComponent(loc.path);
}
const version = 'v[A-Za-z0-9_]+';
const firebaseStorageHost = host.replace(/[.]/g, '\\.');
const firebaseStoragePath = '(/([^?#]*).*)?$';
const firebaseStorageRegExp = new RegExp(`^https?://${firebaseStorageHost}/${version}/b/${bucketDomain}/o${firebaseStoragePath}`, 'i');
const firebaseStorageIndices = { bucket: 1, path: 3 };
const cloudStorageHost = host === DEFAULT_HOST
? '(?:storage.googleapis.com|storage.cloud.google.com)'
: host;
const cloudStoragePath = '([^?#]*)';
const cloudStorageRegExp = new RegExp(`^https?://${cloudStorageHost}/${bucketDomain}/${cloudStoragePath}`, 'i');
const cloudStorageIndices = { bucket: 1, path: 2 };
const groups = [
{ regex: gsRegex, indices: gsIndices, postModify: gsModify },
{
regex: firebaseStorageRegExp,
indices: firebaseStorageIndices,
postModify: httpModify
},
{
regex: cloudStorageRegExp,
indices: cloudStorageIndices,
postModify: httpModify
}
];
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
const captures = group.regex.exec(url);
if (captures) {
const bucketValue = captures[group.indices.bucket];
let pathValue = captures[group.indices.path];
if (!pathValue) {
pathValue = '';
}
location = new Location(bucketValue, pathValue);
group.postModify(location);
break;
}
}
if (location == null) {
throw invalidUrl(url);
}
return location;
}
}
/**
* A request whose promise always fails.
*/
class FailRequest {
constructor(error) {
this.promise_ = Promise.reject(error);
}
/** @inheritDoc */
getPromise() {
return this.promise_;
}
/** @inheritDoc */
cancel(_appDelete = false) { }
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* Accepts a callback for an action to perform (`doRequest`),
* and then a callback for when the backoff has completed (`backoffCompleteCb`).
* The callback sent to start requires an argument to call (`onRequestComplete`).
* When `start` calls `doRequest`, it passes a callback for when the request has
* completed, `onRequestComplete`. Based on this, the backoff continues, with
* another call to `doRequest` and the above loop continues until the timeout
* is hit, or a successful response occurs.
* @description
* @param doRequest Callback to perform request
* @param backoffCompleteCb Callback to call when backoff has been completed
*/
function start(doRequest,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
backoffCompleteCb, timeout) {
// TODO(andysoto): make this code cleaner (probably refactor into an actual
// type instead of a bunch of functions with state shared in the closure)
let waitSeconds = 1;
// Would type this as "number" but that doesn't work for Node so ¯\_(ツ)_/¯
// TODO: find a way to exclude Node type definition for storage because storage only works in browser
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let retryTimeoutId = null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let globalTimeoutId = null;
let hitTimeout = false;
let cancelState = 0;
function canceled() {
return cancelState === 2;
}
let triggeredCallback = false;
function triggerCallback(...args) {
if (!triggeredCallback) {
triggeredCallback = true;
backoffCompleteCb.apply(null, args);
}
}
function callWithDelay(millis) {
retryTimeoutId = setTimeout(() => {
retryTimeoutId = null;
doRequest(responseHandler, canceled());
}, millis);
}
function clearGlobalTimeout() {
if (globalTimeoutId) {
clearTimeout(globalTimeoutId);
}
}
function responseHandler(success, ...args) {
if (triggeredCallback) {
clearGlobalTimeout();
return;
}
if (success) {
clearGlobalTimeout();
triggerCallback.call(null, success, ...args);
return;
}
const mustStop = canceled() || hitTimeout;
if (mustStop) {
clearGlobalTimeout();
triggerCallback.call(null, success, ...args);
return;
}
if (waitSeconds < 64) {
/* TODO(andysoto): don't back off so quickly if we know we're offline. */
waitSeconds *= 2;
}
let waitMillis;
if (cancelState === 1) {
cancelState = 2;
waitMillis = 0;
}
else {
waitMillis = (waitSeconds + Math.random()) * 1000;
}
callWithDelay(waitMillis);
}
let stopped = false;
function stop(wasTimeout) {
if (stopped) {
return;
}
stopped = true;
clearGlobalTimeout();
if (triggeredCallback) {
return;
}
if (retryTimeoutId !== null) {
if (!wasTimeout) {
cancelState = 2;
}
clearTimeout(retryTimeoutId);
callWithDelay(0);
}
else {
if (!wasTimeout) {
cancelState = 1;
}
}
}
callWithDelay(0);
globalTimeoutId = setTimeout(() => {
hitTimeout = true;
stop(true);
}, timeout);
return stop;
}
/**
* Stops the retry loop from repeating.
* If the function is currently "in between" retries, it is invoked immediately
* with the second parameter as "true". Otherwise, it will be invoked once more
* after the current invocation finishes iff the current invocation would have
* triggered another retry.
*/
function stop(id) {
id(false);
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
function isJustDef(p) {
return p !== void 0;
}
// eslint-disable-next-line @typescript-eslint/ban-types
function isFunction(p) {
return typeof p === 'function';
}
function isNonArrayObject(p) {
return typeof p === 'object' && !Array.isArray(p);
}
function isString(p) {
return typeof p === 'string' || p instanceof String;
}
function isNativeBlob(p) {
return isNativeBlobDefined() && p instanceof Blob;
}
function isNativeBlobDefined() {
return typeof Blob !== 'undefined';
}
function validateNumber(argument, minValue, maxValue, value) {
if (value < minValue) {
throw invalidArgument(`Invalid value for '${argument}'. Expected ${minValue} or greater.`);
}
if (value > maxValue) {
throw invalidArgument(`Invalid value for '${argument}'. Expected ${maxValue} or less.`);
}
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
function makeUrl(urlPart, host, protocol) {
let origin = host;
if (protocol == null) {
origin = `https://${host}`;
}
return `${protocol}://${origin}/v0${urlPart}`;
}
function makeQueryString(params) {
const encode = encodeURIComponent;
let queryPart = '?';
for (const key in params) {
if (params.hasOwnProperty(key)) {
const nextPart = encode(key) + '=' + encode(params[key]);
queryPart = queryPart + nextPart + '&';
}
}
// Chop off the extra '&' or '?' on the end
queryPart = queryPart.slice(0, -1);
return queryPart;
}
/**
* Error codes for requests made by the XhrIo wrapper.
*/
var ErrorCode;
(function (ErrorCode) {
ErrorCode[ErrorCode["NO_ERROR"] = 0] = "NO_ERROR";
ErrorCode[ErrorCode["NETWORK_ERROR"] = 1] = "NETWORK_ERROR";
ErrorCode[ErrorCode["ABORT"] = 2] = "ABORT";
})(ErrorCode || (ErrorCode = {}));
/**
* @license
* Copyright 2022 Google LLC
*
* 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.
*/
/**
* Checks the status code to see if the action should be retried.
*
* @param status Current HTTP status code returned by server.
* @param additionalRetryCodes additional retry codes to check against
*/
function isRetryStatusCode(status, additionalRetryCodes) {
// The codes for which to retry came from this page:
// https://cloud.google.com/storage/docs/exponential-backoff
const isFiveHundredCode = status >= 500 && status < 600;
const extraRetryCodes = [
// Request Timeout: web server didn't receive full request in time.
408,
// Too Many Requests: you're getting rate-limited, basically.
429
];
const isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;
const isAdditionalRetryCode = additionalRetryCodes.indexOf(status) !== -1;
return isFiveHundredCode || isExtraRetryCode || isAdditionalRetryCode;
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* Handles network logic for all Storage Requests, including error reporting and
* retries with backoff.
*
* @param I - the type of the backend's network response.
* @param - O the output type used by the rest of the SDK. The conversion
* happens in the specified `callback_`.
*/
class NetworkRequest {
constructor(url_, method_, headers_, body_, successCodes_, additionalRetryCodes_, callback_, errorCallback_, timeout_, progressCallback_, connectionFactory_, retry = true, isUsingEmulator = false) {
this.url_ = url_;
this.method_ = method_;
this.headers_ = headers_;
this.body_ = body_;
this.successCodes_ = successCodes_;
this.additionalRetryCodes_ = additionalRetryCodes_;
this.callback_ = callback_;
this.errorCallback_ = errorCallback_;
this.timeout_ = timeout_;
this.progressCallback_ = progressCallback_;
this.connectionFactory_ = connectionFactory_;
this.retry = retry;
this.isUsingEmulator = isUsingEmulator;
this.pendingConnection_ = null;
this.backoffId_ = null;
this.canceled_ = false;
this.appDelete_ = false;
this.promise_ = new Promise((resolve, reject) => {
this.resolve_ = resolve;
this.reject_ = reject;
this.start_();
});
}
/**
* Actually starts the retry loop.
*/
start_() {
const doTheRequest = (backoffCallback, canceled) => {
if (canceled) {
backoffCallback(false, new RequestEndStatus(false, null, true));
return;
}
const connection = this.connectionFactory_();
this.pendingConnection_ = connection;
const progressListener = progressEvent => {
const loaded = progressEvent.loaded;
const total = progressEvent.lengthComputable ? progressEvent.total : -1;
if (this.progressCallback_ !== null) {
this.progressCallback_(loaded, total);
}
};
if (this.progressCallback_ !== null) {
connection.addUploadProgressListener(progressListener);
}
// connection.send() never rejects, so we don't need to have a error handler or use catch on the returned promise.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
connection
.send(this.url_, this.method_, this.isUsingEmulator, this.body_, this.headers_)
.then(() => {
if (this.progressCallback_ !== null) {
connection.removeUploadProgressListener(progressListener);
}
this.pendingConnection_ = null;
const hitServer = connection.getErrorCode() === ErrorCode.NO_ERROR;
const status = connection.getStatus();
if (!hitServer ||
(isRetryStatusCode(status, this.additionalRetryCodes_) &&
this.retry)) {
const wasCanceled = connection.getErrorCode() === ErrorCode.ABORT;
backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));
return;
}
const successCode = this.successCodes_.indexOf(status) !== -1;
backoffCallback(true, new RequestEndStatus(successCode, connection));
});
};
/**
* @param requestWentThrough - True if the request eventually went
* through, false if it hit the retry limit or was canceled.
*/
const backoffDone = (requestWentThrough, status) => {
const resolve = this.resolve_;
const reject = this.reject_;
const connection = status.connection;
if (status.wasSuccessCode) {
try {
const result = this.callback_(connection, connection.getResponse());
if (isJustDef(result)) {
resolve(result);
}
else {
resolve();
}
}
catch (e) {
reject(e);
}
}
else {
if (connection !== null) {
const err = unknown();
err.serverResponse = connection.getErrorText();
if (this.errorCallback_) {
reject(this.errorCallback_(connection, err));
}
else {
reject(err);
}
}
else {
if (status.canceled) {
const err = this.appDelete_ ? appDeleted() : canceled();
reject(err);
}
else {
const err = retryLimitExceeded();
reject(err);
}
}
}
};
if (this.canceled_) {
backoffDone(false, new RequestEndStatus(false, null, true));
}
else {
this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);
}
}
/** @inheritDoc */
getPromise() {
return this.promise_;
}
/** @inheritDoc */
cancel(appDelete) {
this.canceled_ = true;
this.appDelete_ = appDelete || false;
if (this.backoffId_ !== null) {
stop(this.backoffId_);
}
if (this.pendingConnection_ !== null) {
this.pendingConnection_.abort();
}
}
}
/**
* A collection of information about the result of a network request.
* @param opt_canceled - Defaults to false.
*/
class RequestEndStatus {
constructor(wasSuccessCode, connection, canceled) {
this.wasSuccessCode = wasSuccessCode;
this.connection = connection;
this.canceled = !!canceled;
}
}
function addAuthHeader_(headers, authToken) {
if (authToken !== null && authToken.length > 0) {
headers['Authorization'] = 'Firebase ' + authToken;
}
}
function addVersionHeader_(headers, firebaseVersion) {
headers['X-Firebase-Storage-Version'] =
'webjs/' + (firebaseVersion ?? 'AppManager');
}
function addGmpidHeader_(headers, appId) {
if (appId) {
headers['X-Firebase-GMPID'] = appId;
}
}
function addAppCheckHeader_(headers, appCheckToken) {
if (appCheckToken !== null) {
headers['X-Firebase-AppCheck'] = appCheckToken;
}
}
function makeRequest(requestInfo, appId, authToken, appCheckToken, requestFactory, firebaseVersion, retry = true, isUsingEmulator = false) {
const queryPart = makeQueryString(requestInfo.urlParams);
const url = requestInfo.url + queryPart;
const headers = Object.assign({}, requestInfo.headers);
addGmpidHeader_(headers, appId);
addAuthHeader_(headers, authToken);
addVersionHeader_(headers, firebaseVersion);
addAppCheckHeader_(headers, appCheckToken);
return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, requestFactory, retry, isUsingEmulator);
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
function getBlobBuilder() {
if (typeof BlobBuilder !== 'undefined') {
return BlobBuilder;
}
else if (typeof WebKitBlobBuilder !== 'undefined') {
return WebKitBlobBuilder;
}
else {
return undefined;
}
}
/**
* Concatenates one or more values together and converts them to a Blob.
*
* @param args The values that will make up the resulting blob.
* @return The blob.
*/
function getBlob$1(...args) {
const BlobBuilder = getBlobBuilder();
if (BlobBuilder !== undefined) {
const bb = new BlobBuilder();
for (let i = 0; i < args.length; i++) {
bb.append(args[i]);
}
return bb.getBlob();
}
else {
if (isNativeBlobDefined()) {
return new Blob(args);
}
else {
throw new StorageError(exports.StorageErrorCode.UNSUPPORTED_ENVIRONMENT, "This browser doesn't seem to support creating Blobs");
}
}
}
/**
* Slices the blob. The returned blob contains data from the start byte
* (inclusive) till the end byte (exclusive). Negative indices cannot be used.
*
* @param blob The blob to be sliced.
* @param start Index of the starting byte.
* @param end Index of the ending byte.
* @return The blob slice or null if not supported.
*/
function sliceBlob(blob, start, end) {
if (blob.webkitSlice) {
return blob.webkitSlice(start, end);
}
else if (blob.mozSlice) {
return blob.mozSlice(start, end);
}
else if (blob.slice) {
return blob.slice(start, end);
}
return null;
}
/**
* @license
* Copyright 2021 Google LLC
*
* 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.
*/
/** Converts a Base64 encoded string to a binary string. */
function decodeBase64(encoded) {
if (typeof atob === 'undefined') {
throw missingPolyFill('base-64');
}
return atob(encoded);
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* An enumeration of the possible string formats for upload.
* @public
*/
const StringFormat = {
/**
* Indicates the string should be interpreted "raw", that is, as normal text.
* The string will be interpreted as UTF-16, then uploaded as a UTF-8 byte
* sequence.
* Example: The string 'Hello! \\ud83d\\ude0a' becomes the byte sequence
* 48 65 6c 6c 6f 21 20 f0 9f 98 8a
*/
RAW: 'raw',
/**
* Indicates the string should be interpreted as base64-encoded data.
* Padding characters (trailing '='s) are optional.
* Example: The string 'rWmO++E6t7/rlw==' becomes the byte sequence
* ad 69 8e fb e1 3a b7 bf eb 97
*/
BASE64: 'base64',
/**
* Indicates the string should be interpreted as base64url-encoded data.
* Padding characters (trailing '='s) are optional.
* Example: The string 'rWmO--E6t7_rlw==' becomes the byte sequence
* ad 69 8e fb e1 3a b7 bf eb 97
*/
BASE64URL: 'base64url',
/**
* Indicates the string is a data URL, such as one obtained from
* canvas.toDataURL().
* Example: the string 'data:application/octet-stream;base64,aaaa'
* becomes the byte sequence
* 69 a6 9a
* (the content-type "application/octet-stream" is also applied, but can
* be overridden in the metadata object).
*/
DATA_URL: 'data_url'
};
class StringData {
constructor(data, contentType) {
this.data = data;
this.contentType = contentType || null;
}
}
/**
* @internal
*/
function dataFromString(format, stringData) {
switch (format) {
case StringFormat.RAW:
return new StringData(utf8Bytes_(stringData));
case StringFormat.BASE64:
case StringFormat.BASE64URL:
return new StringData(base64Bytes_(format, stringData));
case StringFormat.DATA_URL:
return new StringData(dataURLBytes_(stringData), dataURLContentType_(stringData));
// do nothing
}
// assert(false);
throw unknown();
}
function utf8Bytes_(value) {
const b = [];
for (let i = 0; i < value.length; i++) {
let c = value.charCodeAt(i);
if (c <= 127) {
b.push(c);
}
else {
if (c <= 2047) {
b.push(192 | (c >> 6), 128 | (c & 63));
}
else {
if ((c & 64512) === 55296) {
// The start of a surrogate pair.
const valid = i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;
if (!valid) {
// The second surrogate wasn't there.
b.push(239, 191, 189);
}
else {
const hi = c;
const lo = value.charCodeAt(++i);
c = 65536 | ((hi & 1023) << 10) | (lo & 1023);
b.push(240 | (c >> 18), 128 | ((c >> 12) & 63), 128 | ((c >> 6) & 63), 128 | (c & 63));
}
}
else {
if ((c & 64512) === 56320) {
// Invalid low surrogate.
b.push(239, 191, 189);
}
else {
b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));
}
}
}
}
}
return new Uint8Array(b);
}
function percentEncodedBytes_(value) {
let decoded;
try {
decoded = decodeURIComponent(value);
}
catch (e) {
throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');
}
return utf8Bytes_(decoded);
}
function base64Bytes_(format, value) {
switch (format) {
case StringFormat.BASE64: {
const hasMinus = value.indexOf('-') !== -1;
const hasUnder = value.indexOf('_') !== -1;
if (hasMinus || hasUnder) {
const invalidChar = hasMinus ? '-' : '_';
throw invalidFormat(format, "Invalid character '" +
invalidChar +
"' found: is it base64url encoded?");
}
break;
}
case StringFormat.BASE64URL: {
const hasPlus = value.indexOf('+') !== -1;
const hasSlash = value.indexOf('/') !== -1;
if (hasPlus || hasSlash) {
const invalidChar = hasPlus ? '+' : '/';
throw invalidFormat(format, "Invalid character '" + invalidChar + "' found: is it base64 encoded?");
}
value = value.replace(/-/g, '+').replace(/_/g, '/');
break;
}
// do nothing
}
let bytes;
try {
bytes = decodeBase64(value);
}
catch (e) {
if (e.message.includes('polyfill')) {
throw e;
}
throw invalidFormat(format, 'Invalid character found');
}
const array = new Uint8Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
array[i] = bytes.charCodeAt(i);
}
return array;
}
class DataURLParts {
constructor(dataURL) {
this.base64 = false;
this.contentType = null;
const matches = dataURL.match(/^data:([^,]+)?,/);
if (matches === null) {
throw invalidFormat(StringFormat.DATA_URL, "Must be formatted 'data:[<mediatype>][;base64],<data>");
}
const middle = matches[1] || null;
if (middle != null) {
this.base64 = endsWith(middle, ';base64');
this.contentType = this.base64
? middle.substring(0, middle.length - ';base64'.length)
: middle;
}
this.rest = dataURL.substring(dataURL.indexOf(',') + 1);
}
}
function dataURLBytes_(dataUrl) {
const parts = new DataURLParts(dataUrl);
if (parts.base64) {
return base64Bytes_(StringFormat.BASE64, parts.rest);
}
else {
return percentEncodedBytes_(parts.rest);
}
}
function dataURLContentType_(dataUrl) {
const parts = new DataURLParts(dataUrl);
return parts.contentType;
}
function endsWith(s, end) {
const longEnough = s.length >= end.length;
if (!longEnough) {
return false;
}
return s.substring(s.length - end.length) === end;
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* @param opt_elideCopy - If true, doesn't copy mutable input data
* (e.g. Uint8Arrays). Pass true only if you know the objects will not be
* modified after this blob's construction.
*
* @internal
*/
class FbsBlob {
constructor(data, elideCopy) {
let size = 0;
let blobType = '';
if (isNativeBlob(data)) {
this.data_ = data;
size = data.size;
blobType = data.type;
}
else if (data instanceof ArrayBuffer) {
if (elideCopy) {
this.data_ = new Uint8Array(data);
}
else {
this.data_ = new Uint8Array(data.byteLength);
this.data_.set(new Uint8Array(data));
}
size = this.data_.length;
}
else if (data instanceof Uint8Array) {
if (elideCopy) {
this.data_ = data;
}
else {
this.data_ = new Uint8Array(data.length);
this.data_.set(data);
}
size = data.length;
}
this.size_ = size;
this.type_ = blobType;
}
size() {
return this.size_;
}
type() {
return this.type_;
}
slice(startByte, endByte) {
if (isNativeBlob(this.data_)) {
const realBlob = this.data_;
const sliced = sliceBlob(realBlob, startByte, endByte);
if (sliced === null) {
return null;
}
return new FbsBlob(sliced);
}
else {
const slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);
return new FbsBlob(slice, true);
}
}
static getBlob(...args) {
if (isNativeBlobDefined()) {
const blobby = args.map((val) => {
if (val instanceof FbsBlob) {
return val.data_;
}
else {
return val;
}
});
return new FbsBlob(getBlob$1.apply(null, blobby));
}
else {
const uint8Arrays = args.map((val) => {
if (isString(val)) {
return dataFromString(StringFormat.RAW, val).data;
}
else {
// Blobs don't exist, so this has to be a Uint8Array.
return val.data_;
}
});
let finalLength = 0;
uint8Arrays.forEach((array) => {
finalLength += array.byteLength;
});
const merged = new Uint8Array(finalLength);
let index = 0;
uint8Arrays.forEach((array) => {
for (let i = 0; i < array.length; i++) {
merged[index++] = array[i];
}
});
return new FbsBlob(merged, true);
}
}
uploadData() {
return this.data_;
}
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* Returns the Object resulting from parsing the given JSON, or null if the
* given string does not represent a JSON object.
*/
function jsonObjectOrNull(s) {
let obj;
try {
obj = JSON.parse(s);
}
catch (e) {
return null;
}
if (isNonArrayObject(obj)) {
return obj;
}
else {
return null;
}
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* @fileoverview Contains helper methods for manipulating paths.
*/
/**
* @return Null if the path is already at the root.
*/
function parent(path) {
if (path.length === 0) {
return null;
}
const index = path.lastIndexOf('/');
if (index === -1) {
return '';
}
const newPath = path.slice(0, index);
return newPath;
}
function child(path, childPath) {
const canonicalChildPath = childPath
.split('/')
.filter(component => component.length > 0)
.join('/');
if (path.length === 0) {
return canonicalChildPath;
}
else {
return path + '/' + canonicalChildPath;
}
}
/**
* Returns the last component of a path.
* '/foo/bar' -> 'bar'
* '/foo/bar/baz/' -> 'baz/'
* '/a' -> 'a'
*/
function lastComponent(path) {
const index = path.lastIndexOf('/', path.length - 2);
if (index === -1) {
return path;
}
else {
return path.slice(index + 1);
}
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
function noXform_(metadata, value) {
return value;
}
class Mapping {
constructor(server, local, writable, xform) {
this.server = server;
this.local = local || server;
this.writable = !!writable;
this.xform = xform || noXform_;
}
}
let mappings_ = null;
function xformPath(fullPath) {
if (!isString(fullPath) || fullPath.length < 2) {
return fullPath;
}
else {
return lastComponent(fullPath);
}
}
function getMappings() {
if (mappings_) {
return mappings_;
}
const mappings = [];
mappings.push(new Mapping('bucket'));
mappings.push(new Mapping('generation'));
mappings.push(new Mapping('metageneration'));
mappings.push(new Mapping('name', 'fullPath', true));
function mappingsXformPath(_metadata, fullPath) {
return xformPath(fullPath);
}
const nameMapping = new Mapping('name');
nameMapping.xform = mappingsXformPath;
mappings.push(nameMapping);
/**
* Coerces the second param to a number, if it is defined.
*/
function xformSize(_metadata, size) {
if (size !== undefined) {
return Number(size);
}
else {
return size;
}
}
const sizeMapping = new Mapping('size');
sizeMapping.xform = xformSize;
mappings.push(sizeMapping);
mappings.push(new Mapping('timeCreated'));
mappings.push(new Mapping('updated'));
mappings.push(new Mapping('md5Hash', null, true));
mappings.push(new Mapping('cacheControl', null, true));
mappings.push(new Mapping('contentDisposition', null, true));
mappings.push(new Mapping('contentEncoding', null, true));
mappings.push(new Mapping('contentLanguage', null, true));
mappings.push(new Mapping('contentType', null, true));
mappings.push(new Mapping('metadata', 'customMetadata', true));
mappings_ = mappings;
return mappings_;
}
function addRef(metadata, service) {
function generateRef() {
const bucket = metadata['bucket'];
const path = metadata['fullPath'];
const loc = new Location(bucket, path);
return service._makeStorageReference(loc);
}
Object.defineProperty(metadata, 'ref', { get: generateRef });
}
function fromResource(service, resource, mappings) {
const metadata = {};
metadata['type'] = 'file';
const len = mappings.length;
for (let i = 0; i < len; i++) {
const mapping = mappings[i];
metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);
}
addRef(metadata, service);
return metadata;
}
function fromResourceString(service, resourceString, mappings) {
const obj = jsonObjectOrNull(resourceString);
if (obj === null) {
return null;
}
const resource = obj;
return fromResource(service, resource, mappings);
}
function downloadUrlFromResourceString(metadata, resourceString, host, protocol) {
const obj = jsonObjectOrNull(resourceString);
if (obj === null) {
return null;
}
if (!isString(obj['downloadTokens'])) {
// This can happen if objects are uploaded through GCS and retrieved
// through list, so we don't want to throw an Error.
return null;
}
const tokens = obj['downloadTokens'];
if (tokens.length === 0) {
return null;
}
const encode = encodeURIComponent;
const tokensList = tokens.split(',');
const urls = tokensList.map((token) => {
const bucket = metadata['bucket'];
const path = metadata['fullPath'];
const urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);
const base = makeUrl(urlPart, host, protocol);
const queryString = makeQueryString({
alt: 'media',
token
});
return base + queryString;
});
return urls[0];
}
function toResourceString(metadata, mappings) {
const resource = {};
const len = mappings.length;
for (let i = 0; i < len; i++) {
const mapping = mappings[i];
if (mapping.writable) {
resource[mapping.server] = metadata[mapping.local];
}
}
return JSON.stringify(resource);
}
/**
* @license
* Copyright 2019 Google LLC
*
* 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.
*/
const PREFIXES_KEY = 'prefixes';
const ITEMS_KEY = 'items';
function fromBackendResponse(service, bucket, resource) {
const listResult = {
prefixes: [],
items: [],
nextPageToken: resource['nextPageToken']
};
if (resource[PREFIXES_KEY]) {
for (const path of resource[PREFIXES_KEY]) {
const pathWithoutTrailingSlash = path.replace(/\/$/, '');
const reference = service._makeStorageReference(new Location(bucket, pathWithoutTrailingSlash));
listResult.prefixes.push(reference);
}
}
if (resource[ITEMS_KEY]) {
for (const item of resource[ITEMS_KEY]) {
const reference = service._makeStorageReference(new Location(bucket, item['name']));
listResult.items.push(reference);
}
}
return listResult;
}
function fromResponseString(service, bucket, resourceString) {
const obj = jsonObjectOrNull(resourceString);
if (obj === null) {
return null;
}
const resource = obj;
return fromBackendResponse(service, bucket, resource);
}
/**
* Contains a fully specified request.
*
* @param I - the type of the backend's network response.
* @param O - the output response type used by the rest of the SDK.
*/
class RequestInfo {
constructor(url, method,
/**
* Returns the value with which to resolve the request's promise. Only called
* if the request is successful. Throw from this function to reject the
* returned Request's promise with the thrown error.
* Note: The XhrIo passed to this function may be reused after this callback
* returns. Do not keep a reference to it in any way.
*/
handler, timeout) {
this.url = url;
this.method = method;
this.handler = handler;
this.timeout = timeout;
this.urlParams = {};
this.headers = {};
this.body = null;
this.errorHandler = null;
/**
* Called with the current number of bytes uploaded and total size (-1 if not
* computable) of the request body (i.e. used to report upload progress).
*/
this.progressCallback = null;
this.successCodes = [200];
this.additionalRetryCodes = [];
}
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* Throws the UNKNOWN StorageError if cndn is false.
*/
function handlerCheck(cndn) {
if (!cndn) {
throw unknown();
}
}
function metadataHandler(service, mappings) {
function handler(xhr, text) {
const metadata = fromResourceString(service, text, mappings);
handlerCheck(metadata !== null);
return metadata;
}
return handler;
}
function listHandler(service, bucket) {
function handler(xhr, text) {
const listResult = fromResponseString(service, bucket, text);
handlerCheck(listResult !== null);
return listResult;
}
return handler;
}
function downloadUrlHandler(service, mappings) {
function handler(xhr, text) {
const metadata = fromResourceString(service, text, mappings);
handlerCheck(metadata !== null);
return downloadUrlFromResourceString(metadata, text, service.host, service._protocol);
}
return handler;
}
function sharedErrorHandler(location) {
function errorHandler(xhr, err) {
let newErr;
if (xhr.getStatus() === 401) {
if (
// This exact message string is the only consistent part of the
// server's error response that identifies it as an App Check error.
xhr.getErrorText().includes('Firebase App Check token is invalid')) {
newErr = unauthorizedApp();
}
else {
newErr = unauthenticated();
}
}
else {
if (xhr.getStatus() === 402) {
newErr = quotaExceeded(location.bucket);
}
else {
if (xhr.getStatus() === 403) {
newErr = unauthorized(location.path);
}
else {
newErr = err;
}
}
}
newErr.status = xhr.getStatus();
newErr.serverResponse = err.serverResponse;
return newErr;
}
return errorHandler;
}
function objectErrorHandler(location) {
const shared = sharedErrorHandler(location);
function errorHandler(xhr, err) {
let newErr = shared(xhr, err);
if (xhr.getStatus() === 404) {
newErr = objectNotFound(location.path);
}
newErr.serverResponse = err.serverResponse;
return newErr;
}
return errorHandler;
}
function getMetadata$2(service, location, mappings) {
const urlPart = location.fullServerUrl();
const url = makeUrl(urlPart, service.host, service._protocol);
const method = 'GET';
const timeout = service.maxOperationRetryTime;
const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
requestInfo.errorHandler = objectErrorHandler(location);
return requestInfo;
}
function list$2(service, location, delimiter, pageToken, maxResults) {
const urlParams = {};
if (location.isRoot) {
urlParams['prefix'] = '';
}
else {
urlParams['prefix'] = location.path + '/';
}
if (delimiter && delimiter.length > 0) {
urlParams['delimiter'] = delimiter;
}
if (pageToken) {
urlParams['pageToken'] = pageToken;
}
if (maxResults) {
urlParams['maxResults'] = maxResults;
}
const urlPart = location.bucketOnlyServerUrl();
const url = makeUrl(urlPart, service.host, service._protocol);
const method = 'GET';
const timeout = service.maxOperationRetryTime;
const requestInfo = new RequestInfo(url, method, listHandler(service, location.bucket), timeout);
requestInfo.urlParams = urlParams;
requestInfo.errorHandler = sharedErrorHandler(location);
return requestInfo;
}
function getBytes$1(service, location, maxDownloadSizeBytes) {
const urlPart = location.fullServerUrl();
const url = makeUrl(urlPart, service.host, service._protocol) + '?alt=media';
const method = 'GET';
const timeout = service.maxOperationRetryTime;
const requestInfo = new RequestInfo(url, method, (_, data) => data, timeout);
requestInfo.errorHandler = objectErrorHandler(location);
if (maxDownloadSizeBytes !== undefined) {
requestInfo.headers['Range'] = `bytes=0-${maxDownloadSizeBytes}`;
requestInfo.successCodes = [200 /* OK */, 206 /* Partial Content */];
}
return requestInfo;
}
function getDownloadUrl(service, location, mappings) {
const urlPart = location.fullServerUrl();
const url = makeUrl(urlPart, service.host, service._protocol);
const method = 'GET';
const timeout = service.maxOperationRetryTime;
const requestInfo = new RequestInfo(url, method, downloadUrlHandler(service, mappings), timeout);
requestInfo.errorHandler = objectErrorHandler(location);
return requestInfo;
}
function updateMetadata$2(service, location, metadata, mappings) {
const urlPart = location.fullServerUrl();
const url = makeUrl(urlPart, service.host, service._protocol);
const method = 'PATCH';
const body = toResourceString(metadata, mappings);
const headers = { 'Content-Type': 'application/json; charset=utf-8' };
const timeout = service.maxOperationRetryTime;
const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
requestInfo.headers = headers;
requestInfo.body = body;
requestInfo.errorHandler = objectErrorHandler(location);
return requestInfo;
}
function deleteObject$2(service, location) {
const urlPart = location.fullServerUrl();
const url = makeUrl(urlPart, service.host, service._protocol);
const method = 'DELETE';
const timeout = service.maxOperationRetryTime;
function handler(_xhr, _text) { }
const requestInfo = new RequestInfo(url, method, handler, timeout);
requestInfo.successCodes = [200, 204];
requestInfo.errorHandler = objectErrorHandler(location);
return requestInfo;
}
function determineContentType_(metadata, blob) {
return ((metadata && metadata['contentType']) ||
(blob && blob.type()) ||
'application/octet-stream');
}
function metadataForUpload_(location, blob, metadata) {
const metadataClone = Object.assign({}, metadata);
metadataClone['fullPath'] = location.path;
metadataClone['size'] = blob.size();
if (!metadataClone['contentType']) {
metadataClone['contentType'] = determineContentType_(null, blob);
}
return metadataClone;
}
/**
* Prepare RequestInfo for uploads as Content-Type: multipart.
*/
function multipartUpload(service, location, mappings, blob, metadata) {
const urlPart = location.bucketOnlyServerUrl();
const headers = {
'X-Goog-Upload-Protocol': 'multipart'
};
function genBoundary() {
let str = '';
for (let i = 0; i < 2; i++) {
str = str + Math.random().toString().slice(2);
}
return str;
}
const boundary = genBoundary();
headers['Content-Type'] = 'multipart/related; boundary=' + boundary;
const metadata_ = metadataForUpload_(location, blob, metadata);
const metadataString = toResourceString(metadata_, mappings);
const preBlobPart = '--' +
boundary +
'\r\n' +
'Content-Type: application/json; charset=utf-8\r\n\r\n' +
metadataString +
'\r\n--' +
boundary +
'\r\n' +
'Content-Type: ' +
metadata_['contentType'] +
'\r\n\r\n';
const postBlobPart = '\r\n--' + boundary + '--';
const body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);
if (body === null) {
throw cannotSliceBlob();
}
const urlParams = { name: metadata_['fullPath'] };
const url = makeUrl(urlPart, service.host, service._protocol);
const method = 'POST';
const timeout = service.maxUploadRetryTime;
const requestInfo = new RequestInfo(url, method, metadataHandler(service, mappings), timeout);
requestInfo.urlParams = urlParams;
requestInfo.headers = headers;
requestInfo.body = body.uploadData();
requestInfo.errorHandler = sharedErrorHandler(location);
return requestInfo;
}
/**
* @param current The number of bytes that have been uploaded so far.
* @param total The total number of bytes in the upload.
* @param opt_finalized True if the server has finished the upload.
* @param opt_metadata The upload metadata, should
* only be passed if opt_finalized is true.
*/
class ResumableUploadStatus {
constructor(current, total, finalized, metadata) {
this.current = current;
this.total = total;
this.finalized = !!finalized;
this.metadata = metadata || null;
}
}
function checkResumeHeader_(xhr, allowed) {
let status = null;
try {
status = xhr.getResponseHeader('X-Goog-Upload-Status');
}
catch (e) {
handlerCheck(false);
}
const allowedStatus = allowed || ['active'];
handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);
return status;
}
function createResumableUpload(service, location, mappings, blob, metadata) {
const urlPart = location.bucketOnlyServerUrl();
const metadataForUpload = metadataForUpload_(location, blob, metadata);
const urlParams = { name: metadataForUpload['fullPath'] };
const url = makeUrl(urlPart, service.host, service._protocol);
const method = 'POST';
const headers = {
'X-Goog-Upload-Protocol': 'resumable',
'X-Goog-Upload-Command': 'start',
'X-Goog-Upload-Header-Content-Length': `${blob.size()}`,
'X-Goog-Upload-Header-Content-Type': metadataForUpload['contentType'],
'Content-Type': 'application/json; charset=utf-8'
};
const body = toResourceString(metadataForUpload, mappings);
const timeout = service.maxUploadRetryTime;
function handler(xhr) {
checkResumeHeader_(xhr);
let url;
try {
url = xhr.getResponseHeader('X-Goog-Upload-URL');
}
catch (e) {
handlerCheck(false);
}
handlerCheck(isString(url));
return url;
}
const requestInfo = new RequestInfo(url, method, handler, timeout);
requestInfo.urlParams = urlParams;
requestInfo.headers = headers;
requestInfo.body = body;
requestInfo.errorHandler = sharedErrorHandler(location);
return requestInfo;
}
/**
* @param url From a call to fbs.requests.createResumableUpload.
*/
function getResumableUploadStatus(service, location, url, blob) {
const headers = { 'X-Goog-Upload-Command': 'query' };
function handler(xhr) {
const status = checkResumeHeader_(xhr, ['active', 'final']);
let sizeString = null;
try {
sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');
}
catch (e) {
handlerCheck(false);
}
if (!sizeString) {
// null or empty string
handlerCheck(false);
}
const size = Number(sizeString);
handlerCheck(!isNaN(size));
return new ResumableUploadStatus(size, blob.size(), status === 'final');
}
const method = 'POST';
const timeout = service.maxUploadRetryTime;
const requestInfo = new RequestInfo(url, method, handler, timeout);
requestInfo.headers = headers;
requestInfo.errorHandler = sharedErrorHandler(location);
return requestInfo;
}
/**
* Any uploads via the resumable upload API must transfer a number of bytes
* that is a multiple of this number.
*/
const RESUMABLE_UPLOAD_CHUNK_SIZE = 256 * 1024;
/**
* @param url From a call to fbs.requests.createResumableUpload.
* @param chunkSize Number of bytes to upload.
* @param status The previous status.
* If not passed or null, we start from the beginning.
* @throws fbs.Error If the upload is already complete, the passed in status
* has a final size inconsistent with the blob, or the blob cannot be sliced
* for upload.
*/
function continueResumableUpload(location, service, url, blob, chunkSize, mappings, status, progressCallback) {
// TODO(andysoto): standardize on internal asserts
// assert(!(opt_status && opt_status.finalized));
const status_ = new ResumableUploadStatus(0, 0);
if (status) {
status_.current = status.current;
status_.total = status.total;
}
else {
status_.current = 0;
status_.total = blob.size();
}
if (blob.size() !== status_.total) {
throw serverFileWrongSize();
}
const bytesLeft = status_.total - status_.current;
let bytesToUpload = bytesLeft;
if (chunkSize > 0) {
bytesToUpload = Math.min(bytesToUpload, chunkSize);
}
const startByte = status_.current;
const endByte = startByte + bytesToUpload;
let uploadCommand = '';
if (bytesToUpload === 0) {
uploadCommand = 'finalize';
}
else if (bytesLeft === bytesToUpload) {
uploadCommand = 'upload, finalize';
}
else {
uploadCommand = 'upload';
}
const headers = {
'X-Goog-Upload-Command': uploadCommand,
'X-Goog-Upload-Offset': `${status_.current}`
};
const body = blob.slice(startByte, endByte);
if (body === null) {
throw cannotSliceBlob();
}
function handler(xhr, text) {
// TODO(andysoto): Verify the MD5 of each uploaded range:
// the 'x-range-md5' header comes back with status code 308 responses.
// We'll only be able to bail out though, because you can't re-upload a
// range that you previously uploaded.
const uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);
const newCurrent = status_.current + bytesToUpload;
const size = blob.size();
let metadata;
if (uploadStatus === 'final') {
metadata = metadataHandler(service, mappings)(xhr, text);
}
else {
metadata = null;
}
return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);
}
const method = 'POST';
const timeout = service.maxUploadRetryTime;
const requestInfo = new RequestInfo(url, method, handler, timeout);
requestInfo.headers = headers;
requestInfo.body = body.uploadData();
requestInfo.progressCallback = progressCallback || null;
requestInfo.errorHandler = sharedErrorHandler(location);
return requestInfo;
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* An event that is triggered on a task.
* @internal
*/
const TaskEvent = {
/**
* For this event,
* <ul>
* <li>The `next` function is triggered on progress updates and when the
* task is paused/resumed with an `UploadTaskSnapshot` as the first
* argument.</li>
* <li>The `error` function is triggered if the upload is canceled or fails
* for another reason.</li>
* <li>The `complete` function is triggered if the upload completes
* successfully.</li>
* </ul>
*/
STATE_CHANGED: 'state_changed'
};
// type keys = keyof TaskState
/**
* Represents the current state of a running upload.
* @internal
*/
const TaskState = {
/** The task is currently transferring data. */
RUNNING: 'running',
/** The task was paused by the user. */
PAUSED: 'paused',
/** The task completed successfully. */
SUCCESS: 'success',
/** The task was canceled. */
CANCELED: 'canceled',
/** The task failed with an error. */
ERROR: 'error'
};
function taskStateFromInternalTaskState(state) {
switch (state) {
case "running" /* InternalTaskState.RUNNING */:
case "pausing" /* InternalTaskState.PAUSING */:
case "canceling" /* InternalTaskState.CANCELING */:
return TaskState.RUNNING;
case "paused" /* InternalTaskState.PAUSED */:
return TaskState.PAUSED;
case "success" /* InternalTaskState.SUCCESS */:
return TaskState.SUCCESS;
case "canceled" /* InternalTaskState.CANCELED */:
return TaskState.CANCELED;
case "error" /* InternalTaskState.ERROR */:
return TaskState.ERROR;
default:
// TODO(andysoto): assert(false);
return TaskState.ERROR;
}
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
class Observer {
constructor(nextOrObserver, error, complete) {
const asFunctions = isFunction(nextOrObserver) || error != null || complete != null;
if (asFunctions) {
this.next = nextOrObserver;
this.error = error ?? undefined;
this.complete = complete ?? undefined;
}
else {
const observer = nextOrObserver;
this.next = observer.next;
this.error = observer.error;
this.complete = observer.complete;
}
}
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* Returns a function that invokes f with its arguments asynchronously as a
* microtask, i.e. as soon as possible after the current script returns back
* into browser code.
*/
// eslint-disable-next-line @typescript-eslint/ban-types
function async(f) {
return (...argsToForward) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Promise.resolve().then(() => f(...argsToForward));
};
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/** An override for the text-based Connection. Used in tests. */
let textFactoryOverride = null;
/**
* Network layer for browsers. We use this instead of goog.net.XhrIo because
* goog.net.XhrIo is hyuuuuge and doesn't work in React Native on Android.
*/
class XhrConnection {
constructor() {
this.sent_ = false;
this.xhr_ = new XMLHttpRequest();
this.initXhr();
this.errorCode_ = ErrorCode.NO_ERROR;
this.sendPromise_ = new Promise(resolve => {
this.xhr_.addEventListener('abort', () => {
this.errorCode_ = ErrorCode.ABORT;
resolve();
});
this.xhr_.addEventListener('error', () => {
this.errorCode_ = ErrorCode.NETWORK_ERROR;
resolve();
});
this.xhr_.addEventListener('load', () => {
resolve();
});
});
}
send(url, method, isUsingEmulator, body, headers) {
if (this.sent_) {
throw internalError('cannot .send() more than once');
}
if (util.isCloudWorkstation(url) && isUsingEmulator) {
this.xhr_.withCredentials = true;
}
this.sent_ = true;
this.xhr_.open(method, url, true);
if (headers !== undefined) {
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
this.xhr_.setRequestHeader(key, headers[key].toString());
}
}
}
if (body !== undefined) {
this.xhr_.send(body);
}
else {
this.xhr_.send();
}
return this.sendPromise_;
}
getErrorCode() {
if (!this.sent_) {
throw internalError('cannot .getErrorCode() before sending');
}
return this.errorCode_;
}
getStatus() {
if (!this.sent_) {
throw internalError('cannot .getStatus() before sending');
}
try {
return this.xhr_.status;
}
catch (e) {
return -1;
}
}
getResponse() {
if (!this.sent_) {
throw internalError('cannot .getResponse() before sending');
}
return this.xhr_.response;
}
getErrorText() {
if (!this.sent_) {
throw internalError('cannot .getErrorText() before sending');
}
return this.xhr_.statusText;
}
/** Aborts the request. */
abort() {
this.xhr_.abort();
}
getResponseHeader(header) {
return this.xhr_.getResponseHeader(header);
}
addUploadProgressListener(listener) {
if (this.xhr_.upload != null) {
this.xhr_.upload.addEventListener('progress', listener);
}
}
removeUploadProgressListener(listener) {
if (this.xhr_.upload != null) {
this.xhr_.upload.removeEventListener('progress', listener);
}
}
}
class XhrTextConnection extends XhrConnection {
initXhr() {
this.xhr_.responseType = 'text';
}
}
function newTextConnection() {
return textFactoryOverride ? textFactoryOverride() : new XhrTextConnection();
}
class XhrBytesConnection extends XhrConnection {
initXhr() {
this.xhr_.responseType = 'arraybuffer';
}
}
function newBytesConnection() {
return new XhrBytesConnection();
}
class XhrBlobConnection extends XhrConnection {
initXhr() {
this.xhr_.responseType = 'blob';
}
}
function newBlobConnection() {
return new XhrBlobConnection();
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
/**
* Represents a blob being uploaded. Can be used to pause/resume/cancel the
* upload and manage callbacks for various events.
* @internal
*/
class UploadTask {
isExponentialBackoffExpired() {
return this.sleepTime > this.maxSleepTime;
}
/**
* @param ref - The firebaseStorage.Reference object this task came
* from, untyped to avoid cyclic dependencies.
* @param blob - The blob to upload.
*/
constructor(ref, blob, metadata = null) {
/**
* Number of bytes transferred so far.
*/
this._transferred = 0;
this._needToFetchStatus = false;
this._needToFetchMetadata = false;
this._observers = [];
this._error = undefined;
this._uploadUrl = undefined;
this._request = undefined;
this._chunkMultiplier = 1;
this._resolve = undefined;
this._reject = undefined;
this._ref = ref;
this._blob = blob;
this._metadata = metadata;
this._mappings = getMappings();
this._resumable = this._shouldDoResumable(this._blob);
this._state = "running" /* InternalTaskState.RUNNING */;
this._errorHandler = error => {
this._request = undefined;
this._chunkMultiplier = 1;
if (error._codeEquals(exports.StorageErrorCode.CANCELED)) {
this._needToFetchStatus = true;
this.completeTransitions_();
}
else {
const backoffExpired = this.isExponentialBackoffExpired();
if (isRetryStatusCode(error.status, [])) {
if (backoffExpired) {
error = retryLimitExceeded();
}
else {
this.sleepTime = Math.max(this.sleepTime * 2, DEFAULT_MIN_SLEEP_TIME_MILLIS);
this._needToFetchStatus = true;
this.completeTransitions_();
return;
}
}
this._error = error;
this._transition("error" /* InternalTaskState.ERROR */);
}
};
this._metadataErrorHandler = error => {
this._request = undefined;
if (error._codeEquals(exports.StorageErrorCode.CANCELED)) {
this.completeTransitions_();
}
else {
this._error = error;
this._transition("error" /* InternalTaskState.ERROR */);
}
};
this.sleepTime = 0;
this.maxSleepTime = this._ref.storage.maxUploadRetryTime;
this._promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
this._start();
});
// Prevent uncaught rejections on the internal promise from bubbling out
// to the top level with a dummy handler.
this._promise.then(null, () => { });
}
_makeProgressCallback() {
const sizeBefore = this._transferred;
return loaded => this._updateProgress(sizeBefore + loaded);
}
_shouldDoResumable(blob) {
return blob.size() > 256 * 1024;
}
_start() {
if (this._state !== "running" /* InternalTaskState.RUNNING */) {
// This can happen if someone pauses us in a resume callback, for example.
return;
}
if (this._request !== undefined) {
return;
}
if (this._resumable) {
if (this._uploadUrl === undefined) {
this._createResumable();
}
else {
if (this._needToFetchStatus) {
this._fetchStatus();
}
else {
if (this._needToFetchMetadata) {
// Happens if we miss the metadata on upload completion.
this._fetchMetadata();
}
else {
this.pendingTimeout = setTimeout(() => {
this.pendingTimeout = undefined;
this._continueUpload();
}, this.sleepTime);
}
}
}
}
else {
this._oneShotUpload();
}
}
_resolveToken(callback) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Promise.all([
this._ref.storage._getAuthToken(),
this._ref.storage._getAppCheckToken()
]).then(([authToken, appCheckToken]) => {
switch (this._state) {
case "running" /* InternalTaskState.RUNNING */:
callback(authToken, appCheckToken);
break;
case "canceling" /* InternalTaskState.CANCELING */:
this._transition("canceled" /* InternalTaskState.CANCELED */);
break;
case "pausing" /* InternalTaskState.PAUSING */:
this._transition("paused" /* InternalTaskState.PAUSED */);
break;
}
});
}
// TODO(andysoto): assert false
_createResumable() {
this._resolveToken((authToken, appCheckToken) => {
const requestInfo = createResumableUpload(this._ref.storage, this._ref._location, this._mappings, this._blob, this._metadata);
const createRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
this._request = createRequest;
createRequest.getPromise().then((url) => {
this._request = undefined;
this._uploadUrl = url;
this._needToFetchStatus = false;
this.completeTransitions_();
}, this._errorHandler);
});
}
_fetchStatus() {
// TODO(andysoto): assert(this.uploadUrl_ !== null);
const url = this._uploadUrl;
this._resolveToken((authToken, appCheckToken) => {
const requestInfo = getResumableUploadStatus(this._ref.storage, this._ref._location, url, this._blob);
const statusRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
this._request = statusRequest;
statusRequest.getPromise().then(status => {
status = status;
this._request = undefined;
this._updateProgress(status.current);
this._needToFetchStatus = false;
if (status.finalized) {
this._needToFetchMetadata = true;
}
this.completeTransitions_();
}, this._errorHandler);
});
}
_continueUpload() {
const chunkSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;
const status = new ResumableUploadStatus(this._transferred, this._blob.size());
// TODO(andysoto): assert(this.uploadUrl_ !== null);
const url = this._uploadUrl;
this._resolveToken((authToken, appCheckToken) => {
let requestInfo;
try {
requestInfo = continueResumableUpload(this._ref._location, this._ref.storage, url, this._blob, chunkSize, this._mappings, status, this._makeProgressCallback());
}
catch (e) {
this._error = e;
this._transition("error" /* InternalTaskState.ERROR */);
return;
}
const uploadRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken,
/*retry=*/ false // Upload requests should not be retried as each retry should be preceded by another query request. Which is handled in this file.
);
this._request = uploadRequest;
uploadRequest.getPromise().then((newStatus) => {
this._increaseMultiplier();
this._request = undefined;
this._updateProgress(newStatus.current);
if (newStatus.finalized) {
this._metadata = newStatus.metadata;
this._transition("success" /* InternalTaskState.SUCCESS */);
}
else {
this.completeTransitions_();
}
}, this._errorHandler);
});
}
_increaseMultiplier() {
const currentSize = RESUMABLE_UPLOAD_CHUNK_SIZE * this._chunkMultiplier;
// Max chunk size is 32M.
if (currentSize * 2 < 32 * 1024 * 1024) {
this._chunkMultiplier *= 2;
}
}
_fetchMetadata() {
this._resolveToken((authToken, appCheckToken) => {
const requestInfo = getMetadata$2(this._ref.storage, this._ref._location, this._mappings);
const metadataRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
this._request = metadataRequest;
metadataRequest.getPromise().then(metadata => {
this._request = undefined;
this._metadata = metadata;
this._transition("success" /* InternalTaskState.SUCCESS */);
}, this._metadataErrorHandler);
});
}
_oneShotUpload() {
this._resolveToken((authToken, appCheckToken) => {
const requestInfo = multipartUpload(this._ref.storage, this._ref._location, this._mappings, this._blob, this._metadata);
const multipartRequest = this._ref.storage._makeRequest(requestInfo, newTextConnection, authToken, appCheckToken);
this._request = multipartRequest;
multipartRequest.getPromise().then(metadata => {
this._request = undefined;
this._metadata = metadata;
this._updateProgress(this._blob.size());
this._transition("success" /* InternalTaskState.SUCCESS */);
}, this._errorHandler);
});
}
_updateProgress(transferred) {
const old = this._transferred;
this._transferred = transferred;
// A progress update can make the "transferred" value smaller (e.g. a
// partial upload not completed by server, after which the "transferred"
// value may reset to the value at the beginning of the request).
if (this._transferred !== old) {
this._notifyObservers();
}
}
_transition(state) {
if (this._state === state) {
return;
}
switch (state) {
case "canceling" /* InternalTaskState.CANCELING */:
case "pausing" /* InternalTaskState.PAUSING */:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.RUNNING ||
// this.state_ === InternalTaskState.PAUSING);
this._state = state;
if (this._request !== undefined) {
this._request.cancel();
}
else if (this.pendingTimeout) {
clearTimeout(this.pendingTimeout);
this.pendingTimeout = undefined;
this.completeTransitions_();
}
break;
case "running" /* InternalTaskState.RUNNING */:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.PAUSED ||
// this.state_ === InternalTaskState.PAUSING);
const wasPaused = this._state === "paused" /* InternalTaskState.PAUSED */;
this._state = state;
if (wasPaused) {
this._notifyObservers();
this._start();
}
break;
case "paused" /* InternalTaskState.PAUSED */:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.PAUSING);
this._state = state;
this._notifyObservers();
break;
case "canceled" /* InternalTaskState.CANCELED */:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.PAUSED ||
// this.state_ === InternalTaskState.CANCELING);
this._error = canceled();
this._state = state;
this._notifyObservers();
break;
case "error" /* InternalTaskState.ERROR */:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.RUNNING ||
// this.state_ === InternalTaskState.PAUSING ||
// this.state_ === InternalTaskState.CANCELING);
this._state = state;
this._notifyObservers();
break;
case "success" /* InternalTaskState.SUCCESS */:
// TODO(andysoto):
// assert(this.state_ === InternalTaskState.RUNNING ||
// this.state_ === InternalTaskState.PAUSING ||
// this.state_ === InternalTaskState.CANCELING);
this._state = state;
this._notifyObservers();
break;
}
}
completeTransitions_() {
switch (this._state) {
case "pausing" /* InternalTaskState.PAUSING */:
this._transition("paused" /* InternalTaskState.PAUSED */);
break;
case "canceling" /* InternalTaskState.CANCELING */:
this._transition("canceled" /* InternalTaskState.CANCELED */);
break;
case "running" /* InternalTaskState.RUNNING */:
this._start();
break;
}
}
/**
* A snapshot of the current task state.
*/
get snapshot() {
const externalState = taskStateFromInternalTaskState(this._state);
return {
bytesTransferred: this._transferred,
totalBytes: this._blob.size(),
state: externalState,
metadata: this._metadata,
task: this,
ref: this._ref
};
}
/**
* Adds a callback for an event.
* @param type - The type of event to listen for.
* @param nextOrObserver -
* The `next` function, which gets called for each item in
* the event stream, or an observer object with some or all of these three
* properties (`next`, `error`, `complete`).
* @param error - A function that gets called with a `StorageError`
* if the event stream ends due to an error.
* @param completed - A function that gets called if the
* event stream ends normally.
* @returns
* If only the event argument is passed, returns a function you can use to
* add callbacks (see the examples above). If more than just the event
* argument is passed, returns a function you can call to unregister the
* callbacks.
*/
on(type, nextOrObserver, error, completed) {
// Note: `type` isn't being used. Its type is also incorrect. TaskEvent should not be a string.
const observer = new Observer(nextOrObserver || undefined, error || undefined, completed || undefined);
this._addObserver(observer);
return () => {
this._removeObserver(observer);
};
}
/**
* This object behaves like a Promise, and resolves with its snapshot data
* when the upload completes.
* @param onFulfilled - The fulfillment callback. Promise chaining works as normal.
* @param onRejected - The rejection callback.
*/
then(onFulfilled, onRejected) {
// These casts are needed so that TypeScript can infer the types of the
// resulting Promise.
return this._promise.then(onFulfilled, onRejected);
}
/**
* Equivalent to calling `then(null, onRejected)`.
*/
catch(onRejected) {
return this.then(null, onRejected);
}
/**
* Adds the given observer.
*/
_addObserver(observer) {
this._observers.push(observer);
this._notifyObserver(observer);
}
/**
* Removes the given observer.
*/
_removeObserver(observer) {
const i = this._observers.indexOf(observer);
if (i !== -1) {
this._observers.splice(i, 1);
}
}
_notifyObservers() {
this._finishPromise();
const observers = this._observers.slice();
observers.forEach(observer => {
this._notifyObserver(observer);
});
}
_finishPromise() {
if (this._resolve !== undefined) {
let triggered = true;
switch (taskStateFromInternalTaskState(this._state)) {
case TaskState.SUCCESS:
async(this._resolve.bind(null, this.snapshot))();
break;
case TaskState.CANCELED:
case TaskState.ERROR:
const toCall = this._reject;
async(toCall.bind(null, this._error))();
break;
default:
triggered = false;
break;
}
if (triggered) {
this._resolve = undefined;
this._reject = undefined;
}
}
}
_notifyObserver(observer) {
const externalState = taskStateFromInternalTaskState(this._state);
switch (externalState) {
case TaskState.RUNNING:
case TaskState.PAUSED:
if (observer.next) {
async(observer.next.bind(observer, this.snapshot))();
}
break;
case TaskState.SUCCESS:
if (observer.complete) {
async(observer.complete.bind(observer))();
}
break;
case TaskState.CANCELED:
case TaskState.ERROR:
if (observer.error) {
async(observer.error.bind(observer, this._error))();
}
break;
default:
// TODO(andysoto): assert(false);
if (observer.error) {
async(observer.error.bind(observer, this._error))();
}
}
}
/**
* Resumes a paused task. Has no effect on a currently running or failed task.
* @returns True if the operation took effect, false if ignored.
*/
resume() {
const valid = this._state === "paused" /* InternalTaskState.PAUSED */ ||
this._state === "pausing" /* InternalTaskState.PAUSING */;
if (valid) {
this._transition("running" /* InternalTaskState.RUNNING */);
}
return valid;
}
/**
* Pauses a currently running task. Has no effect on a paused or failed task.
* @returns True if the operation took effect, false if ignored.
*/
pause() {
const valid = this._state === "running" /* InternalTaskState.RUNNING */;
if (valid) {
this._transition("pausing" /* InternalTaskState.PAUSING */);
}
return valid;
}
/**
* Cancels a currently running or paused task. Has no effect on a complete or
* failed task.
* @returns True if the operation took effect, false if ignored.
*/
cancel() {
const valid = this._state === "running" /* InternalTaskState.RUNNING */ ||
this._state === "pausing" /* InternalTaskState.PAUSING */;
if (valid) {
this._transition("canceling" /* InternalTaskState.CANCELING */);
}
return valid;
}
}
/**
* @license
* Copyright 2019 Google LLC
*
* 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.
*/
/**
* Provides methods to interact with a bucket in the Firebase Storage service.
* @internal
* @param _location - An fbs.location, or the URL at
* which to base this object, in one of the following forms:
* gs://<bucket>/<object-path>
* http[s]://firebasestorage.googleapis.com/
* <api-version>/b/<bucket>/o/<object-path>
* Any query or fragment strings will be ignored in the http[s]
* format. If no value is passed, the storage object will use a URL based on
* the project ID of the base firebase.App instance.
*/
class Reference {
constructor(_service, location) {
this._service = _service;
if (location instanceof Location) {
this._location = location;
}
else {
this._location = Location.makeFromUrl(location, _service.host);
}
}
/**
* Returns the URL for the bucket and path this object references,
* in the form gs://<bucket>/<object-path>
* @override
*/
toString() {
return 'gs://' + this._location.bucket + '/' + this._location.path;
}
_newRef(service, location) {
return new Reference(service, location);
}
/**
* A reference to the root of this object's bucket.
*/
get root() {
const location = new Location(this._location.bucket, '');
return this._newRef(this._service, location);
}
/**
* The name of the bucket containing this reference's object.
*/
get bucket() {
return this._location.bucket;
}
/**
* The full path of this object.
*/
get fullPath() {
return this._location.path;
}
/**
* The short name of this object, which is the last component of the full path.
* For example, if fullPath is 'full/path/image.png', name is 'image.png'.
*/
get name() {
return lastComponent(this._location.path);
}
/**
* The `StorageService` instance this `StorageReference` is associated with.
*/
get storage() {
return this._service;
}
/**
* A `StorageReference` pointing to the parent location of this `StorageReference`, or null if
* this reference is the root.
*/
get parent() {
const newPath = parent(this._location.path);
if (newPath === null) {
return null;
}
const location = new Location(this._location.bucket, newPath);
return new Reference(this._service, location);
}
/**
* Utility function to throw an error in methods that do not accept a root reference.
*/
_throwIfRoot(name) {
if (this._location.path === '') {
throw invalidRootOperation(name);
}
}
}
/**
* Download the bytes at the object's location.
* @returns A Promise containing the downloaded bytes.
*/
function getBytesInternal(ref, maxDownloadSizeBytes) {
ref._throwIfRoot('getBytes');
const requestInfo = getBytes$1(ref.storage, ref._location, maxDownloadSizeBytes);
return ref.storage
.makeRequestWithTokens(requestInfo, newBytesConnection)
.then(bytes => maxDownloadSizeBytes !== undefined
? // GCS may not honor the Range header for small files
bytes.slice(0, maxDownloadSizeBytes)
: bytes);
}
/**
* Download the bytes at the object's location.
* @returns A Promise containing the downloaded blob.
*/
function getBlobInternal(ref, maxDownloadSizeBytes) {
ref._throwIfRoot('getBlob');
const requestInfo = getBytes$1(ref.storage, ref._location, maxDownloadSizeBytes);
return ref.storage
.makeRequestWithTokens(requestInfo, newBlobConnection)
.then(blob => maxDownloadSizeBytes !== undefined
? // GCS may not honor the Range header for small files
blob.slice(0, maxDownloadSizeBytes)
: blob);
}
/**
* Uploads data to this object's location.
* The upload is not resumable.
*
* @param ref - StorageReference where data should be uploaded.
* @param data - The data to upload.
* @param metadata - Metadata for the newly uploaded data.
* @returns A Promise containing an UploadResult
*/
function uploadBytes$1(ref, data, metadata) {
ref._throwIfRoot('uploadBytes');
const requestInfo = multipartUpload(ref.storage, ref._location, getMappings(), new FbsBlob(data, true), metadata);
return ref.storage
.makeRequestWithTokens(requestInfo, newTextConnection)
.then(finalMetadata => {
return {
metadata: finalMetadata,
ref
};
});
}
/**
* Uploads data to this object's location.
* The upload can be paused and resumed, and exposes progress updates.
* @public
* @param ref - StorageReference where data should be uploaded.
* @param data - The data to upload.
* @param metadata - Metadata for the newly uploaded data.
* @returns An UploadTask
*/
function uploadBytesResumable$1(ref, data, metadata) {
ref._throwIfRoot('uploadBytesResumable');
return new UploadTask(ref, new FbsBlob(data), metadata);
}
/**
* Uploads a string to this object's location.
* The upload is not resumable.
* @public
* @param ref - StorageReference where string should be uploaded.
* @param value - The string to upload.
* @param format - The format of the string to upload.
* @param metadata - Metadata for the newly uploaded string.
* @returns A Promise containing an UploadResult
*/
function uploadString$1(ref, value, format = StringFormat.RAW, metadata) {
ref._throwIfRoot('uploadString');
const data = dataFromString(format, value);
const metadataClone = { ...metadata };
if (metadataClone['contentType'] == null && data.contentType != null) {
metadataClone['contentType'] = data.contentType;
}
return uploadBytes$1(ref, data.data, metadataClone);
}
/**
* List all items (files) and prefixes (folders) under this storage reference.
*
* This is a helper method for calling list() repeatedly until there are
* no more results. The default pagination size is 1000.
*
* Note: The results may not be consistent if objects are changed while this
* operation is running.
*
* Warning: listAll may potentially consume too many resources if there are
* too many results.
* @public
* @param ref - StorageReference to get list from.
*
* @returns A Promise that resolves with all the items and prefixes under
* the current storage reference. `prefixes` contains references to
* sub-directories and `items` contains references to objects in this
* folder. `nextPageToken` is never returned.
*/
function listAll$1(ref) {
const accumulator = {
prefixes: [],
items: []
};
return listAllHelper(ref, accumulator).then(() => accumulator);
}
/**
* Separated from listAll because async functions can't use "arguments".
* @param ref
* @param accumulator
* @param pageToken
*/
async function listAllHelper(ref, accumulator, pageToken) {
const opt = {
// maxResults is 1000 by default.
pageToken
};
const nextPage = await list$1(ref, opt);
accumulator.prefixes.push(...nextPage.prefixes);
accumulator.items.push(...nextPage.items);
if (nextPage.nextPageToken != null) {
await listAllHelper(ref, accumulator, nextPage.nextPageToken);
}
}
/**
* List items (files) and prefixes (folders) under this storage reference.
*
* List API is only available for Firebase Rules Version 2.
*
* GCS is a key-blob store. Firebase Storage imposes the semantic of '/'
* delimited folder structure.
* Refer to GCS's List API if you want to learn more.
*
* To adhere to Firebase Rules's Semantics, Firebase Storage does not
* support objects whose paths end with "/" or contain two consecutive
* "/"s. Firebase Storage List API will filter these unsupported objects.
* list() may fail if there are too many unsupported objects in the bucket.
* @public
*
* @param ref - StorageReference to get list from.
* @param options - See ListOptions for details.
* @returns A Promise that resolves with the items and prefixes.
* `prefixes` contains references to sub-folders and `items`
* contains references to objects in this folder. `nextPageToken`
* can be used to get the rest of the results.
*/
function list$1(ref, options) {
if (options != null) {
if (typeof options.maxResults === 'number') {
validateNumber('options.maxResults',
/* minValue= */ 1,
/* maxValue= */ 1000, options.maxResults);
}
}
const op = options || {};
const requestInfo = list$2(ref.storage, ref._location,
/*delimiter= */ '/', op.pageToken, op.maxResults);
return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
}
/**
* A `Promise` that resolves with the metadata for this object. If this
* object doesn't exist or metadata cannot be retrieved, the promise is
* rejected.
* @public
* @param ref - StorageReference to get metadata from.
*/
function getMetadata$1(ref) {
ref._throwIfRoot('getMetadata');
const requestInfo = getMetadata$2(ref.storage, ref._location, getMappings());
return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
}
/**
* Updates the metadata for this object.
* @public
* @param ref - StorageReference to update metadata for.
* @param metadata - The new metadata for the object.
* Only values that have been explicitly set will be changed. Explicitly
* setting a value to null will remove the metadata.
* @returns A `Promise` that resolves
* with the new metadata for this object.
* See `firebaseStorage.Reference.prototype.getMetadata`
*/
function updateMetadata$1(ref, metadata) {
ref._throwIfRoot('updateMetadata');
const requestInfo = updateMetadata$2(ref.storage, ref._location, metadata, getMappings());
return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
}
/**
* Returns the download URL for the given Reference.
* @public
* @returns A `Promise` that resolves with the download
* URL for this object.
*/
function getDownloadURL$1(ref) {
ref._throwIfRoot('getDownloadURL');
const requestInfo = getDownloadUrl(ref.storage, ref._location, getMappings());
return ref.storage
.makeRequestWithTokens(requestInfo, newTextConnection)
.then(url => {
if (url === null) {
throw noDownloadURL();
}
return url;
});
}
/**
* Deletes the object at this location.
* @public
* @param ref - StorageReference for object to delete.
* @returns A `Promise` that resolves if the deletion succeeds.
*/
function deleteObject$1(ref) {
ref._throwIfRoot('deleteObject');
const requestInfo = deleteObject$2(ref.storage, ref._location);
return ref.storage.makeRequestWithTokens(requestInfo, newTextConnection);
}
/**
* Returns reference for object obtained by appending `childPath` to `ref`.
*
* @param ref - StorageReference to get child of.
* @param childPath - Child path from provided ref.
* @returns A reference to the object obtained by
* appending childPath, removing any duplicate, beginning, or trailing
* slashes.
*
*/
function _getChild$1(ref, childPath) {
const newPath = child(ref._location.path, childPath);
const location = new Location(ref._location.bucket, newPath);
return new Reference(ref.storage, location);
}
/**
* @license
* Copyright 2017 Google LLC
*
* 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.
*/
function isUrl(path) {
return /^[A-Za-z]+:\/\//.test(path);
}
/**
* Returns a firebaseStorage.Reference for the given url.
*/
function refFromURL(service, url) {
return new Reference(service, url);
}
/**
* Returns a firebaseStorage.Reference for the given path in the default
* bucket.
*/
function refFromPath(ref, path) {
if (ref instanceof FirebaseStorageImpl) {
const service = ref;
if (service._bucket == null) {
throw noDefaultBucket();
}
const reference = new Reference(service, service._bucket);
if (path != null) {
return refFromPath(reference, path);
}
else {
return reference;
}
}
else {
// ref is a Reference
if (path !== undefined) {
return _getChild$1(ref, path);
}
else {
return ref;
}
}
}
function ref$1(serviceOrRef, pathOrUrl) {
if (pathOrUrl && isUrl(pathOrUrl)) {
if (serviceOrRef instanceof FirebaseStorageImpl) {
return refFromURL(serviceOrRef, pathOrUrl);
}
else {
throw invalidArgument('To use ref(service, url), the first argument must be a Storage instance.');
}
}
else {
return refFromPath(serviceOrRef, pathOrUrl);
}
}
function extractBucket(host, config) {
const bucketString = config?.[CONFIG_STORAGE_BUCKET_KEY];
if (bucketString == null) {
return null;
}
return Location.makeFromBucketSpec(bucketString, host);
}
function connectStorageEmulator$1(storage, host, port, options = {}) {
storage.host = `${host}:${port}`;
const useSsl = util.isCloudWorkstation(host);
// Workaround to get cookies in Firebase Studio
if (useSsl) {
void util.pingServer(`https://${storage.host}/b`);
util.updateEmulatorBanner('Storage', true);
}
storage._isUsingEmulator = true;
storage._protocol = useSsl ? 'https' : 'http';
const { mockUserToken } = options;
if (mockUserToken) {
storage._overrideAuthToken =
typeof mockUserToken === 'string'
? mockUserToken
: util.createMockUserToken(mockUserToken, storage.app.options.projectId);
}
}
/**
* A service that provides Firebase Storage Reference instances.
* @param opt_url - gs:// url to a custom Storage Bucket
*
* @internal
*/
class FirebaseStorageImpl {
constructor(
/**
* FirebaseApp associated with this StorageService instance.
*/
app, _authProvider,
/**
* @internal
*/
_appCheckProvider,
/**
* @internal
*/
_url, _firebaseVersion, _isUsingEmulator = false) {
this.app = app;
this._authProvider = _authProvider;
this._appCheckProvider = _appCheckProvider;
this._url = _url;
this._firebaseVersion = _firebaseVersion;
this._isUsingEmulator = _isUsingEmulator;
this._bucket = null;
/**
* This string can be in the formats:
* - host
* - host:port
*/
this._host = DEFAULT_HOST;
this._protocol = 'https';
this._appId = null;
this._deleted = false;
this._maxOperationRetryTime = DEFAULT_MAX_OPERATION_RETRY_TIME;
this._maxUploadRetryTime = DEFAULT_MAX_UPLOAD_RETRY_TIME;
this._requests = new Set();
if (_url != null) {
this._bucket = Location.makeFromBucketSpec(_url, this._host);
}
else {
this._bucket = extractBucket(this._host, this.app.options);
}
}
/**
* The host string for this service, in the form of `host` or
* `host:port`.
*/
get host() {
return this._host;
}
set host(host) {
this._host = host;
if (this._url != null) {
this._bucket = Location.makeFromBucketSpec(this._url, host);
}
else {
this._bucket = extractBucket(host, this.app.options);
}
}
/**
* The maximum time to retry uploads in milliseconds.
*/
get maxUploadRetryTime() {
return this._maxUploadRetryTime;
}
set maxUploadRetryTime(time) {
validateNumber('time',
/* minValue=*/ 0,
/* maxValue= */ Number.POSITIVE_INFINITY, time);
this._maxUploadRetryTime = time;
}
/**
* The maximum time to retry operations other than uploads or downloads in
* milliseconds.
*/
get maxOperationRetryTime() {
return this._maxOperationRetryTime;
}
set maxOperationRetryTime(time) {
validateNumber('time',
/* minValue=*/ 0,
/* maxValue= */ Number.POSITIVE_INFINITY, time);
this._maxOperationRetryTime = time;
}
async _getAuthToken() {
if (this._overrideAuthToken) {
return this._overrideAuthToken;
}
const auth = this._authProvider.getImmediate({ optional: true });
if (auth) {
const tokenData = await auth.getToken();
if (tokenData !== null) {
return tokenData.accessToken;
}
}
return null;
}
async _getAppCheckToken() {
if (app._isFirebaseServerApp(this.app) && this.app.settings.appCheckToken) {
return this.app.settings.appCheckToken;
}
const appCheck = this._appCheckProvider.getImmediate({ optional: true });
if (appCheck) {
const result = await appCheck.getToken();
// TODO: What do we want to do if there is an error getting the token?
// Context: appCheck.getToken() will never throw even if an error happened. In the error case, a dummy token will be
// returned along with an error field describing the error. In general, we shouldn't care about the error condition and just use
// the token (actual or dummy) to send requests.
return result.token;
}
return null;
}
/**
* Stop running requests and prevent more from being created.
*/
_delete() {
if (!this._deleted) {
this._deleted = true;
this._requests.forEach(request => request.cancel());
this._requests.clear();
}
return Promise.resolve();
}
/**
* Returns a new firebaseStorage.Reference object referencing this StorageService
* at the given Location.
*/
_makeStorageReference(loc) {
return new Reference(this, loc);
}
/**
* @param requestInfo - HTTP RequestInfo object
* @param authToken - Firebase auth token
*/
_makeRequest(requestInfo, requestFactory, authToken, appCheckToken, retry = true) {
if (!this._deleted) {
const request = makeRequest(requestInfo, this._appId, authToken, appCheckToken, requestFactory, this._firebaseVersion, retry, this._isUsingEmulator);
this._requests.add(request);
// Request removes itself from set when complete.
request.getPromise().then(() => this._requests.delete(request), () => this._requests.delete(request));
return request;
}
else {
return new FailRequest(appDeleted());
}
}
async makeRequestWithTokens(requestInfo, requestFactory) {
const [authToken, appCheckToken] = await Promise.all([
this._getAuthToken(),
this._getAppCheckToken()
]);
return this._makeRequest(requestInfo, requestFactory, authToken, appCheckToken).getPromise();
}
}
const name = "@firebase/storage";
const version = "0.14.0";
/**
* @license
* Copyright 2020 Google LLC
*
* 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.
*/
/**
* Type constant for Firebase Storage.
*/
const STORAGE_TYPE = 'storage';
/**
* @license
* Copyright 2020 Google LLC
*
* 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.
*/
/**
* Downloads the data at the object's location. Returns an error if the object
* is not found.
*
* To use this functionality, you have to whitelist your app's origin in your
* Cloud Storage bucket. See also
* https://cloud.google.com/storage/docs/configuring-cors
*
* @public
* @param ref - StorageReference where data should be downloaded.
* @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
* retrieve.
* @returns A Promise containing the object's bytes
*/
function getBytes(ref, maxDownloadSizeBytes) {
ref = util.getModularInstance(ref);
return getBytesInternal(ref, maxDownloadSizeBytes);
}
/**
* Uploads data to this object's location.
* The upload is not resumable.
* @public
* @param ref - {@link StorageReference} where data should be uploaded.
* @param data - The data to upload.
* @param metadata - Metadata for the data to upload.
* @returns A Promise containing an UploadResult
*/
function uploadBytes(ref, data, metadata) {
ref = util.getModularInstance(ref);
return uploadBytes$1(ref, data, metadata);
}
/**
* Uploads a string to this object's location.
* The upload is not resumable.
* @public
* @param ref - {@link StorageReference} where string should be uploaded.
* @param value - The string to upload.
* @param format - The format of the string to upload.
* @param metadata - Metadata for the string to upload.
* @returns A Promise containing an UploadResult
*/
function uploadString(ref, value, format, metadata) {
ref = util.getModularInstance(ref);
return uploadString$1(ref, value, format, metadata);
}
/**
* Uploads data to this object's location.
* The upload can be paused and resumed, and exposes progress updates.
* @public
* @param ref - {@link StorageReference} where data should be uploaded.
* @param data - The data to upload.
* @param metadata - Metadata for the data to upload.
* @returns An UploadTask
*/
function uploadBytesResumable(ref, data, metadata) {
ref = util.getModularInstance(ref);
return uploadBytesResumable$1(ref, data, metadata);
}
/**
* A `Promise` that resolves with the metadata for this object. If this
* object doesn't exist or metadata cannot be retrieved, the promise is
* rejected.
* @public
* @param ref - {@link StorageReference} to get metadata from.
*/
function getMetadata(ref) {
ref = util.getModularInstance(ref);
return getMetadata$1(ref);
}
/**
* Updates the metadata for this object.
* @public
* @param ref - {@link StorageReference} to update metadata for.
* @param metadata - The new metadata for the object.
* Only values that have been explicitly set will be changed. Explicitly
* setting a value to null will remove the metadata.
* @returns A `Promise` that resolves with the new metadata for this object.
*/
function updateMetadata(ref, metadata) {
ref = util.getModularInstance(ref);
return updateMetadata$1(ref, metadata);
}
/**
* List items (files) and prefixes (folders) under this storage reference.
*
* List API is only available for Firebase Rules Version 2.
*
* GCS is a key-blob store. Firebase Storage imposes the semantic of '/'
* delimited folder structure.
* Refer to GCS's List API if you want to learn more.
*
* To adhere to Firebase Rules's Semantics, Firebase Storage does not
* support objects whose paths end with "/" or contain two consecutive
* "/"s. Firebase Storage List API will filter these unsupported objects.
* list() may fail if there are too many unsupported objects in the bucket.
* @public
*
* @param ref - {@link StorageReference} to get list from.
* @param options - See {@link ListOptions} for details.
* @returns A `Promise` that resolves with the items and prefixes.
* `prefixes` contains references to sub-folders and `items`
* contains references to objects in this folder. `nextPageToken`
* can be used to get the rest of the results.
*/
function list(ref, options) {
ref = util.getModularInstance(ref);
return list$1(ref, options);
}
/**
* List all items (files) and prefixes (folders) under this storage reference.
*
* This is a helper method for calling list() repeatedly until there are
* no more results. The default pagination size is 1000.
*
* Note: The results may not be consistent if objects are changed while this
* operation is running.
*
* Warning: `listAll` may potentially consume too many resources if there are
* too many results.
* @public
* @param ref - {@link StorageReference} to get list from.
*
* @returns A `Promise` that resolves with all the items and prefixes under
* the current storage reference. `prefixes` contains references to
* sub-directories and `items` contains references to objects in this
* folder. `nextPageToken` is never returned.
*/
function listAll(ref) {
ref = util.getModularInstance(ref);
return listAll$1(ref);
}
/**
* Returns the download URL for the given {@link StorageReference}.
* @public
* @param ref - {@link StorageReference} to get the download URL for.
* @returns A `Promise` that resolves with the download
* URL for this object.
*/
function getDownloadURL(ref) {
ref = util.getModularInstance(ref);
return getDownloadURL$1(ref);
}
/**
* Deletes the object at this location.
* @public
* @param ref - {@link StorageReference} for object to delete.
* @returns A `Promise` that resolves if the deletion succeeds.
*/
function deleteObject(ref) {
ref = util.getModularInstance(ref);
return deleteObject$1(ref);
}
function ref(serviceOrRef, pathOrUrl) {
serviceOrRef = util.getModularInstance(serviceOrRef);
return ref$1(serviceOrRef, pathOrUrl);
}
/**
* @internal
*/
function _getChild(ref, childPath) {
return _getChild$1(ref, childPath);
}
/**
* Gets a {@link FirebaseStorage} instance for the given Firebase app.
* @public
* @param app - Firebase app to get {@link FirebaseStorage} instance for.
* @param bucketUrl - The gs:// url to your Firebase Storage Bucket.
* If not passed, uses the app's default Storage Bucket.
* @returns A {@link FirebaseStorage} instance.
*/
function getStorage(app$1 = app.getApp(), bucketUrl) {
app$1 = util.getModularInstance(app$1);
const storageProvider = app._getProvider(app$1, STORAGE_TYPE);
const storageInstance = storageProvider.getImmediate({
identifier: bucketUrl
});
const emulator = util.getDefaultEmulatorHostnameAndPort('storage');
if (emulator) {
connectStorageEmulator(storageInstance, ...emulator);
}
return storageInstance;
}
/**
* Modify this {@link FirebaseStorage} instance to communicate with the Cloud Storage emulator.
*
* @param storage - The {@link FirebaseStorage} instance
* @param host - The emulator host (ex: localhost)
* @param port - The emulator port (ex: 5001)
* @param options - Emulator options. `options.mockUserToken` is the mock auth
* token to use for unit testing Security Rules.
* @public
*/
function connectStorageEmulator(storage, host, port, options = {}) {
connectStorageEmulator$1(storage, host, port, options);
}
/**
* @license
* Copyright 2021 Google LLC
*
* 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.
*/
/**
* Downloads the data at the object's location. Returns an error if the object
* is not found.
*
* To use this functionality, you have to whitelist your app's origin in your
* Cloud Storage bucket. See also
* https://cloud.google.com/storage/docs/configuring-cors
*
* This API is not available in Node.
*
* @public
* @param ref - StorageReference where data should be downloaded.
* @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
* retrieve.
* @returns A Promise that resolves with a Blob containing the object's bytes
*/
function getBlob(ref, maxDownloadSizeBytes) {
ref = util.getModularInstance(ref);
return getBlobInternal(ref, maxDownloadSizeBytes);
}
/**
* Downloads the data at the object's location. Raises an error event if the
* object is not found.
*
* This API is only available in Node.
*
* @public
* @param ref - StorageReference where data should be downloaded.
* @param maxDownloadSizeBytes - If set, the maximum allowed size in bytes to
* retrieve.
* @returns A stream with the object's data as bytes
*/
function getStream(ref, maxDownloadSizeBytes) {
throw new Error('getStream() is only supported by NodeJS builds');
}
/**
* Cloud Storage for Firebase
*
* @packageDocumentation
*/
function factory(container, { instanceIdentifier: url }) {
const app$1 = container.getProvider('app').getImmediate();
const authProvider = container.getProvider('auth-internal');
const appCheckProvider = container.getProvider('app-check-internal');
return new FirebaseStorageImpl(app$1, authProvider, appCheckProvider, url, app.SDK_VERSION);
}
function registerStorage() {
app._registerComponent(new component.Component(STORAGE_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
//RUNTIME_ENV will be replaced during the compilation to "node" for nodejs and an empty string for browser
app.registerVersion(name, version, '');
// BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
app.registerVersion(name, version, 'cjs2020');
}
registerStorage();
exports.StorageError = StorageError;
exports.StringFormat = StringFormat;
exports._FbsBlob = FbsBlob;
exports._Location = Location;
exports._TaskEvent = TaskEvent;
exports._TaskState = TaskState;
exports._UploadTask = UploadTask;
exports._dataFromString = dataFromString;
exports._getChild = _getChild;
exports._invalidArgument = invalidArgument;
exports._invalidRootOperation = invalidRootOperation;
exports.connectStorageEmulator = connectStorageEmulator;
exports.deleteObject = deleteObject;
exports.getBlob = getBlob;
exports.getBytes = getBytes;
exports.getDownloadURL = getDownloadURL;
exports.getMetadata = getMetadata;
exports.getStorage = getStorage;
exports.getStream = getStream;
exports.list = list;
exports.listAll = listAll;
exports.ref = ref;
exports.updateMetadata = updateMetadata;
exports.uploadBytes = uploadBytes;
exports.uploadBytesResumable = uploadBytesResumable;
exports.uploadString = uploadString;
//# sourceMappingURL=index.browser.cjs.js.map
|