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
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
"use strict";
// 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.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Bucket = exports.BucketExceptionMessages = exports.AvailableServiceObjectMethods = exports.BucketActionToHTTPMethod = void 0;
const nodejs_common_1 = require("./nodejs-common");
const paginator_1 = require("@google-cloud/paginator");
const promisify_1 = require("@google-cloud/promisify");
const extend = require("extend");
const fs = require("fs");
const mime = require("mime-types");
const path = require("path");
const pLimit = require("p-limit");
const util_1 = require("util");
const retry = require("async-retry");
const util_2 = require("./util");
const acl_1 = require("./acl");
const file_1 = require("./file");
const iam_1 = require("./iam");
const notification_1 = require("./notification");
const storage_1 = require("./storage");
const signer_1 = require("./signer");
const stream_1 = require("stream");
const url_1 = require("url");
var BucketActionToHTTPMethod;
(function (BucketActionToHTTPMethod) {
    BucketActionToHTTPMethod["list"] = "GET";
})(BucketActionToHTTPMethod = exports.BucketActionToHTTPMethod || (exports.BucketActionToHTTPMethod = {}));
var AvailableServiceObjectMethods;
(function (AvailableServiceObjectMethods) {
    AvailableServiceObjectMethods[AvailableServiceObjectMethods["setMetadata"] = 0] = "setMetadata";
    AvailableServiceObjectMethods[AvailableServiceObjectMethods["delete"] = 1] = "delete";
})(AvailableServiceObjectMethods = exports.AvailableServiceObjectMethods || (exports.AvailableServiceObjectMethods = {}));
var BucketExceptionMessages;
(function (BucketExceptionMessages) {
    BucketExceptionMessages["PROVIDE_SOURCE_FILE"] = "You must provide at least one source file.";
    BucketExceptionMessages["DESTINATION_FILE_NOT_SPECIFIED"] = "A destination file must be specified.";
    BucketExceptionMessages["CHANNEL_ID_REQUIRED"] = "An ID is required to create a channel.";
    BucketExceptionMessages["CHANNEL_ADDRESS_REQUIRED"] = "An address is required to create a channel.";
    BucketExceptionMessages["TOPIC_NAME_REQUIRED"] = "A valid topic name is required.";
    BucketExceptionMessages["CONFIGURATION_OBJECT_PREFIX_REQUIRED"] = "A configuration object with a prefix is required.";
    BucketExceptionMessages["SPECIFY_FILE_NAME"] = "A file name must be specified.";
    BucketExceptionMessages["METAGENERATION_NOT_PROVIDED"] = "A metageneration must be provided.";
    BucketExceptionMessages["SUPPLY_NOTIFICATION_ID"] = "You must supply a notification ID.";
})(BucketExceptionMessages = exports.BucketExceptionMessages || (exports.BucketExceptionMessages = {}));
/**
 * @callback Crc32cGeneratorToStringCallback
 * A method returning the CRC32C as a base64-encoded string.
 *
 * @returns {string}
 *
 * @example
 * Hashing the string 'data' should return 'rth90Q=='
 *
 * ```js
 * const buffer = Buffer.from('data');
 * crc32c.update(buffer);
 * crc32c.toString(); // 'rth90Q=='
 * ```
 **/
/**
 * @callback Crc32cGeneratorValidateCallback
 * A method validating a base64-encoded CRC32C string.
 *
 * @param {string} [value] base64-encoded CRC32C string to validate
 * @returns {boolean}
 *
 * @example
 * Should return `true` if the value matches, `false` otherwise
 *
 * ```js
 * const buffer = Buffer.from('data');
 * crc32c.update(buffer);
 * crc32c.validate('DkjKuA=='); // false
 * crc32c.validate('rth90Q=='); // true
 * ```
 **/
/**
 * @callback Crc32cGeneratorUpdateCallback
 * A method for passing `Buffer`s for CRC32C generation.
 *
 * @param {Buffer} [data] data to update CRC32C value with
 * @returns {undefined}
 *
 * @example
 * Hashing buffers from 'some ' and 'text\n'
 *
 * ```js
 * const buffer1 = Buffer.from('some ');
 * crc32c.update(buffer1);
 *
 * const buffer2 = Buffer.from('text\n');
 * crc32c.update(buffer2);
 *
 * crc32c.toString(); // 'DkjKuA=='
 * ```
 **/
/**
 * @typedef {object} CRC32CValidator
 * @property {Crc32cGeneratorToStringCallback}
 * @property {Crc32cGeneratorValidateCallback}
 * @property {Crc32cGeneratorUpdateCallback}
 */
/**
 * A function that generates a CRC32C Validator. Defaults to {@link CRC32C}
 *
 * @name Bucket#crc32cGenerator
 * @type {CRC32CValidator}
 */
/**
 * Get and set IAM policies for your bucket.
 *
 * @name Bucket#iam
 * @mixes Iam
 *
 * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management}
 * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access}
 * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles}
 *
 * @example
 * ```
 * const {Storage} = require('@google-cloud/storage');
 * const storage = new Storage();
 * const bucket = storage.bucket('albums');
 *
 * //-
 * // Get the IAM policy for your bucket.
 * //-
 * bucket.iam.getPolicy(function(err, policy) {
 *   console.log(policy);
 * });
 *
 * //-
 * // If the callback is omitted, we'll return a Promise.
 * //-
 * bucket.iam.getPolicy().then(function(data) {
 *   const policy = data[0];
 *   const apiResponse = data[1];
 * });
 *
 * ```
 * @example <caption>include:samples/iam.js</caption>
 * region_tag:storage_view_bucket_iam_members
 * Example of retrieving a bucket's IAM policy:
 *
 * @example <caption>include:samples/iam.js</caption>
 * region_tag:storage_add_bucket_iam_member
 * Example of adding to a bucket's IAM policy:
 *
 * @example <caption>include:samples/iam.js</caption>
 * region_tag:storage_remove_bucket_iam_member
 * Example of removing from a bucket's IAM policy:
 */
/**
 * Cloud Storage uses access control lists (ACLs) to manage object and
 * bucket access. ACLs are the mechanism you use to share objects with other
 * users and allow other users to access your buckets and objects.
 *
 * An ACL consists of one or more entries, where each entry grants permissions
 * to an entity. Permissions define the actions that can be performed against
 * an object or bucket (for example, `READ` or `WRITE`); the entity defines
 * who the permission applies to (for example, a specific user or group of
 * users).
 *
 * The `acl` object on a Bucket instance provides methods to get you a list of
 * the ACLs defined on your bucket, as well as set, update, and delete them.
 *
 * Buckets also have
 * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs}
 * for all created files. Default ACLs specify permissions that all new
 * objects added to the bucket will inherit by default. You can add, delete,
 * get, and update entities and permissions for these as well with
 * {@link Bucket#acl.default}.
 *
 * See {@link http://goo.gl/6qBBPO| About Access Control Lists}
 * See {@link https://cloud.google.com/storage/docs/access-control/lists#default| Default ACLs}
 *
 * @name Bucket#acl
 * @mixes Acl
 * @property {Acl} default Cloud Storage Buckets have
 * {@link https://cloud.google.com/storage/docs/access-control/lists#default| default ACLs}
 * for all created files. You can add, delete, get, and update entities and
 * permissions for these as well. The method signatures and examples are all
 * the same, after only prefixing the method call with `default`.
 *
 * @example
 * ```
 * const {Storage} = require('@google-cloud/storage');
 * const storage = new Storage();
 *
 * //-
 * // Make a bucket's contents publicly readable.
 * //-
 * const myBucket = storage.bucket('my-bucket');
 *
 * const options = {
 *   entity: 'allUsers',
 *   role: storage.acl.READER_ROLE
 * };
 *
 * myBucket.acl.add(options, function(err, aclObject) {});
 *
 * //-
 * // If the callback is omitted, we'll return a Promise.
 * //-
 * myBucket.acl.add(options).then(function(data) {
 *   const aclObject = data[0];
 *   const apiResponse = data[1];
 * });
 *
 * ```
 * @example <caption>include:samples/acl.js</caption>
 * region_tag:storage_print_bucket_acl
 * Example of printing a bucket's ACL:
 *
 * @example <caption>include:samples/acl.js</caption>
 * region_tag:storage_print_bucket_acl_for_user
 * Example of printing a bucket's ACL for a specific user:
 *
 * @example <caption>include:samples/acl.js</caption>
 * region_tag:storage_add_bucket_owner
 * Example of adding an owner to a bucket:
 *
 * @example <caption>include:samples/acl.js</caption>
 * region_tag:storage_remove_bucket_owner
 * Example of removing an owner from a bucket:
 *
 * @example <caption>include:samples/acl.js</caption>
 * region_tag:storage_add_bucket_default_owner
 * Example of adding a default owner to a bucket:
 *
 * @example <caption>include:samples/acl.js</caption>
 * region_tag:storage_remove_bucket_default_owner
 * Example of removing a default owner from a bucket:
 */
/**
 * The API-formatted resource description of the bucket.
 *
 * Note: This is not guaranteed to be up-to-date when accessed. To get the
 * latest record, call the `getMetadata()` method.
 *
 * @name Bucket#metadata
 * @type {object}
 */
/**
 * The bucket's name.
 * @name Bucket#name
 * @type {string}
 */
/**
 * Get {@link File} objects for the files currently in the bucket as a
 * readable object stream.
 *
 * @method Bucket#getFilesStream
 * @param {GetFilesOptions} [query] Query object for listing files.
 * @returns {ReadableStream} A readable stream that emits {@link File} instances.
 *
 * @example
 * ```
 * const {Storage} = require('@google-cloud/storage');
 * const storage = new Storage();
 * const bucket = storage.bucket('albums');
 *
 * bucket.getFilesStream()
 *   .on('error', console.error)
 *   .on('data', function(file) {
 *     // file is a File object.
 *   })
 *   .on('end', function() {
 *     // All files retrieved.
 *   });
 *
 * //-
 * // If you anticipate many results, you can end a stream early to prevent
 * // unnecessary processing and API requests.
 * //-
 * bucket.getFilesStream()
 *   .on('data', function(file) {
 *     this.end();
 *   });
 *
 * //-
 * // If you're filtering files with a delimiter, you should use
 * // {@link Bucket#getFiles} and set `autoPaginate: false` in order to
 * // preserve the `apiResponse` argument.
 * //-
 * const prefixes = [];
 *
 * function callback(err, files, nextQuery, apiResponse) {
 *   prefixes = prefixes.concat(apiResponse.prefixes);
 *
 *   if (nextQuery) {
 *     bucket.getFiles(nextQuery, callback);
 *   } else {
 *     // prefixes = The finished array of prefixes.
 *   }
 * }
 *
 * bucket.getFiles({
 *   autoPaginate: false,
 *   delimiter: '/'
 * }, callback);
 * ```
 */
/**
 * Create a Bucket object to interact with a Cloud Storage bucket.
 *
 * @class
 * @hideconstructor
 *
 * @param {Storage} storage A {@link Storage} instance.
 * @param {string} name The name of the bucket.
 * @param {object} [options] Configuration object.
 * @param {string} [options.userProject] User project.
 *
 * @example
 * ```
 * const {Storage} = require('@google-cloud/storage');
 * const storage = new Storage();
 * const bucket = storage.bucket('albums');
 * ```
 */
class Bucket extends nodejs_common_1.ServiceObject {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    getFilesStream(query) {
        // placeholder body, overwritten in constructor
        return new stream_1.Readable();
    }
    constructor(storage, name, options) {
        var _a, _b, _c, _d;
        options = options || {};
        // Allow for "gs://"-style input, and strip any trailing slashes.
        name = name.replace(/^gs:\/\//, '').replace(/\/+$/, '');
        const requestQueryObject = {};
        if ((_a = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) {
            requestQueryObject.ifGenerationMatch =
                options.preconditionOpts.ifGenerationMatch;
        }
        if ((_b = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationNotMatch) {
            requestQueryObject.ifGenerationNotMatch =
                options.preconditionOpts.ifGenerationNotMatch;
        }
        if ((_c = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _c === void 0 ? void 0 : _c.ifMetagenerationMatch) {
            requestQueryObject.ifMetagenerationMatch =
                options.preconditionOpts.ifMetagenerationMatch;
        }
        if ((_d = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _d === void 0 ? void 0 : _d.ifMetagenerationNotMatch) {
            requestQueryObject.ifMetagenerationNotMatch =
                options.preconditionOpts.ifMetagenerationNotMatch;
        }
        const userProject = options.userProject;
        if (typeof userProject === 'string') {
            requestQueryObject.userProject = userProject;
        }
        const methods = {
            /**
             * Create a bucket.
             *
             * @method Bucket#create
             * @param {CreateBucketRequest} [metadata] Metadata to set for the bucket.
             * @param {CreateBucketCallback} [callback] Callback function.
             * @returns {Promise<CreateBucketResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const bucket = storage.bucket('albums');
             * bucket.create(function(err, bucket, apiResponse) {
             *   if (!err) {
             *     // The bucket was created successfully.
             *   }
             * });
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * bucket.create().then(function(data) {
             *   const bucket = data[0];
             *   const apiResponse = data[1];
             * });
             * ```
             */
            create: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
            /**
             * IamDeleteBucketOptions Configuration options.
             * @property {boolean} [ignoreNotFound = false] Ignore an error if
             *     the bucket does not exist.
             * @property {string} [userProject] The ID of the project which will be
             *     billed for the request.
             */
            /**
             * @typedef {array} DeleteBucketResponse
             * @property {object} 0 The full API response.
             */
            /**
             * @callback DeleteBucketCallback
             * @param {?Error} err Request error, if any.
             * @param {object} apiResponse The full API response.
             */
            /**
             * Delete the bucket.
             *
             * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/delete| Buckets: delete API Documentation}
             *
             * @method Bucket#delete
             * @param {DeleteBucketOptions} [options] Configuration options.
             * @param {boolean} [options.ignoreNotFound = false] Ignore an error if
             *     the bucket does not exist.
             * @param {string} [options.userProject] The ID of the project which will be
             *     billed for the request.
             * @param {DeleteBucketCallback} [callback] Callback function.
             * @returns {Promise<DeleteBucketResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const bucket = storage.bucket('albums');
             * bucket.delete(function(err, apiResponse) {});
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * bucket.delete().then(function(data) {
             *   const apiResponse = data[0];
             * });
             *
             * ```
             * @example <caption>include:samples/buckets.js</caption>
             * region_tag:storage_delete_bucket
             * Another example:
             */
            delete: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
            /**
             * @typedef {object} BucketExistsOptions Configuration options for Bucket#exists().
             * @property {string} [userProject] The ID of the project which will be
             *     billed for the request.
             */
            /**
             * @typedef {array} BucketExistsResponse
             * @property {boolean} 0 Whether the {@link Bucket} exists.
             */
            /**
             * @callback BucketExistsCallback
             * @param {?Error} err Request error, if any.
             * @param {boolean} exists Whether the {@link Bucket} exists.
             */
            /**
             * Check if the bucket exists.
             *
             * @method Bucket#exists
             * @param {BucketExistsOptions} [options] Configuration options.
             * @param {string} [options.userProject] The ID of the project which will be
             *     billed for the request.
             * @param {BucketExistsCallback} [callback] Callback function.
             * @returns {Promise<BucketExistsResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const bucket = storage.bucket('albums');
             *
             * bucket.exists(function(err, exists) {});
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * bucket.exists().then(function(data) {
             *   const exists = data[0];
             * });
             * ```
             */
            exists: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
            /**
             * @typedef {object} [GetBucketOptions] Configuration options for Bucket#get()
             * @property {boolean} [autoCreate] Automatically create the object if
             *     it does not exist. Default: `false`
             * @property {string} [userProject] The ID of the project which will be
             *     billed for the request.
             */
            /**
             * @typedef {array} GetBucketResponse
             * @property {Bucket} 0 The {@link Bucket}.
             * @property {object} 1 The full API response.
             */
            /**
             * @callback GetBucketCallback
             * @param {?Error} err Request error, if any.
             * @param {Bucket} bucket The {@link Bucket}.
             * @param {object} apiResponse The full API response.
             */
            /**
             * Get a bucket if it exists.
             *
             * You may optionally use this to "get or create" an object by providing
             * an object with `autoCreate` set to `true`. Any extra configuration that
             * is normally required for the `create` method must be contained within
             * this object as well.
             *
             * @method Bucket#get
             * @param {GetBucketOptions} [options] Configuration options.
             * @param {boolean} [options.autoCreate] Automatically create the object if
             *     it does not exist. Default: `false`
             * @param {string} [options.userProject] The ID of the project which will be
             *     billed for the request.
             * @param {GetBucketCallback} [callback] Callback function.
             * @returns {Promise<GetBucketResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const bucket = storage.bucket('albums');
             *
             * bucket.get(function(err, bucket, apiResponse) {
             *   // `bucket.metadata` has been populated.
             * });
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * bucket.get().then(function(data) {
             *   const bucket = data[0];
             *   const apiResponse = data[1];
             * });
             * ```
             */
            get: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
            /**
             * @typedef {array} GetBucketMetadataResponse
             * @property {object} 0 The bucket metadata.
             * @property {object} 1 The full API response.
             */
            /**
             * @callback GetBucketMetadataCallback
             * @param {?Error} err Request error, if any.
             * @param {object} metadata The bucket metadata.
             * @param {object} apiResponse The full API response.
             */
            /**
             * @typedef {object} GetBucketMetadataOptions Configuration options for Bucket#getMetadata().
             * @property {string} [userProject] The ID of the project which will be
             *     billed for the request.
             */
            /**
             * Get the bucket's metadata.
             *
             * To set metadata, see {@link Bucket#setMetadata}.
             *
             * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/get| Buckets: get API Documentation}
             *
             * @method Bucket#getMetadata
             * @param {GetBucketMetadataOptions} [options] Configuration options.
             * @param {string} [options.userProject] The ID of the project which will be
             *     billed for the request.
             * @param {GetBucketMetadataCallback} [callback] Callback function.
             * @returns {Promise<GetBucketMetadataResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const bucket = storage.bucket('albums');
             *
             * bucket.getMetadata(function(err, metadata, apiResponse) {});
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * bucket.getMetadata().then(function(data) {
             *   const metadata = data[0];
             *   const apiResponse = data[1];
             * });
             *
             * ```
             * @example <caption>include:samples/requesterPays.js</caption>
             * region_tag:storage_get_requester_pays_status
             * Example of retrieving the requester pays status of a bucket:
             */
            getMetadata: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
            /**
             * @typedef {object} SetBucketMetadataOptions Configuration options for Bucket#setMetadata().
             * @property {string} [userProject] The ID of the project which will be
             *     billed for the request.
             */
            /**
             * @typedef {array} SetBucketMetadataResponse
             * @property {object} apiResponse The full API response.
             */
            /**
             * @callback SetBucketMetadataCallback
             * @param {?Error} err Request error, if any.
             * @param {object} metadata The bucket metadata.
             */
            /**
             * Set the bucket's metadata.
             *
             * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation}
             *
             * @method Bucket#setMetadata
             * @param {object<string, *>} metadata The metadata you wish to set.
             * @param {SetBucketMetadataOptions} [options] Configuration options.
             * @param {string} [options.userProject] The ID of the project which will be
             *     billed for the request.
             * @param {SetBucketMetadataCallback} [callback] Callback function.
             * @returns {Promise<SetBucketMetadataResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const bucket = storage.bucket('albums');
             *
             * //-
             * // Set website metadata field on the bucket.
             * //-
             * const metadata = {
             *   website: {
             *     mainPageSuffix: 'http://example.com',
             *     notFoundPage: 'http://example.com/404.html'
             *   }
             * };
             *
             * bucket.setMetadata(metadata, function(err, apiResponse) {});
             *
             * //-
             * // Enable versioning for your bucket.
             * //-
             * bucket.setMetadata({
             *   versioning: {
             *     enabled: true
             *   }
             * }, function(err, apiResponse) {});
             *
             * //-
             * // Enable KMS encryption for objects within this bucket.
             * //-
             * bucket.setMetadata({
             *   encryption: {
             *     defaultKmsKeyName: 'projects/grape-spaceship-123/...'
             *   }
             * }, function(err, apiResponse) {});
             *
             * //-
             * // Set the default event-based hold value for new objects in this
             * // bucket.
             * //-
             * bucket.setMetadata({
             *   defaultEventBasedHold: true
             * }, function(err, apiResponse) {});
             *
             * //-
             * // Remove object lifecycle rules.
             * //-
             * bucket.setMetadata({
             *   lifecycle: null
             * }, function(err, apiResponse) {});
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * bucket.setMetadata(metadata).then(function(data) {
             *   const apiResponse = data[0];
             * });
             * ```
             */
            setMetadata: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
        };
        super({
            parent: storage,
            baseUrl: '/b',
            id: name,
            createMethod: storage.createBucket.bind(storage),
            methods,
        });
        this.name = name;
        this.storage = storage;
        this.userProject = options.userProject;
        this.acl = new acl_1.Acl({
            request: this.request.bind(this),
            pathPrefix: '/acl',
        });
        this.acl.default = new acl_1.Acl({
            request: this.request.bind(this),
            pathPrefix: '/defaultObjectAcl',
        });
        this.crc32cGenerator =
            options.crc32cGenerator || this.storage.crc32cGenerator;
        this.iam = new iam_1.Iam(this);
        this.getFilesStream = paginator_1.paginator.streamify('getFiles');
        this.instanceRetryValue = storage.retryOptions.autoRetry;
        this.instancePreconditionOpts = options === null || options === void 0 ? void 0 : options.preconditionOpts;
    }
    /**
     * The bucket's Cloud Storage URI (`gs://`)
     *
     * @example
     * ```ts
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('my-bucket');
     *
     * // `gs://my-bucket`
     * const href = bucket.cloudStorageURI.href;
     * ```
     */
    get cloudStorageURI() {
        const uri = new url_1.URL('gs://');
        uri.host = this.name;
        return uri;
    }
    /**
     * @typedef {object} AddLifecycleRuleOptions Configuration options for Bucket#addLifecycleRule().
     * @property {boolean} [append=true] The new rules will be appended to any
     *     pre-existing rules.
     */
    /**
     *
     * @typedef {object} LifecycleRule The new lifecycle rule to be added to objects
     *     in this bucket.
     * @property {string|object} action The action to be taken upon matching of
     *     all the conditions 'delete', 'setStorageClass', or 'AbortIncompleteMultipartUpload'.
     *     **Note**: For configuring a raw-formatted rule object to be passed as `action`
     *               please refer to the [examples]{@link https://cloud.google.com/storage/docs/managing-lifecycles#configexamples}.
     * @property {object} condition Condition a bucket must meet before the
     *     action occurs on the bucket. Refer to following supported [conditions]{@link https://cloud.google.com/storage/docs/lifecycle#conditions}.
     * @property {string} [storageClass] When using the `setStorageClass`
     *     action, provide this option to dictate which storage class the object
     *     should update to. Please see
     *     [SetStorageClass option documentation]{@link https://cloud.google.com/storage/docs/lifecycle#setstorageclass} for supported transitions.
     */
    /**
     * Add an object lifecycle management rule to the bucket.
     *
     * By default, an Object Lifecycle Management rule provided to this method
     * will be included to the existing policy. To replace all existing rules,
     * supply the `options` argument, setting `append` to `false`.
     *
     * To add multiple rules, pass a list to the `rule` parameter. Calling this
     * function multiple times asynchronously does not guarantee that all rules
     * are added correctly.
     *
     * See {@link https://cloud.google.com/storage/docs/lifecycle| Object Lifecycle Management}
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation}
     *
     * @param {LifecycleRule|LifecycleRule[]} rule The new lifecycle rule or rules to be added to objects
     *     in this bucket.
     * @param {string|object} rule.action The action to be taken upon matching of
     *     all the conditions 'delete', 'setStorageClass', or 'AbortIncompleteMultipartUpload'.
     *     **Note**: For configuring a raw-formatted rule object to be passed as `action`
     *               please refer to the [examples]{@link https://cloud.google.com/storage/docs/managing-lifecycles#configexamples}.
     * @param {object} rule.condition Condition a bucket must meet before the
     *     action occurson the bucket. Refer to followitn supported [conditions]{@link https://cloud.google.com/storage/docs/lifecycle#conditions}.
     * @param {string} [rule.storageClass] When using the `setStorageClass`
     *     action, provide this option to dictate which storage class the object
     *     should update to.
     * @param {AddLifecycleRuleOptions} [options] Configuration object.
     * @param {boolean} [options.append=true] Append the new rule to the existing
     *     policy.
     * @param {SetBucketMetadataCallback} [callback] Callback function.
     * @returns {Promise<SetBucketMetadataResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * //-
     * // Automatically have an object deleted from this bucket once it is 3 years
     * // of age.
     * //-
     * bucket.addLifecycleRule({
     *   action: 'delete',
     *   condition: {
     *     age: 365 * 3 // Specified in days.
     *   }
     * }, function(err, apiResponse) {
     *   if (err) {
     *     // Error handling omitted.
     *   }
     *
     *   const lifecycleRules = bucket.metadata.lifecycle.rule;
     *
     *   // Iterate over the Object Lifecycle Management rules on this bucket.
     *   lifecycleRules.forEach(lifecycleRule => {});
     * });
     *
     * //-
     * // By default, the rule you provide will be added to the existing policy.
     * // Optionally, you can disable this behavior to replace all of the
     * // pre-existing rules.
     * //-
     * const options = {
     *   append: false
     * };
     *
     * bucket.addLifecycleRule({
     *   action: 'delete',
     *   condition: {
     *     age: 365 * 3 // Specified in days.
     *   }
     * }, options, function(err, apiResponse) {
     *   if (err) {
     *     // Error handling omitted.
     *   }
     *
     *   // All rules have been replaced with the new "delete" rule.
     *
     *   // Iterate over the Object Lifecycle Management rules on this bucket.
     *   lifecycleRules.forEach(lifecycleRule => {});
     * });
     *
     * //-
     * // For objects created before 2018, "downgrade" the storage class.
     * //-
     * bucket.addLifecycleRule({
     *   action: 'setStorageClass',
     *   storageClass: 'COLDLINE',
     *   condition: {
     *     createdBefore: new Date('2018')
     *   }
     * }, function(err, apiResponse) {});
     *
     * //-
     * // Delete objects created before 2016 which have the Coldline storage
     * // class.
     * //-
     * bucket.addLifecycleRule({
     *   action: 'delete',
     *   condition: {
     *     matchesStorageClass: [
     *       'COLDLINE'
     *     ],
     *     createdBefore: new Date('2016')
     *   }
     * }, function(err, apiResponse) {});
     *
     * //-
     * // Delete object that has a noncurrent timestamp that is at least 100 days.
     * //-
     * bucket.addLifecycleRule({
     *   action: 'delete',
     *   condition: {
     *     daysSinceNoncurrentTime: 100
     *   }
     * }, function(err, apiResponse) {});
     *
     * //-
     * // Delete object that has a noncurrent timestamp before 2020-01-01.
     * //-
     * bucket.addLifecycleRule({
     *   action: 'delete',
     *   condition: {
     *     noncurrentTimeBefore: new Date('2020-01-01')
     *   }
     * }, function(err, apiResponse) {});
     *
     * //-
     * // Delete object that has a customTime that is at least 100 days.
     * //-
     * bucket.addLifecycleRule({
     *   action: 'delete',
     *   condition: {
     *     daysSinceCustomTime: 100
     *   }
     * }, function(err, apiResponse) ());
     *
     * //-
     * // Delete object that has a customTime before 2020-01-01.
     * //-
     * bucket.addLifecycleRule({
     *   action: 'delete',
     *   condition: {
     *     customTimeBefore: new Date('2020-01-01')
     *   }
     * }, function(err, apiResponse) {});
     * ```
     */
    addLifecycleRule(rule, optionsOrCallback, callback) {
        let options = {};
        if (typeof optionsOrCallback === 'function') {
            callback = optionsOrCallback;
        }
        else if (optionsOrCallback) {
            options = optionsOrCallback;
        }
        options = options || {};
        const rules = Array.isArray(rule) ? rule : [rule];
        const newLifecycleRules = rules.map(rule => {
            if (typeof rule.action === 'object') {
                // This is a raw-formatted rule object, the way the API expects.
                // Just pass it through as-is.
                return rule;
            }
            const apiFormattedRule = {};
            apiFormattedRule.condition = {};
            apiFormattedRule.action = {
                type: rule.action.charAt(0).toUpperCase() + rule.action.slice(1),
            };
            if (rule.storageClass) {
                apiFormattedRule.action.storageClass = rule.storageClass;
            }
            for (const condition in rule.condition) {
                if (rule.condition[condition] instanceof Date) {
                    apiFormattedRule.condition[condition] = rule.condition[condition]
                        .toISOString()
                        .replace(/T.+$/, '');
                }
                else {
                    apiFormattedRule.condition[condition] = rule.condition[condition];
                }
            }
            return apiFormattedRule;
        });
        if (options.append === false) {
            this.setMetadata({ lifecycle: { rule: newLifecycleRules } }, options, callback);
            return;
        }
        // The default behavior appends the previously-defined lifecycle rules with
        // the new ones just passed in by the user.
        this.getMetadata((err, metadata) => {
            if (err) {
                callback(err);
                return;
            }
            const currentLifecycleRules = Array.isArray(metadata.lifecycle && metadata.lifecycle.rule)
                ? metadata.lifecycle && metadata.lifecycle.rule
                : [];
            this.setMetadata({
                lifecycle: {
                    rule: currentLifecycleRules.concat(newLifecycleRules),
                },
            }, options, callback);
        });
    }
    /**
     * @typedef {object} CombineOptions
     * @property {string} [kmsKeyName] Resource name of the Cloud KMS key, of
     *     the form
     *     `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`,
     *     that will be used to encrypt the object. Overwrites the object
     * metadata's `kms_key_name` value, if any.
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * @callback CombineCallback
     * @param {?Error} err Request error, if any.
     * @param {File} newFile The new {@link File}.
     * @param {object} apiResponse The full API response.
     */
    /**
     * @typedef {array} CombineResponse
     * @property {File} 0 The new {@link File}.
     * @property {object} 1 The full API response.
     */
    /**
     * Combine multiple files into one new file.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/compose| Objects: compose API Documentation}
     *
     * @throws {Error} if a non-array is provided as sources argument.
     * @throws {Error} if no sources are provided.
     * @throws {Error} if no destination is provided.
     *
     * @param {string[]|File[]} sources The source files that will be
     *     combined.
     * @param {string|File} destination The file you would like the
     *     source files combined into.
     * @param {CombineOptions} [options] Configuration options.
     * @param {string} [options.kmsKeyName] Resource name of the Cloud KMS key, of
     *     the form
     *     `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`,
     *     that will be used to encrypt the object. Overwrites the object
     * metadata's `kms_key_name` value, if any.
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for the request.
  
     * @param {CombineCallback} [callback] Callback function.
     * @returns {Promise<CombineResponse>}
     *
     * @example
     * ```
     * const logBucket = storage.bucket('log-bucket');
     *
     * const sources = [
     *   logBucket.file('2013-logs.txt'),
     *   logBucket.file('2014-logs.txt')
     * ];
     *
     * const allLogs = logBucket.file('all-logs.txt');
     *
     * logBucket.combine(sources, allLogs, function(err, newFile, apiResponse) {
     *   // newFile === allLogs
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * logBucket.combine(sources, allLogs).then(function(data) {
     *   const newFile = data[0];
     *   const apiResponse = data[1];
     * });
     * ```
     */
    combine(sources, destination, optionsOrCallback, callback) {
        var _a;
        if (!Array.isArray(sources) || sources.length === 0) {
            throw new Error(BucketExceptionMessages.PROVIDE_SOURCE_FILE);
        }
        if (!destination) {
            throw new Error(BucketExceptionMessages.DESTINATION_FILE_NOT_SPECIFIED);
        }
        let options = {};
        if (typeof optionsOrCallback === 'function') {
            callback = optionsOrCallback;
        }
        else if (optionsOrCallback) {
            options = optionsOrCallback;
        }
        this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, // Not relevant but param is required
        AvailableServiceObjectMethods.setMetadata, // Same as above
        options);
        const convertToFile = (file) => {
            if (file instanceof file_1.File) {
                return file;
            }
            return this.file(file);
        };
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        sources = sources.map(convertToFile);
        const destinationFile = convertToFile(destination);
        callback = callback || nodejs_common_1.util.noop;
        if (!destinationFile.metadata.contentType) {
            const destinationContentType = mime.contentType(destinationFile.name);
            if (destinationContentType) {
                destinationFile.metadata.contentType = destinationContentType;
            }
        }
        let maxRetries = this.storage.retryOptions.maxRetries;
        if ((((_a = destinationFile === null || destinationFile === void 0 ? void 0 : destinationFile.instancePreconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) ===
            undefined &&
            options.ifGenerationMatch === undefined &&
            this.storage.retryOptions.idempotencyStrategy ===
                storage_1.IdempotencyStrategy.RetryConditional) ||
            this.storage.retryOptions.idempotencyStrategy ===
                storage_1.IdempotencyStrategy.RetryNever) {
            maxRetries = 0;
        }
        if (options.ifGenerationMatch === undefined) {
            Object.assign(options, destinationFile.instancePreconditionOpts, options);
        }
        // Make the request from the destination File object.
        destinationFile.request({
            method: 'POST',
            uri: '/compose',
            maxRetries,
            json: {
                destination: {
                    contentType: destinationFile.metadata.contentType,
                },
                sourceObjects: sources.map(source => {
                    const sourceObject = {
                        name: source.name,
                    };
                    if (source.metadata && source.metadata.generation) {
                        sourceObject.generation = source.metadata.generation;
                    }
                    return sourceObject;
                }),
            },
            qs: options,
        }, (err, resp) => {
            this.storage.retryOptions.autoRetry = this.instanceRetryValue;
            if (err) {
                callback(err, null, resp);
                return;
            }
            callback(null, destinationFile, resp);
        });
    }
    /**
     * See a {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll request body}.
     *
     * @typedef {object} CreateChannelConfig
     * @property {string} address The address where notifications are
     *     delivered for this channel.
     * @property {string} [delimiter] Returns results in a directory-like mode.
     * @property {number} [maxResults] Maximum number of `items` plus `prefixes`
     *     to return in a single page of responses.
     * @property {string} [pageToken] A previously-returned page token
     *     representing part of the larger set of results to view.
     * @property {string} [prefix] Filter results to objects whose names begin
     *     with this prefix.
     * @property {string} [projection=noAcl] Set of properties to return.
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     * @property {boolean} [versions=false] If `true`, lists all versions of an object
     *     as distinct results.
     */
    /**
     * @typedef {object} CreateChannelOptions
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * @typedef {array} CreateChannelResponse
     * @property {Channel} 0 The new {@link Channel}.
     * @property {object} 1 The full API response.
     */
    /**
     * @callback CreateChannelCallback
     * @param {?Error} err Request error, if any.
     * @param {Channel} channel The new {@link Channel}.
     * @param {object} apiResponse The full API response.
     */
    /**
     * Create a channel that will be notified when objects in this bucket changes.
     *
     * @throws {Error} If an ID is not provided.
     * @throws {Error} If an address is not provided.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/watchAll| Objects: watchAll API Documentation}
     *
     * @param {string} id The ID of the channel to create.
     * @param {CreateChannelConfig} config Configuration for creating channel.
     * @param {string} config.address The address where notifications are
     *     delivered for this channel.
     * @param {string} [config.delimiter] Returns results in a directory-like mode.
     * @param {number} [config.maxResults] Maximum number of `items` plus `prefixes`
     *     to return in a single page of responses.
     * @param {string} [config.pageToken] A previously-returned page token
     *     representing part of the larger set of results to view.
     * @param {string} [config.prefix] Filter results to objects whose names begin
     *     with this prefix.
     * @param {string} [config.projection=noAcl] Set of properties to return.
     * @param {string} [config.userProject] The ID of the project which will be
     *     billed for the request.
     * @param {boolean} [config.versions=false] If `true`, lists all versions of an object
     *     as distinct results.
     * @param {CreateChannelOptions} [options] Configuration options.
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for the request.
     * @param {CreateChannelCallback} [callback] Callback function.
     * @returns {Promise<CreateChannelResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     * const id = 'new-channel-id';
     *
     * const config = {
     *   address: 'https://...'
     * };
     *
     * bucket.createChannel(id, config, function(err, channel, apiResponse) {
     *   if (!err) {
     *     // Channel created successfully.
     *   }
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.createChannel(id, config).then(function(data) {
     *   const channel = data[0];
     *   const apiResponse = data[1];
     * });
     * ```
     */
    createChannel(id, config, optionsOrCallback, callback) {
        if (typeof id !== 'string') {
            throw new Error(BucketExceptionMessages.CHANNEL_ID_REQUIRED);
        }
        if (typeof config.address !== 'string') {
            throw new Error(BucketExceptionMessages.CHANNEL_ADDRESS_REQUIRED);
        }
        let options = {};
        if (typeof optionsOrCallback === 'function') {
            callback = optionsOrCallback;
        }
        else if (optionsOrCallback) {
            options = optionsOrCallback;
        }
        this.request({
            method: 'POST',
            uri: '/o/watch',
            json: Object.assign({
                id,
                type: 'web_hook',
            }, config),
            qs: options,
        }, (err, apiResponse) => {
            if (err) {
                callback(err, null, apiResponse);
                return;
            }
            const resourceId = apiResponse.resourceId;
            const channel = this.storage.channel(id, resourceId);
            channel.metadata = apiResponse;
            callback(null, channel, apiResponse);
        });
    }
    /**
     * Metadata to set for the Notification.
     *
     * @typedef {object} CreateNotificationOptions
     * @property {object} [customAttributes] An optional list of additional
     *     attributes to attach to each Cloud PubSub message published for this
     *     notification subscription.
     * @property {string[]} [eventTypes] If present, only send notifications about
     *     listed event types. If empty, sent notifications for all event types.
     * @property {string} [objectNamePrefix] If present, only apply this
     *     notification configuration to object names that begin with this prefix.
     * @property {string} [payloadFormat] The desired content of the Payload.
     * Defaults to `JSON_API_V1`.
     *
     * Acceptable values are:
     * - `JSON_API_V1`
     *
     * - `NONE`
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * @callback CreateNotificationCallback
     * @param {?Error} err Request error, if any.
     * @param {Notification} notification The new {@link Notification}.
     * @param {object} apiResponse The full API response.
     */
    /**
     * @typedef {array} CreateNotificationResponse
     * @property {Notification} 0 The new {@link Notification}.
     * @property {object} 1 The full API response.
     */
    /**
     * Creates a notification subscription for the bucket.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/insert| Notifications: insert}
     *
     * @param {Topic|string} topic The Cloud PubSub topic to which this
     * subscription publishes. If the project ID is omitted, the current
     * project ID will be used.
     *
     * Acceptable formats are:
     * - `projects/grape-spaceship-123/topics/my-topic`
     *
     * - `my-topic`
     * @param {CreateNotificationOptions} [options] Metadata to set for the
     *     notification.
     * @param {object} [options.customAttributes] An optional list of additional
     *     attributes to attach to each Cloud PubSub message published for this
     *     notification subscription.
     * @param {string[]} [options.eventTypes] If present, only send notifications about
     *     listed event types. If empty, sent notifications for all event types.
     * @param {string} [options.objectNamePrefix] If present, only apply this
     *     notification configuration to object names that begin with this prefix.
     * @param {string} [options.payloadFormat] The desired content of the Payload.
     * Defaults to `JSON_API_V1`.
     *
     * Acceptable values are:
     * - `JSON_API_V1`
     *
     * - `NONE`
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for the request.
     * @param {CreateNotificationCallback} [callback] Callback function.
     * @returns {Promise<CreateNotificationResponse>}
     * @throws {Error} If a valid topic is not provided.
     * @see Notification#create
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const callback = function(err, notification, apiResponse) {
     *   if (!err) {
     *     // The notification was created successfully.
     *   }
     * };
     *
     * myBucket.createNotification('my-topic', callback);
     *
     * //-
     * // Configure the nofiication by providing Notification metadata.
     * //-
     * const metadata = {
     *   objectNamePrefix: 'prefix-'
     * };
     *
     * myBucket.createNotification('my-topic', metadata, callback);
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * myBucket.createNotification('my-topic').then(function(data) {
     *   const notification = data[0];
     *   const apiResponse = data[1];
     * });
     *
     * ```
     * @example <caption>include:samples/createNotification.js</caption>
     * region_tag:storage_create_bucket_notifications
     * Another example:
     */
    createNotification(topic, optionsOrCallback, callback) {
        let options = {};
        if (typeof optionsOrCallback === 'function') {
            callback = optionsOrCallback;
        }
        else if (optionsOrCallback) {
            options = optionsOrCallback;
        }
        const topicIsObject = topic !== null && typeof topic === 'object';
        if (topicIsObject && nodejs_common_1.util.isCustomType(topic, 'pubsub/topic')) {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            topic = topic.name;
        }
        if (typeof topic !== 'string') {
            throw new Error(BucketExceptionMessages.TOPIC_NAME_REQUIRED);
        }
        const body = Object.assign({ topic }, options);
        if (body.topic.indexOf('projects') !== 0) {
            body.topic = 'projects/{{projectId}}/topics/' + body.topic;
        }
        body.topic = '//pubsub.googleapis.com/' + body.topic;
        if (!body.payloadFormat) {
            body.payloadFormat = 'JSON_API_V1';
        }
        const query = {};
        if (body.userProject) {
            query.userProject = body.userProject;
            delete body.userProject;
        }
        this.request({
            method: 'POST',
            uri: '/notificationConfigs',
            json: (0, util_2.convertObjKeysToSnakeCase)(body),
            qs: query,
            maxRetries: 0, //explicitly set this value since this is a non-idempotent function
        }, (err, apiResponse) => {
            if (err) {
                callback(err, null, apiResponse);
                return;
            }
            const notification = this.notification(apiResponse.id);
            notification.metadata = apiResponse;
            callback(null, notification, apiResponse);
        });
    }
    /**
     * @typedef {object} DeleteFilesOptions Query object. See {@link Bucket#getFiles}
     *     for all of the supported properties.
     * @property {boolean} [force] Suppress errors until all files have been
     *     processed.
     */
    /**
     * @callback DeleteFilesCallback
     * @param {?Error|?Error[]} err Request error, if any, or array of errors from
     *     files that were not able to be deleted.
     * @param {object} [apiResponse] The full API response.
     */
    /**
     * Iterate over the bucket's files, calling `file.delete()` on each.
     *
     * <strong>This is not an atomic request.</strong> A delete attempt will be
     * made for each file individually. Any one can fail, in which case only a
     * portion of the files you intended to be deleted would have.
     *
     * Operations are performed in parallel, up to 10 at once. The first error
     * breaks the loop and will execute the provided callback with it. Specify
     * `{ force: true }` to suppress the errors until all files have had a chance
     * to be processed.
     *
     * File preconditions cannot be passed to this function. It will not retry unless
     * the idempotency strategy is set to retry always.
     *
     * The `query` object passed as the first argument will also be passed to
     * {@link Bucket#getFiles}.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete| Objects: delete API Documentation}
     *
     * @param {DeleteFilesOptions} [query] Query object. See {@link Bucket#getFiles}
     * @param {boolean} [query.force] Suppress errors until all files have been
     *     processed.
     * @param {DeleteFilesCallback} [callback] Callback function.
     * @returns {Promise}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * //-
     * // Delete all of the files in the bucket.
     * //-
     * bucket.deleteFiles(function(err) {});
     *
     * //-
     * // By default, if a file cannot be deleted, this method will stop deleting
     * // files from your bucket. You can override this setting with `force:
     * // true`.
     * //-
     * bucket.deleteFiles({
     *   force: true
     * }, function(errors) {
     *   // `errors`:
     *   //    Array of errors if any occurred, otherwise null.
     * });
     *
     * //-
     * // The first argument to this method acts as a query to
     * // {@link Bucket#getFiles}. As an example, you can delete files
     * // which match a prefix.
     * //-
     * bucket.deleteFiles({
     *   prefix: 'images/'
     * }, function(err) {
     *   if (!err) {
     *     // All files in the `images` directory have been deleted.
     *   }
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.deleteFiles().then(function() {});
     * ```
     */
    deleteFiles(queryOrCallback, callback) {
        let query = {};
        if (typeof queryOrCallback === 'function') {
            callback = queryOrCallback;
        }
        else if (queryOrCallback) {
            query = queryOrCallback;
        }
        const MAX_PARALLEL_LIMIT = 10;
        const MAX_QUEUE_SIZE = 1000;
        const errors = [];
        const deleteFile = (file) => {
            return file.delete(query).catch(err => {
                if (!query.force) {
                    throw err;
                }
                errors.push(err);
            });
        };
        (async () => {
            try {
                let promises = [];
                const limit = pLimit(MAX_PARALLEL_LIMIT);
                const filesStream = this.getFilesStream(query);
                for await (const curFile of filesStream) {
                    if (promises.length >= MAX_QUEUE_SIZE) {
                        await Promise.all(promises);
                        promises = [];
                    }
                    promises.push(limit(() => deleteFile(curFile)).catch(e => {
                        filesStream.destroy();
                        throw e;
                    }));
                }
                await Promise.all(promises);
                callback(errors.length > 0 ? errors : null);
            }
            catch (e) {
                callback(e);
                return;
            }
        })();
    }
    /**
     * @typedef {array} DeleteLabelsResponse
     * @property {object} 0 The full API response.
     */
    /**
     * @callback DeleteLabelsCallback
     * @param {?Error} err Request error, if any.
     * @param {object} metadata Bucket's metadata.
     */
    /**
     * Delete one or more labels from this bucket.
     *
     * @param {string|string[]} [labels] The labels to delete. If no labels are
     *     provided, all of the labels are removed.
     * @param {DeleteLabelsCallback} [callback] Callback function.
     * @param {DeleteLabelsOptions} [options] Options, including precondition options
     * @returns {Promise<DeleteLabelsResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * //-
     * // Delete all of the labels from this bucket.
     * //-
     * bucket.deleteLabels(function(err, apiResponse) {});
     *
     * //-
     * // Delete a single label.
     * //-
     * bucket.deleteLabels('labelone', function(err, apiResponse) {});
     *
     * //-
     * // Delete a specific set of labels.
     * //-
     * bucket.deleteLabels([
     *   'labelone',
     *   'labeltwo'
     * ], function(err, apiResponse) {});
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.deleteLabels().then(function(data) {
     *   const apiResponse = data[0];
     * });
     * ```
     */
    deleteLabels(labelsOrCallbackOrOptions, optionsOrCallback, callback) {
        let labels = new Array();
        let options = {};
        if (typeof labelsOrCallbackOrOptions === 'function') {
            callback = labelsOrCallbackOrOptions;
        }
        else if (typeof labelsOrCallbackOrOptions === 'string') {
            labels = [labelsOrCallbackOrOptions];
        }
        else if (Array.isArray(labelsOrCallbackOrOptions)) {
            labels = labelsOrCallbackOrOptions;
        }
        else if (labelsOrCallbackOrOptions) {
            options = labelsOrCallbackOrOptions;
        }
        if (typeof optionsOrCallback === 'function') {
            callback = optionsOrCallback;
        }
        else if (optionsOrCallback) {
            options = optionsOrCallback;
        }
        const deleteLabels = (labels) => {
            const nullLabelMap = labels.reduce((nullLabelMap, labelKey) => {
                nullLabelMap[labelKey] = null;
                return nullLabelMap;
            }, {});
            if ((options === null || options === void 0 ? void 0 : options.ifMetagenerationMatch) !== undefined) {
                this.setLabels(nullLabelMap, options, callback);
            }
            else {
                this.setLabels(nullLabelMap, callback);
            }
        };
        if (labels.length === 0) {
            this.getLabels((err, labels) => {
                if (err) {
                    callback(err);
                    return;
                }
                deleteLabels(Object.keys(labels));
            });
        }
        else {
            deleteLabels(labels);
        }
    }
    /**
     * @typedef {array} DisableRequesterPaysResponse
     * @property {object} 0 The full API response.
     */
    /**
     * @callback DisableRequesterPaysCallback
     * @param {?Error} err Request error, if any.
     * @param {object} apiResponse The full API response.
     */
    /**
     * <div class="notice">
     *   <strong>Early Access Testers Only</strong>
     *   <p>
     *     This feature is not yet widely-available.
     *   </p>
     * </div>
     *
     * Disable `requesterPays` functionality from this bucket.
     *
     * @param {DisableRequesterPaysCallback} [callback] Callback function.
     * @param {DisableRequesterPaysOptions} [options] Options, including precondition options
     * @returns {Promise<DisableRequesterPaysCallback>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * bucket.disableRequesterPays(function(err, apiResponse) {
     *   if (!err) {
     *     // requesterPays functionality disabled successfully.
     *   }
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.disableRequesterPays().then(function(data) {
     *   const apiResponse = data[0];
     * });
     *
     * ```
     * @example <caption>include:samples/requesterPays.js</caption>
     * region_tag:storage_disable_requester_pays
     * Example of disabling requester pays:
     */
    disableRequesterPays(optionsOrCallback, callback) {
        let options = {};
        if (typeof optionsOrCallback === 'function') {
            callback = optionsOrCallback;
        }
        else if (optionsOrCallback) {
            options = optionsOrCallback;
        }
        this.setMetadata({
            billing: {
                requesterPays: false,
            },
        }, options, callback);
    }
    /**
     * Configuration object for enabling logging.
     *
     * @typedef {object} EnableLoggingOptions
     * @property {string|Bucket} [bucket] The bucket for the log entries. By
     *     default, the current bucket is used.
     * @property {string} prefix A unique prefix for log object names.
     */
    /**
     * Enable logging functionality for this bucket. This will make two API
     * requests, first to grant Cloud Storage WRITE permission to the bucket, then
     * to set the appropriate configuration on the Bucket's metadata.
     *
     * @param {EnableLoggingOptions} config Configuration options.
     * @param {string|Bucket} [config.bucket] The bucket for the log entries. By
     *     default, the current bucket is used.
     * @param {string} config.prefix A unique prefix for log object names.
     * @param {SetBucketMetadataCallback} [callback] Callback function.
     * @returns {Promise<SetBucketMetadataResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * const config = {
     *   prefix: 'log'
     * };
     *
     * bucket.enableLogging(config, function(err, apiResponse) {
     *   if (!err) {
     *     // Logging functionality enabled successfully.
     *   }
     * });
     *
     * ```
     * @example
     * Optionally, provide a destination bucket.
     * ```
     * const config = {
     *   prefix: 'log',
     *   bucket: 'destination-bucket'
     * };
     *
     * bucket.enableLogging(config, function(err, apiResponse) {});
     * ```
     *
     * @example
     * If the callback is omitted, we'll return a Promise.
     * ```
     * bucket.enableLogging(config).then(function(data) {
     *   const apiResponse = data[0];
     * });
     * ```
     */
    enableLogging(config, callback) {
        if (!config ||
            typeof config === 'function' ||
            typeof config.prefix === 'undefined') {
            throw new Error(BucketExceptionMessages.CONFIGURATION_OBJECT_PREFIX_REQUIRED);
        }
        const logBucket = config.bucket
            ? config.bucket.id || config.bucket
            : this.id;
        const options = {};
        if (config === null || config === void 0 ? void 0 : config.ifMetagenerationMatch) {
            options.ifMetagenerationMatch = config.ifMetagenerationMatch;
        }
        if (config === null || config === void 0 ? void 0 : config.ifMetagenerationNotMatch) {
            options.ifMetagenerationNotMatch = config.ifMetagenerationNotMatch;
        }
        (async () => {
            try {
                const [policy] = await this.iam.getPolicy();
                policy.bindings.push({
                    members: ['group:cloud-storage-analytics@google.com'],
                    role: 'roles/storage.objectCreator',
                });
                await this.iam.setPolicy(policy);
                this.setMetadata({
                    logging: {
                        logBucket,
                        logObjectPrefix: config.prefix,
                    },
                }, options, callback);
            }
            catch (e) {
                callback(e);
                return;
            }
        })();
    }
    /**
     * @typedef {array} EnableRequesterPaysResponse
     * @property {object} 0 The full API response.
     */
    /**
     * @callback EnableRequesterPaysCallback
     * @param {?Error} err Request error, if any.
     * @param {object} apiResponse The full API response.
     */
    /**
     * <div class="notice">
     *   <strong>Early Access Testers Only</strong>
     *   <p>
     *     This feature is not yet widely-available.
     *   </p>
     * </div>
     *
     * Enable `requesterPays` functionality for this bucket. This enables you, the
     * bucket owner, to have the requesting user assume the charges for the access
     * to your bucket and its contents.
     *
     * @param {EnableRequesterPaysCallback | EnableRequesterPaysOptions} [optionsOrCallback]
     * Callback function or precondition options.
     * @returns {Promise<EnableRequesterPaysResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * bucket.enableRequesterPays(function(err, apiResponse) {
     *   if (!err) {
     *     // requesterPays functionality enabled successfully.
     *   }
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.enableRequesterPays().then(function(data) {
     *   const apiResponse = data[0];
     * });
     *
     * ```
     * @example <caption>include:samples/requesterPays.js</caption>
     * region_tag:storage_enable_requester_pays
     * Example of enabling requester pays:
     */
    enableRequesterPays(optionsOrCallback, cb) {
        let options = {};
        if (typeof optionsOrCallback === 'function') {
            cb = optionsOrCallback;
        }
        else if (optionsOrCallback) {
            options = optionsOrCallback;
        }
        this.setMetadata({
            billing: {
                requesterPays: true,
            },
        }, options, cb);
    }
    /**
     * Create a {@link File} object. See {@link File} to see how to handle
     * the different use cases you may have.
     *
     * @param {string} name The name of the file in this bucket.
     * @param {FileOptions} [options] Configuration options.
     * @param {string|number} [options.generation] Only use a specific revision of
     *     this file.
     * @param {string} [options.encryptionKey] A custom encryption key. See
     *     {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}.
     * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will
     *     be used to encrypt the object. Must be in the format:
     *     `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`.
     *     KMS key ring must use the same location as the bucket.
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for all requests made from File object.
     * @returns {File}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     * const file = bucket.file('my-existing-file.png');
     * ```
     */
    file(name, options) {
        if (!name) {
            throw Error(BucketExceptionMessages.SPECIFY_FILE_NAME);
        }
        return new file_1.File(this, name, options);
    }
    /**
     * @typedef {array} GetFilesResponse
     * @property {File[]} 0 Array of {@link File} instances.
     * @param {object} nextQuery 1 A query object to receive more results.
     * @param {object} apiResponse 2 The full API response.
     */
    /**
     * @callback GetFilesCallback
     * @param {?Error} err Request error, if any.
     * @param {File[]} files Array of {@link File} instances.
     * @param {object} nextQuery A query object to receive more results.
     * @param {object} apiResponse The full API response.
     */
    /**
     * Query object for listing files.
     *
     * @typedef {object} GetFilesOptions
     * @property {boolean} [autoPaginate=true] Have pagination handled
     *     automatically.
     * @property {string} [delimiter] Results will contain only objects whose
     *     names, aside from the prefix, do not contain delimiter. Objects whose
     *     names, aside from the prefix, contain delimiter will have their name
     *     truncated after the delimiter, returned in `apiResponse.prefixes`.
     *     Duplicate prefixes are omitted.
     * @property {string} [endOffset] Filter results to objects whose names are
     * lexicographically before endOffset. If startOffset is also set, the objects
     * listed have names between startOffset (inclusive) and endOffset (exclusive).
     * @property {boolean} [includeTrailingDelimiter] If true, objects that end in
     * exactly one instance of delimiter have their metadata included in items[]
     * in addition to the relevant part of the object name appearing in prefixes[].
     * @property {string} [prefix] Filter results to objects whose names begin
     *     with this prefix.
     * @property {string} [matchGlob] A glob pattern used to filter results,
     *     for example foo*bar
     * @property {number} [maxApiCalls] Maximum number of API calls to make.
     * @property {number} [maxResults] Maximum number of items plus prefixes to
     *     return per call.
     *     Note: By default will handle pagination automatically
     *     if more than 1 page worth of results are requested per call.
     *     When `autoPaginate` is set to `false` the smaller of `maxResults`
     *     or 1 page of results will be returned per call.
     * @property {string} [pageToken] A previously-returned page token
     *     representing part of the larger set of results to view.
     * @property {string} [startOffset] Filter results to objects whose names are
     * lexicographically equal to or after startOffset. If endOffset is also set,
     * the objects listed have names between startOffset (inclusive) and endOffset (exclusive).
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     * @property {boolean} [versions] If true, returns File objects scoped to
     *     their versions.
     */
    /**
     * Get {@link File} objects for the files currently in the bucket.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/list| Objects: list API Documentation}
     *
     * @param {GetFilesOptions} [query] Query object for listing files.
     * @param {boolean} [query.autoPaginate=true] Have pagination handled
     *     automatically.
     * @param {string} [query.delimiter] Results will contain only objects whose
     *     names, aside from the prefix, do not contain delimiter. Objects whose
     *     names, aside from the prefix, contain delimiter will have their name
     *     truncated after the delimiter, returned in `apiResponse.prefixes`.
     *     Duplicate prefixes are omitted.
     * @param {string} [query.endOffset] Filter results to objects whose names are
     * lexicographically before endOffset. If startOffset is also set, the objects
     * listed have names between startOffset (inclusive) and endOffset (exclusive).
     * @param {boolean} [query.includeTrailingDelimiter] If true, objects that end in
     * exactly one instance of delimiter have their metadata included in items[]
     * in addition to the relevant part of the object name appearing in prefixes[].
     * @param {string} [query.prefix] Filter results to objects whose names begin
     *     with this prefix.
     * @param {number} [query.maxApiCalls] Maximum number of API calls to make.
     * @param {number} [query.maxResults] Maximum number of items plus prefixes to
     *     return per call.
     *     Note: By default will handle pagination automatically
     *     if more than 1 page worth of results are requested per call.
     *     When `autoPaginate` is set to `false` the smaller of `maxResults`
     *     or 1 page of results will be returned per call.
     * @param {string} [query.pageToken] A previously-returned page token
     *     representing part of the larger set of results to view.
     * @param {string} [query.startOffset] Filter results to objects whose names are
     * lexicographically equal to or after startOffset. If endOffset is also set,
     * the objects listed have names between startOffset (inclusive) and endOffset (exclusive).
     * @param {string} [query.userProject] The ID of the project which will be
     *     billed for the request.
     * @param {boolean} [query.versions] If true, returns File objects scoped to
     *     their versions.
     * @param {GetFilesCallback} [callback] Callback function.
     * @returns {Promise<GetFilesResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * bucket.getFiles(function(err, files) {
     *   if (!err) {
     *     // files is an array of File objects.
     *   }
     * });
     *
     * //-
     * // If your bucket has versioning enabled, you can get all of your files
     * // scoped to their generation.
     * //-
     * bucket.getFiles({
     *   versions: true
     * }, function(err, files) {
     *   // Each file is scoped to its generation.
     * });
     *
     * //-
     * // To control how many API requests are made and page through the results
     * // manually, set `autoPaginate` to `false`.
     * //-
     * const callback = function(err, files, nextQuery, apiResponse) {
     *   if (nextQuery) {
     *     // More results exist.
     *     bucket.getFiles(nextQuery, callback);
     *   }
     *
     *   // The `metadata` property is populated for you with the metadata at the
     *   // time of fetching.
     *   files[0].metadata;
     *
     *   // However, in cases where you are concerned the metadata could have
     *   // changed, use the `getMetadata` method.
     *   files[0].getMetadata(function(err, metadata) {});
     * };
     *
     * bucket.getFiles({
     *   autoPaginate: false
     * }, callback);
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.getFiles().then(function(data) {
     *   const files = data[0];
     * });
     *
     * ```
     * @example
     * <h6>Simulating a File System</h6><p>With `autoPaginate: false`, it's possible to iterate over files which incorporate a common structure using a delimiter.</p><p>Consider the following remote objects:</p><ol><li>"a"</li><li>"a/b/c/d"</li><li>"b/d/e"</li></ol><p>Using a delimiter of `/` will return a single file, "a".</p><p>`apiResponse.prefixes` will return the "sub-directories" that were found:</p><ol><li>"a/"</li><li>"b/"</li></ol>
     * ```
     * bucket.getFiles({
     *   autoPaginate: false,
     *   delimiter: '/'
     * }, function(err, files, nextQuery, apiResponse) {
     *   // files = [
     *   //   {File} // File object for file "a"
     *   // ]
     *
     *   // apiResponse.prefixes = [
     *   //   'a/',
     *   //   'b/'
     *   // ]
     * });
     * ```
     *
     * @example
     * Using prefixes, it's now possible to simulate a file system with follow-up requests.
     * ```
     * bucket.getFiles({
     *   autoPaginate: false,
     *   delimiter: '/',
     *   prefix: 'a/'
     * }, function(err, files, nextQuery, apiResponse) {
     *   // No files found within "directory" a.
     *   // files = []
     *
     *   // However, a "sub-directory" was found.
     *   // This prefix can be used to continue traversing the "file system".
     *   // apiResponse.prefixes = [
     *   //   'a/b/'
     *   // ]
     * });
     * ```
     *
     * @example <caption>include:samples/files.js</caption>
     * region_tag:storage_list_files
     * Another example:
     *
     * @example <caption>include:samples/files.js</caption>
     * region_tag:storage_list_files_with_prefix
     * Example of listing files, filtered by a prefix:
     */
    getFiles(queryOrCallback, callback) {
        let query = typeof queryOrCallback === 'object' ? queryOrCallback : {};
        if (!callback) {
            callback = queryOrCallback;
        }
        query = Object.assign({}, query);
        this.request({
            uri: '/o',
            qs: query,
        }, (err, resp) => {
            if (err) {
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                callback(err, null, null, resp);
                return;
            }
            const itemsArray = resp.items ? resp.items : [];
            const files = itemsArray.map((file) => {
                const options = {};
                if (query.versions) {
                    options.generation = file.generation;
                }
                if (file.kmsKeyName) {
                    options.kmsKeyName = file.kmsKeyName;
                }
                const fileInstance = this.file(file.name, options);
                fileInstance.metadata = file;
                return fileInstance;
            });
            let nextQuery = null;
            if (resp.nextPageToken) {
                nextQuery = Object.assign({}, query, {
                    pageToken: resp.nextPageToken,
                });
            }
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            callback(null, files, nextQuery, resp);
        });
    }
    /**
     * @typedef {object} GetLabelsOptions Configuration options for Bucket#getLabels().
     * @param {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * @typedef {array} GetLabelsResponse
     * @property {object} 0 Object of labels currently set on this bucket.
     */
    /**
     * @callback GetLabelsCallback
     * @param {?Error} err Request error, if any.
     * @param {object} labels Object of labels currently set on this bucket.
     */
    /**
     * Get the labels currently set on this bucket.
     *
     * @param {object} [options] Configuration options.
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for the request.
     * @param {GetLabelsCallback} [callback] Callback function.
     * @returns {Promise<GetLabelsCallback>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * bucket.getLabels(function(err, labels) {
     *   if (err) {
     *     // Error handling omitted.
     *   }
     *
     *   // labels = {
     *   //   label: 'labelValue',
     *   //   ...
     *   // }
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.getLabels().then(function(data) {
     *   const labels = data[0];
     * });
     * ```
     */
    getLabels(optionsOrCallback, callback) {
        let options = {};
        if (typeof optionsOrCallback === 'function') {
            callback = optionsOrCallback;
        }
        else if (optionsOrCallback) {
            options = optionsOrCallback;
        }
        this.getMetadata(options, (err, metadata) => {
            if (err) {
                callback(err, null);
                return;
            }
            callback(null, metadata.labels || {});
        });
    }
    /**
     * @typedef {object} GetNotificationsOptions Configuration options for Bucket#getNotification().
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * @callback GetNotificationsCallback
     * @param {?Error} err Request error, if any.
     * @param {Notification[]} notifications Array of {@link Notification}
     *     instances.
     * @param {object} apiResponse The full API response.
     */
    /**
     * @typedef {array} GetNotificationsResponse
     * @property {Notification[]} 0 Array of {@link Notification} instances.
     * @property {object} 1 The full API response.
     */
    /**
     * Retrieves a list of notification subscriptions for a given bucket.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/notifications/list| Notifications: list}
     *
     * @param {GetNotificationsOptions} [options] Configuration options.
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for the request.
     * @param {GetNotificationsCallback} [callback] Callback function.
     * @returns {Promise<GetNotificationsResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('my-bucket');
     *
     * bucket.getNotifications(function(err, notifications, apiResponse) {
     *   if (!err) {
     *     // notifications is an array of Notification objects.
     *   }
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.getNotifications().then(function(data) {
     *   const notifications = data[0];
     *   const apiResponse = data[1];
     * });
     *
     * ```
     * @example <caption>include:samples/listNotifications.js</caption>
     * region_tag:storage_list_bucket_notifications
     * Another example:
     */
    getNotifications(optionsOrCallback, callback) {
        let options = {};
        if (typeof optionsOrCallback === 'function') {
            callback = optionsOrCallback;
        }
        else if (optionsOrCallback) {
            options = optionsOrCallback;
        }
        this.request({
            uri: '/notificationConfigs',
            qs: options,
        }, (err, resp) => {
            if (err) {
                callback(err, null, resp);
                return;
            }
            const itemsArray = resp.items ? resp.items : [];
            const notifications = itemsArray.map((notification) => {
                const notificationInstance = this.notification(notification.id);
                notificationInstance.metadata = notification;
                return notificationInstance;
            });
            callback(null, notifications, resp);
        });
    }
    /**
     * @typedef {array} GetSignedUrlResponse
     * @property {object} 0 The signed URL.
     */
    /**
     * @callback GetSignedUrlCallback
     * @param {?Error} err Request error, if any.
     * @param {object} url The signed URL.
     */
    /**
     * @typedef {object} GetBucketSignedUrlConfig
     * @property {string} action Currently only supports "list" (HTTP: GET).
     * @property {*} expires A timestamp when this link will expire. Any value
     *     given is passed to `new Date()`.
     *     Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now.
     * @property {string} [version='v2'] The signing version to use, either
     *     'v2' or 'v4'.
     * @property {boolean} [virtualHostedStyle=false] Use virtual hosted-style
     *     URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style
     *     ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs
     *     should generally be preferred instaed of path-style URL.
     *     Currently defaults to `false` for path-style, although this may change in a
     *     future major-version release.
     * @property {string} [cname] The cname for this bucket, i.e.,
     *     "https://cdn.example.com".
     *     See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example}
     * @property {object} [extensionHeaders] If these headers are used, the
     * server will check to make sure that the client provides matching
     * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers}
     * for the requirements of this feature, most notably:
     * - The header name must be prefixed with `x-goog-`
     * - The header name must be all lowercase
     *
     * Note: Multi-valued header passed as an array in the extensionHeaders
     *       object is converted into a string, delimited by `,` with
     *       no space. Requests made using the signed URL will need to
     *       delimit multi-valued headers using a single `,` as well, or
     *       else the server will report a mismatched signature.
     * @property {object} [queryParams] Additional query parameters to include
     *     in the signed URL.
     */
    /**
     * Get a signed URL to allow limited time access to a bucket.
     *
     * In Google Cloud Platform environments, such as Cloud Functions and App
     * Engine, you usually don't provide a `keyFilename` or `credentials` during
     * instantiation. In those environments, we call the
     * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob| signBlob API}
     * to create a signed URL. That API requires either the
     * `https://www.googleapis.com/auth/iam` or
     * `https://www.googleapis.com/auth/cloud-platform` scope, so be sure they are
     * enabled.
     *
     * See {@link https://cloud.google.com/storage/docs/access-control/signed-urls| Signed URLs Reference}
     *
     * @throws {Error} if an expiration timestamp from the past is given.
     *
     * @param {GetBucketSignedUrlConfig} config Configuration object.
     * @param {string} config.action Currently only supports "list" (HTTP: GET).
     * @param {*} config.expires A timestamp when this link will expire. Any value
     *     given is passed to `new Date()`.
     *     Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now.
     * @param {string} [config.version='v2'] The signing version to use, either
     *     'v2' or 'v4'.
     * @param {boolean} [config.virtualHostedStyle=false] Use virtual hosted-style
     *     URLs ('https://mybucket.storage.googleapis.com/...') instead of path-style
     *     ('https://storage.googleapis.com/mybucket/...'). Virtual hosted-style URLs
     *     should generally be preferred instaed of path-style URL.
     *     Currently defaults to `false` for path-style, although this may change in a
     *     future major-version release.
     * @param {string} [config.cname] The cname for this bucket, i.e.,
     *     "https://cdn.example.com".
     *     See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example}
     * @param {object} [config.extensionHeaders] If these headers are used, the
     * server will check to make sure that the client provides matching
     * values. See {@link https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers| Canonical extension headers}
     * for the requirements of this feature, most notably:
     * - The header name must be prefixed with `x-goog-`
     * - The header name must be all lowercase
     *
     * Note: Multi-valued header passed as an array in the extensionHeaders
     *       object is converted into a string, delimited by `,` with
     *       no space. Requests made using the signed URL will need to
     *       delimit multi-valued headers using a single `,` as well, or
     *       else the server will report a mismatched signature.
     * @property {object} [config.queryParams] Additional query parameters to include
     *     in the signed URL.
     * @param {GetSignedUrlCallback} [callback] Callback function.
     * @returns {Promise<GetSignedUrlResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * //-
     * // Generate a URL that allows temporary access to list files in a bucket.
     * //-
     * const request = require('request');
     *
     * const config = {
     *   action: 'list',
     *   expires: '03-17-2025'
     * };
     *
     * bucket.getSignedUrl(config, function(err, url) {
     *   if (err) {
     *     console.error(err);
     *     return;
     *   }
     *
     *   // The bucket is now available to be listed from this URL.
     *   request(url, function(err, resp) {
     *     // resp.statusCode = 200
     *   });
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.getSignedUrl(config).then(function(data) {
     *   const url = data[0];
     * });
     * ```
     */
    getSignedUrl(cfg, callback) {
        const method = BucketActionToHTTPMethod[cfg.action];
        if (!method) {
            throw new Error(storage_1.ExceptionMessages.INVALID_ACTION);
        }
        const signConfig = {
            method,
            expires: cfg.expires,
            version: cfg.version,
            cname: cfg.cname,
            extensionHeaders: cfg.extensionHeaders || {},
            queryParams: cfg.queryParams || {},
        };
        if (!this.signer) {
            this.signer = new signer_1.URLSigner(this.storage.authClient, this);
        }
        this.signer
            .getSignedUrl(signConfig)
            .then(signedUrl => callback(null, signedUrl), callback);
    }
    /**
     * @callback BucketLockCallback
     * @param {?Error} err Request error, if any.
     * @param {object} apiResponse The full API response.
     */
    /**
     * Lock a previously-defined retention policy. This will prevent changes to
     * the policy.
     *
     * @throws {Error} if a metageneration is not provided.
     *
     * @param {number|string} metageneration The bucket's metageneration. This is
     *     accesssible from calling {@link File#getMetadata}.
     * @param {BucketLockCallback} [callback] Callback function.
     * @returns {Promise<BucketLockResponse>}
     *
     * @example
     * ```
     * const storage = require('@google-cloud/storage')();
     * const bucket = storage.bucket('albums');
     *
     * const metageneration = 2;
     *
     * bucket.lock(metageneration, function(err, apiResponse) {});
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.lock(metageneration).then(function(data) {
     *   const apiResponse = data[0];
     * });
     * ```
     */
    lock(metageneration, callback) {
        const metatype = typeof metageneration;
        if (metatype !== 'number' && metatype !== 'string') {
            throw new Error(BucketExceptionMessages.METAGENERATION_NOT_PROVIDED);
        }
        this.request({
            method: 'POST',
            uri: '/lockRetentionPolicy',
            qs: {
                ifMetagenerationMatch: metageneration,
            },
        }, callback);
    }
    /**
     * @typedef {array} MakeBucketPrivateResponse
     * @property {File[]} 0 List of files made private.
     */
    /**
     * @callback MakeBucketPrivateCallback
     * @param {?Error} err Request error, if any.
     * @param {File[]} files List of files made private.
     */
    /**
     * @typedef {object} MakeBucketPrivateOptions
     * @property {boolean} [includeFiles=false] Make each file in the bucket
     *     private.
     * @property {Metadata} [metadata] Define custom metadata properties to define
     *     along with the operation.
     * @property {boolean} [force] Queue errors occurred while making files
     *     private until all files have been processed.
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * Make the bucket listing private.
     *
     * You may also choose to make the contents of the bucket private by
     * specifying `includeFiles: true`. This will automatically run
     * {@link File#makePrivate} for every file in the bucket.
     *
     * When specifying `includeFiles: true`, use `force: true` to delay execution
     * of your callback until all files have been processed. By default, the
     * callback is executed after the first error. Use `force` to queue such
     * errors until all files have been processed, after which they will be
     * returned as an array as the first argument to your callback.
     *
     * NOTE: This may cause the process to be long-running and use a high number
     * of requests. Use with caution.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation}
     *
     * @param {MakeBucketPrivateOptions} [options] Configuration options.
     * @param {boolean} [options.includeFiles=false] Make each file in the bucket
     *     private.
     * @param {Metadata} [options.metadata] Define custom metadata properties to define
     *     along with the operation.
     * @param {boolean} [options.force] Queue errors occurred while making files
     *     private until all files have been processed.
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for the request.
     * @param {MakeBucketPrivateCallback} [callback] Callback function.
     * @returns {Promise<MakeBucketPrivateResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * //-
     * // Make the bucket private.
     * //-
     * bucket.makePrivate(function(err) {});
     *
     * //-
     * // Make the bucket and its contents private.
     * //-
     * const opts = {
     *   includeFiles: true
     * };
     *
     * bucket.makePrivate(opts, function(err, files) {
     *   // `err`:
     *   //    The first error to occur, otherwise null.
     *   //
     *   // `files`:
     *   //    Array of files successfully made private in the bucket.
     * });
     *
     * //-
     * // Make the bucket and its contents private, using force to suppress errors
     * // until all files have been processed.
     * //-
     * const opts = {
     *   includeFiles: true,
     *   force: true
     * };
     *
     * bucket.makePrivate(opts, function(errors, files) {
     *   // `errors`:
     *   //    Array of errors if any occurred, otherwise null.
     *   //
     *   // `files`:
     *   //    Array of files successfully made private in the bucket.
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.makePrivate(opts).then(function(data) {
     *   const files = data[0];
     * });
     * ```
     */
    makePrivate(optionsOrCallback, callback) {
        var _a, _b, _c, _d;
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        options.private = true;
        const query = {
            predefinedAcl: 'projectPrivate',
        };
        if (options.userProject) {
            query.userProject = options.userProject;
        }
        if ((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) {
            query.ifGenerationMatch = options.preconditionOpts.ifGenerationMatch;
        }
        if ((_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationNotMatch) {
            query.ifGenerationNotMatch =
                options.preconditionOpts.ifGenerationNotMatch;
        }
        if ((_c = options.preconditionOpts) === null || _c === void 0 ? void 0 : _c.ifMetagenerationMatch) {
            query.ifMetagenerationMatch =
                options.preconditionOpts.ifMetagenerationMatch;
        }
        if ((_d = options.preconditionOpts) === null || _d === void 0 ? void 0 : _d.ifMetagenerationNotMatch) {
            query.ifMetagenerationNotMatch =
                options.preconditionOpts.ifMetagenerationNotMatch;
        }
        // You aren't allowed to set both predefinedAcl & acl properties on a bucket
        // so acl must explicitly be nullified.
        const metadata = extend({}, options.metadata, { acl: null });
        this.setMetadata(metadata, query, err => {
            if (err) {
                callback(err);
            }
            const internalCall = () => {
                if (options.includeFiles) {
                    return (0, util_1.promisify)(this.makeAllFilesPublicPrivate_).call(this, options);
                }
                return Promise.resolve([]);
            };
            internalCall()
                .then(files => callback(null, files))
                .catch(callback);
        });
    }
    /**
     * @typedef {object} MakeBucketPublicOptions
     * @property {boolean} [includeFiles=false] Make each file in the bucket
     *     private.
     * @property {boolean} [force] Queue errors occurred while making files
     *     private until all files have been processed.
     */
    /**
     * @callback MakeBucketPublicCallback
     * @param {?Error} err Request error, if any.
     * @param {File[]} files List of files made public.
     */
    /**
     * @typedef {array} MakeBucketPublicResponse
     * @property {File[]} 0 List of files made public.
     */
    /**
     * Make the bucket publicly readable.
     *
     * You may also choose to make the contents of the bucket publicly readable by
     * specifying `includeFiles: true`. This will automatically run
     * {@link File#makePublic} for every file in the bucket.
     *
     * When specifying `includeFiles: true`, use `force: true` to delay execution
     * of your callback until all files have been processed. By default, the
     * callback is executed after the first error. Use `force` to queue such
     * errors until all files have been processed, after which they will be
     * returned as an array as the first argument to your callback.
     *
     * NOTE: This may cause the process to be long-running and use a high number
     * of requests. Use with caution.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/patch| Buckets: patch API Documentation}
     *
     * @param {MakeBucketPublicOptions} [options] Configuration options.
     * @param {boolean} [options.includeFiles=false] Make each file in the bucket
     *     private.
     * @param {boolean} [options.force] Queue errors occurred while making files
     *     private until all files have been processed.
     * @param {MakeBucketPublicCallback} [callback] Callback function.
     * @returns {Promise<MakeBucketPublicResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * //-
     * // Make the bucket publicly readable.
     * //-
     * bucket.makePublic(function(err) {});
     *
     * //-
     * // Make the bucket and its contents publicly readable.
     * //-
     * const opts = {
     *   includeFiles: true
     * };
     *
     * bucket.makePublic(opts, function(err, files) {
     *   // `err`:
     *   //    The first error to occur, otherwise null.
     *   //
     *   // `files`:
     *   //    Array of files successfully made public in the bucket.
     * });
     *
     * //-
     * // Make the bucket and its contents publicly readable, using force to
     * // suppress errors until all files have been processed.
     * //-
     * const opts = {
     *   includeFiles: true,
     *   force: true
     * };
     *
     * bucket.makePublic(opts, function(errors, files) {
     *   // `errors`:
     *   //    Array of errors if any occurred, otherwise null.
     *   //
     *   // `files`:
     *   //    Array of files successfully made public in the bucket.
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.makePublic(opts).then(function(data) {
     *   const files = data[0];
     * });
     * ```
     */
    makePublic(optionsOrCallback, callback) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        const req = extend(true, { public: true }, options);
        this.acl
            .add({
            entity: 'allUsers',
            role: 'READER',
        })
            .then(() => {
            return this.acl.default.add({
                entity: 'allUsers',
                role: 'READER',
            });
        })
            .then(() => {
            if (req.includeFiles) {
                return (0, util_1.promisify)(this.makeAllFilesPublicPrivate_).call(this, req);
            }
            return [];
        })
            .then(files => callback(null, files), callback);
    }
    /**
     * Get a reference to a Cloud Pub/Sub Notification.
     *
     * @param {string} id ID of notification.
     * @returns {Notification}
     * @see Notification
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('my-bucket');
     * const notification = bucket.notification('1');
     * ```
     */
    notification(id) {
        if (!id) {
            throw new Error(BucketExceptionMessages.SUPPLY_NOTIFICATION_ID);
        }
        return new notification_1.Notification(this, id);
    }
    /**
     * Remove an already-existing retention policy from this bucket, if it is not
     * locked.
     *
     * @param {SetBucketMetadataCallback} [callback] Callback function.
     * @param {SetBucketMetadataOptions} [options] Options, including precondition options
     * @returns {Promise<SetBucketMetadataResponse>}
     *
     * @example
     * ```
     * const storage = require('@google-cloud/storage')();
     * const bucket = storage.bucket('albums');
     *
     * bucket.removeRetentionPeriod(function(err, apiResponse) {});
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.removeRetentionPeriod().then(function(data) {
     *   const apiResponse = data[0];
     * });
     * ```
     */
    removeRetentionPeriod(optionsOrCallback, callback) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        this.setMetadata({
            retentionPolicy: null,
        }, options, callback);
    }
    /**
     * Makes request and applies userProject query parameter if necessary.
     *
     * @private
     *
     * @param {object} reqOpts - The request options.
     * @param {function} callback - The callback function.
     */
    request(reqOpts, callback) {
        if (this.userProject && (!reqOpts.qs || !reqOpts.qs.userProject)) {
            reqOpts.qs = extend(reqOpts.qs, { userProject: this.userProject });
        }
        return super.request(reqOpts, callback);
    }
    /**
     * @typedef {array} SetLabelsResponse
     * @property {object} 0 The bucket metadata.
     */
    /**
     * @callback SetLabelsCallback
     * @param {?Error} err Request error, if any.
     * @param {object} metadata The bucket metadata.
     */
    /**
     * @typedef {object} SetLabelsOptions Configuration options for Bucket#setLabels().
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * Set labels on the bucket.
     *
     * This makes an underlying call to {@link Bucket#setMetadata}, which
     * is a PATCH request. This means an individual label can be overwritten, but
     * unmentioned labels will not be touched.
     *
     * @param {object<string, string>} labels Labels to set on the bucket.
     * @param {SetLabelsOptions} [options] Configuration options.
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for the request.
     * @param {SetLabelsCallback} [callback] Callback function.
     * @returns {Promise<SetLabelsResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * const labels = {
     *   labelone: 'labelonevalue',
     *   labeltwo: 'labeltwovalue'
     * };
     *
     * bucket.setLabels(labels, function(err, metadata) {
     *   if (!err) {
     *     // Labels set successfully.
     *   }
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.setLabels(labels).then(function(data) {
     *   const metadata = data[0];
     * });
     * ```
     */
    setLabels(labels, optionsOrCallback, callback) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        callback = callback || nodejs_common_1.util.noop;
        this.setMetadata({ labels }, options, callback);
    }
    setMetadata(metadata, optionsOrCallback, cb) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        cb =
            typeof optionsOrCallback === 'function'
                ? optionsOrCallback
                : cb;
        this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, AvailableServiceObjectMethods.setMetadata, options);
        super
            .setMetadata(metadata, options)
            .then(resp => cb(null, ...resp))
            .catch(cb)
            .finally(() => {
            this.storage.retryOptions.autoRetry = this.instanceRetryValue;
        });
    }
    /**
     * Lock all objects contained in the bucket, based on their creation time. Any
     * attempt to overwrite or delete objects younger than the retention period
     * will result in a `PERMISSION_DENIED` error.
     *
     * An unlocked retention policy can be modified or removed from the bucket via
     * {@link File#removeRetentionPeriod} and {@link File#setRetentionPeriod}. A
     * locked retention policy cannot be removed or shortened in duration for the
     * lifetime of the bucket. Attempting to remove or decrease period of a locked
     * retention policy will result in a `PERMISSION_DENIED` error. You can still
     * increase the policy.
     *
     * @param {*} duration In seconds, the minimum retention time for all objects
     *     contained in this bucket.
     * @param {SetBucketMetadataCallback} [callback] Callback function.
     * @param {SetBucketMetadataCallback} [options] Options, including precondition options.
     * @returns {Promise<SetBucketMetadataResponse>}
     *
     * @example
     * ```
     * const storage = require('@google-cloud/storage')();
     * const bucket = storage.bucket('albums');
     *
     * const DURATION_SECONDS = 15780000; // 6 months.
     *
     * //-
     * // Lock the objects in this bucket for 6 months.
     * //-
     * bucket.setRetentionPeriod(DURATION_SECONDS, function(err, apiResponse) {});
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.setRetentionPeriod(DURATION_SECONDS).then(function(data) {
     *   const apiResponse = data[0];
     * });
     * ```
     */
    setRetentionPeriod(duration, optionsOrCallback, callback) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        this.setMetadata({
            retentionPolicy: {
                retentionPeriod: duration,
            },
        }, options, callback);
    }
    /**
     *
     * @typedef {object} Cors
     * @property {number} [maxAgeSeconds] The number of seconds the browser is
     *     allowed to make requests before it must repeat the preflight request.
     * @property {string[]} [method] HTTP method allowed for cross origin resource
     *     sharing with this bucket.
     * @property {string[]} [origin] an origin allowed for cross origin resource
     *     sharing with this bucket.
     * @property {string[]} [responseHeader] A header allowed for cross origin
     *     resource sharing with this bucket.
     */
    /**
     * This can be used to set the CORS configuration on the bucket.
     *
     * The configuration will be overwritten with the value passed into this.
     *
     * @param {Cors[]} corsConfiguration The new CORS configuration to set
     * @param {number} [corsConfiguration.maxAgeSeconds] The number of seconds the browser is
     *     allowed to make requests before it must repeat the preflight request.
     * @param {string[]} [corsConfiguration.method] HTTP method allowed for cross origin resource
     *     sharing with this bucket.
     * @param {string[]} [corsConfiguration.origin] an origin allowed for cross origin resource
     *     sharing with this bucket.
     * @param {string[]} [corsConfiguration.responseHeader] A header allowed for cross origin
     *     resource sharing with this bucket.
     * @param {SetBucketMetadataCallback} [callback] Callback function.
     * @param {SetBucketMetadataOptions} [options] Options, including precondition options.
     * @returns {Promise<SetBucketMetadataResponse>}
     *
     * @example
     * ```
     * const storage = require('@google-cloud/storage')();
     * const bucket = storage.bucket('albums');
     *
     * const corsConfiguration = [{maxAgeSeconds: 3600}]; // 1 hour
     * bucket.setCorsConfiguration(corsConfiguration);
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.setCorsConfiguration(corsConfiguration).then(function(data) {
     *   const apiResponse = data[0];
     * });
     * ```
     */
    setCorsConfiguration(corsConfiguration, optionsOrCallback, callback) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        this.setMetadata({
            cors: corsConfiguration,
        }, options, callback);
    }
    /**
     * @typedef {object} SetBucketStorageClassOptions
     * @property {string} [userProject] - The ID of the project which will be
     *     billed for the request.
     */
    /**
     * @callback SetBucketStorageClassCallback
     * @param {?Error} err Request error, if any.
     */
    /**
     * Set the default storage class for new files in this bucket.
     *
     * See {@link https://cloud.google.com/storage/docs/storage-classes| Storage Classes}
     *
     * @param {string} storageClass The new storage class. (`standard`,
     *     `nearline`, `coldline`, or `archive`).
     *     **Note:** The storage classes `multi_regional`, `regional`, and
     *     `durable_reduced_availability` are now legacy and will be deprecated in
     *     the future.
     * @param {object} [options] Configuration options.
     * @param {string} [options.userProject] - The ID of the project which will be
     *     billed for the request.
     * @param {SetStorageClassCallback} [callback] Callback function.
     * @returns {Promise}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * bucket.setStorageClass('nearline', function(err, apiResponse) {
     *   if (err) {
     *     // Error handling omitted.
     *   }
     *
     *   // The storage class was updated successfully.
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.setStorageClass('nearline').then(function() {});
     * ```
     */
    setStorageClass(storageClass, optionsOrCallback, callback) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        // In case we get input like `storageClass`, convert to `storage_class`.
        storageClass = storageClass
            .replace(/-/g, '_')
            .replace(/([a-z])([A-Z])/g, (_, low, up) => {
            return low + '_' + up;
        })
            .toUpperCase();
        this.setMetadata({ storageClass }, options, callback);
    }
    /**
     * Set a user project to be billed for all requests made from this Bucket
     * object and any files referenced from this Bucket object.
     *
     * @param {string} userProject The user project.
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * bucket.setUserProject('grape-spaceship-123');
     * ```
     */
    setUserProject(userProject) {
        this.userProject = userProject;
        const methods = [
            'create',
            'delete',
            'exists',
            'get',
            'getMetadata',
            'setMetadata',
        ];
        methods.forEach(method => {
            const methodConfig = this.methods[method];
            if (typeof methodConfig === 'object') {
                if (typeof methodConfig.reqOpts === 'object') {
                    extend(methodConfig.reqOpts.qs, { userProject });
                }
                else {
                    methodConfig.reqOpts = {
                        qs: { userProject },
                    };
                }
            }
        });
    }
    /**
     * @typedef {object} UploadOptions Configuration options for Bucket#upload().
     * @property {string|File} [destination] The place to save
     *     your file. If given a string, the file will be uploaded to the bucket
     *     using the string as a filename. When given a File object, your local
     * file will be uploaded to the File object's bucket and under the File
     * object's name. Lastly, when this argument is omitted, the file is uploaded
     * to your bucket using the name of the local file.
     * @property {string} [encryptionKey] A custom encryption key. See
     *     {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}.
     * @property {boolean} [gzip] Automatically gzip the file. This will set
     *     `options.metadata.contentEncoding` to `gzip`.
     * @property {string} [kmsKeyName] The name of the Cloud KMS key that will
     *     be used to encrypt the object. Must be in the format:
     *     `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`.
     * @property {object} [metadata] See an
     *     {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}.
     * @property {string} [offset] The starting byte of the upload stream, for
     *     resuming an interrupted upload. Defaults to 0.
     * @property {string} [predefinedAcl] Apply a predefined set of access
     * controls to this object.
     *
     * Acceptable values are:
     * - **`authenticatedRead`** - Object owner gets `OWNER` access, and
     *       `allAuthenticatedUsers` get `READER` access.
     *
     * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and
     *       project team owners get `OWNER` access.
     *
     * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project
     *       team owners get `READER` access.
     *
     * - **`private`** - Object owner gets `OWNER` access.
     *
     * - **`projectPrivate`** - Object owner gets `OWNER` access, and project
     *       team members get access according to their roles.
     *
     * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers`
     *       get `READER` access.
     * @property {boolean} [private] Make the uploaded file private. (Alias for
     *     `options.predefinedAcl = 'private'`)
     * @property {boolean} [public] Make the uploaded file public. (Alias for
     *     `options.predefinedAcl = 'publicRead'`)
     * @property {boolean} [resumable=true] Resumable uploads are automatically
     *     enabled and must be shut off explicitly by setting to false.
     * @property {number} [timeout=60000] Set the HTTP request timeout in
     *     milliseconds. This option is not available for resumable uploads.
     *     Default: `60000`
     * @property {string} [uri] The URI for an already-created resumable
     *     upload. See {@link File#createResumableUpload}.
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     * @property {string|boolean} [validation] Possible values: `"md5"`,
     *     `"crc32c"`, or `false`. By default, data integrity is validated with an
     *     MD5 checksum for maximum reliability. CRC32c will provide better
     *     performance with less reliability. You may also choose to skip
     * validation completely, however this is **not recommended**.
     */
    /**
     * @typedef {array} UploadResponse
     * @property {object} 0 The uploaded {@link File}.
     * @property {object} 1 The full API response.
     */
    /**
     * @callback UploadCallback
     * @param {?Error} err Request error, if any.
     * @param {object} file The uploaded {@link File}.
     * @param {object} apiResponse The full API response.
     */
    /**
     * Upload a file to the bucket. This is a convenience method that wraps
     * {@link File#createWriteStream}.
     *
     * Resumable uploads are enabled by default
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#uploads| Upload Options (Simple or Resumable)}
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert| Objects: insert API Documentation}
     *
     * @param {string} pathString The fully qualified path to the file you
     *     wish to upload to your bucket.
     * @param {UploadOptions} [options] Configuration options.
     * @param {string|File} [options.destination] The place to save
     *     your file. If given a string, the file will be uploaded to the bucket
     *     using the string as a filename. When given a File object, your local
     * file will be uploaded to the File object's bucket and under the File
     * object's name. Lastly, when this argument is omitted, the file is uploaded
     * to your bucket using the name of the local file.
     * @param {string} [options.encryptionKey] A custom encryption key. See
     *     {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}.
     * @param {boolean} [options.gzip] Automatically gzip the file. This will set
     *     `options.metadata.contentEncoding` to `gzip`.
     * @param {string} [options.kmsKeyName] The name of the Cloud KMS key that will
     *     be used to encrypt the object. Must be in the format:
     *     `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`.
     * @param {object} [options.metadata] See an
     *     {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}.
     * @param {string} [options.offset] The starting byte of the upload stream, for
     *     resuming an interrupted upload. Defaults to 0.
     * @param {string} [options.predefinedAcl] Apply a predefined set of access
     * controls to this object.
     * Acceptable values are:
     * - **`authenticatedRead`** - Object owner gets `OWNER` access, and
     *   `allAuthenticatedUsers` get `READER` access.
     *
     * - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and
     *   project team owners get `OWNER` access.
     *
     * - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project
     *   team owners get `READER` access.
     *
     * - **`private`** - Object owner gets `OWNER` access.
     *
     * - **`projectPrivate`** - Object owner gets `OWNER` access, and project
     *   team members get access according to their roles.
     *
     * - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers`
     *   get `READER` access.
     * @param {boolean} [options.private] Make the uploaded file private. (Alias for
     *     `options.predefinedAcl = 'private'`)
     * @param {boolean} [options.public] Make the uploaded file public. (Alias for
     *     `options.predefinedAcl = 'publicRead'`)
     * @param {boolean} [options.resumable=true] Resumable uploads are automatically
     *     enabled and must be shut off explicitly by setting to false.
     * @param {number} [options.timeout=60000] Set the HTTP request timeout in
     *     milliseconds. This option is not available for resumable uploads.
     *     Default: `60000`
     * @param {string} [options.uri] The URI for an already-created resumable
     *     upload. See {@link File#createResumableUpload}.
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for the request.
     * @param {string|boolean} [options.validation] Possible values: `"md5"`,
     *     `"crc32c"`, or `false`. By default, data integrity is validated with an
     *     MD5 checksum for maximum reliability. CRC32c will provide better
     *     performance with less reliability. You may also choose to skip
     * validation completely, however this is **not recommended**.
     * @param {UploadCallback} [callback] Callback function.
     * @returns {Promise<UploadResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     *
     * //-
     * // Upload a file from a local path.
     * //-
     * bucket.upload('/local/path/image.png', function(err, file, apiResponse) {
     *   // Your bucket now contains:
     *   // - "image.png" (with the contents of `/local/path/image.png')
     *
     *   // `file` is an instance of a File object that refers to your new file.
     * });
     *
     *
     * //-
     * // It's not always that easy. You will likely want to specify the filename
     * // used when your new file lands in your bucket.
     * //
     * // You may also want to set metadata or customize other options.
     * //-
     * const options = {
     *   destination: 'new-image.png',
     *   validation: 'crc32c',
     *   metadata: {
     *     metadata: {
     *       event: 'Fall trip to the zoo'
     *     }
     *   }
     * };
     *
     * bucket.upload('local-image.png', options, function(err, file) {
     *   // Your bucket now contains:
     *   // - "new-image.png" (with the contents of `local-image.png')
     *
     *   // `file` is an instance of a File object that refers to your new file.
     * });
     *
     * //-
     * // You can also have a file gzip'd on the fly.
     * //-
     * bucket.upload('index.html', { gzip: true }, function(err, file) {
     *   // Your bucket now contains:
     *   // - "index.html" (automatically compressed with gzip)
     *
     *   // Downloading the file with `file.download` will automatically decode
     * the
     *   // file.
     * });
     *
     * //-
     * // You may also re-use a File object, {File}, that references
     * // the file you wish to create or overwrite.
     * //-
     * const options = {
     *   destination: bucket.file('existing-file.png'),
     *   resumable: false
     * };
     *
     * bucket.upload('local-img.png', options, function(err, newFile) {
     *   // Your bucket now contains:
     *   // - "existing-file.png" (with the contents of `local-img.png')
     *
     *   // Note:
     *   // The `newFile` parameter is equal to `file`.
     * });
     *
     * //-
     * // To use
     * // <a
     * href="https://cloud.google.com/storage/docs/encryption#customer-supplied">
     * // Customer-supplied Encryption Keys</a>, provide the `encryptionKey`
     * option.
     * //-
     * const crypto = require('crypto');
     * const encryptionKey = crypto.randomBytes(32);
     *
     * bucket.upload('img.png', {
     *   encryptionKey: encryptionKey
     * }, function(err, newFile) {
     *   // `img.png` was uploaded with your custom encryption key.
     *
     *   // `newFile` is already configured to use the encryption key when making
     *   // operations on the remote object.
     *
     *   // However, to use your encryption key later, you must create a `File`
     *   // instance with the `key` supplied:
     *   const file = bucket.file('img.png', {
     *     encryptionKey: encryptionKey
     *   });
     *
     *   // Or with `file#setEncryptionKey`:
     *   const file = bucket.file('img.png');
     *   file.setEncryptionKey(encryptionKey);
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * bucket.upload('local-image.png').then(function(data) {
     *   const file = data[0];
     * });
     *
     * To upload a file from a URL, use {@link File#createWriteStream}.
     *
     * ```
     * @example <caption>include:samples/files.js</caption>
     * region_tag:storage_upload_file
     * Another example:
     *
     * @example <caption>include:samples/encryption.js</caption>
     * region_tag:storage_upload_encrypted_file
     * Example of uploading an encrypted file:
     */
    upload(pathString, optionsOrCallback, callback) {
        var _a, _b;
        const upload = (numberOfRetries) => {
            const returnValue = retry(async (bail) => {
                await new Promise((resolve, reject) => {
                    var _a, _b;
                    if (numberOfRetries === 0 &&
                        ((_b = (_a = newFile === null || newFile === void 0 ? void 0 : newFile.storage) === null || _a === void 0 ? void 0 : _a.retryOptions) === null || _b === void 0 ? void 0 : _b.autoRetry)) {
                        newFile.storage.retryOptions.autoRetry = false;
                    }
                    const writable = newFile.createWriteStream(options);
                    if (options.onUploadProgress) {
                        writable.on('progress', options.onUploadProgress);
                    }
                    fs.createReadStream(pathString)
                        .on('error', bail)
                        .pipe(writable)
                        .on('error', err => {
                        if (this.storage.retryOptions.autoRetry &&
                            this.storage.retryOptions.retryableErrorFn(err)) {
                            return reject(err);
                        }
                        else {
                            return bail(err);
                        }
                    })
                        .on('finish', () => {
                        return resolve();
                    });
                });
            }, {
                retries: numberOfRetries,
                factor: this.storage.retryOptions.retryDelayMultiplier,
                maxTimeout: this.storage.retryOptions.maxRetryDelay * 1000,
                maxRetryTime: this.storage.retryOptions.totalTimeout * 1000, //convert to milliseconds
            });
            if (!callback) {
                return returnValue;
            }
            else {
                return returnValue
                    .then(() => {
                    if (callback) {
                        return callback(null, newFile, newFile.metadata);
                    }
                })
                    .catch(callback);
            }
        };
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        if (global['GCLOUD_SANDBOX_ENV']) {
            return;
        }
        let options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        options = Object.assign({
            metadata: {},
        }, options);
        // Do not retry if precondition option ifGenerationMatch is not set
        // because this is a file operation
        let maxRetries = this.storage.retryOptions.maxRetries;
        if ((((_a = options === null || options === void 0 ? void 0 : options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === undefined &&
            ((_b = this.instancePreconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch) === undefined &&
            this.storage.retryOptions.idempotencyStrategy ===
                storage_1.IdempotencyStrategy.RetryConditional) ||
            this.storage.retryOptions.idempotencyStrategy ===
                storage_1.IdempotencyStrategy.RetryNever) {
            maxRetries = 0;
        }
        let newFile;
        if (options.destination instanceof file_1.File) {
            newFile = options.destination;
        }
        else if (options.destination !== null &&
            typeof options.destination === 'string') {
            // Use the string as the name of the file.
            newFile = this.file(options.destination, {
                encryptionKey: options.encryptionKey,
                kmsKeyName: options.kmsKeyName,
                preconditionOpts: this.instancePreconditionOpts,
            });
        }
        else {
            // Resort to using the name of the incoming file.
            const destination = path.basename(pathString);
            newFile = this.file(destination, {
                encryptionKey: options.encryptionKey,
                kmsKeyName: options.kmsKeyName,
                preconditionOpts: this.instancePreconditionOpts,
            });
        }
        upload(maxRetries);
    }
    /**
     * @private
     *
     * @typedef {object} MakeAllFilesPublicPrivateOptions
     * @property {boolean} [force] Suppress errors until all files have been
     *     processed.
     * @property {boolean} [private] Make files private.
     * @property {boolean} [public] Make files public.
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * @private
     *
     * @callback SetBucketMetadataCallback
     * @param {?Error} err Request error, if any.
     * @param {File[]} files Files that were updated.
     */
    /**
     * @typedef {array} MakeAllFilesPublicPrivateResponse
     * @property {File[]} 0 List of files affected.
     */
    /**
     * Iterate over all of a bucket's files, calling `file.makePublic()` (public)
     * or `file.makePrivate()` (private) on each.
     *
     * Operations are performed in parallel, up to 10 at once. The first error
     * breaks the loop, and will execute the provided callback with it. Specify
     * `{ force: true }` to suppress the errors.
     *
     * @private
     *
     * @param {MakeAllFilesPublicPrivateOptions} [options] Configuration options.
     * @param {boolean} [options.force] Suppress errors until all files have been
     *     processed.
     * @param {boolean} [options.private] Make files private.
     * @param {boolean} [options.public] Make files public.
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for the request.
  
     * @param {MakeAllFilesPublicPrivateCallback} callback Callback function.
     *
     * @return {Promise<MakeAllFilesPublicPrivateResponse>}
     */
    makeAllFilesPublicPrivate_(optionsOrCallback, callback) {
        const MAX_PARALLEL_LIMIT = 10;
        const errors = [];
        const updatedFiles = [];
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        const processFile = async (file) => {
            try {
                await (options.public ? file.makePublic() : file.makePrivate(options));
                updatedFiles.push(file);
            }
            catch (e) {
                if (!options.force) {
                    throw e;
                }
                errors.push(e);
            }
        };
        this.getFiles(options)
            .then(([files]) => {
            const limit = pLimit(MAX_PARALLEL_LIMIT);
            const promises = files.map(file => {
                return limit(() => processFile(file));
            });
            return Promise.all(promises);
        })
            .then(() => callback(errors.length > 0 ? errors : null, updatedFiles), err => callback(err, updatedFiles));
    }
    getId() {
        return this.id;
    }
    disableAutoRetryConditionallyIdempotent_(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    coreOpts, 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    methodType, localPreconditionOptions) {
        var _a, _b;
        if (typeof coreOpts === 'object' &&
            ((_b = (_a = coreOpts === null || coreOpts === void 0 ? void 0 : coreOpts.reqOpts) === null || _a === void 0 ? void 0 : _a.qs) === null || _b === void 0 ? void 0 : _b.ifMetagenerationMatch) === undefined &&
            (localPreconditionOptions === null || localPreconditionOptions === void 0 ? void 0 : localPreconditionOptions.ifMetagenerationMatch) === undefined &&
            (methodType === AvailableServiceObjectMethods.setMetadata ||
                methodType === AvailableServiceObjectMethods.delete) &&
            this.storage.retryOptions.idempotencyStrategy ===
                storage_1.IdempotencyStrategy.RetryConditional) {
            this.storage.retryOptions.autoRetry = false;
        }
        else if (this.storage.retryOptions.idempotencyStrategy ===
            storage_1.IdempotencyStrategy.RetryNever) {
            this.storage.retryOptions.autoRetry = false;
        }
    }
}
exports.Bucket = Bucket;
/*! Developer Documentation
 *
 * These methods can be auto-paginated.
 */
paginator_1.paginator.extend(Bucket, 'getFiles');
/*! Developer Documentation
 *
 * All async methods (except for streams) will return a Promise in the event
 * that a callback is omitted.
 */
(0, promisify_1.promisifyAll)(Bucket, {
    exclude: ['cloudStorageURI', 'request', 'file', 'notification'],
});
//# sourceMappingURL=bucket.js.map