summaryrefslogtreecommitdiff
path: root/includes/fcm/node_modules/@google-cloud/storage/build/src/file.js
blob: 507a161ee3a29cb327b82268a371d1193cc370f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
"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.
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _File_instances, _File_validateIntegrity;
Object.defineProperty(exports, "__esModule", { value: true });
exports.File = exports.FileExceptionMessages = exports.STORAGE_POST_POLICY_BASE_URL = exports.ActionToHTTPMethod = void 0;
const nodejs_common_1 = require("./nodejs-common");
const promisify_1 = require("@google-cloud/promisify");
const compressible = require("compressible");
const crypto = require("crypto");
const extend = require("extend");
const fs = require("fs");
const mime = require("mime");
const resumableUpload = require("./resumable-upload");
const stream_1 = require("stream");
const zlib = require("zlib");
const storage_1 = require("./storage");
const bucket_1 = require("./bucket");
const acl_1 = require("./acl");
const signer_1 = require("./signer");
// eslint-disable-next-line @typescript-eslint/no-var-requires
const duplexify = require('duplexify');
const util_1 = require("./util");
const hash_stream_validator_1 = require("./hash-stream-validator");
const retry = require("async-retry");
var ActionToHTTPMethod;
(function (ActionToHTTPMethod) {
    ActionToHTTPMethod["read"] = "GET";
    ActionToHTTPMethod["write"] = "PUT";
    ActionToHTTPMethod["delete"] = "DELETE";
    ActionToHTTPMethod["resumable"] = "POST";
})(ActionToHTTPMethod = exports.ActionToHTTPMethod || (exports.ActionToHTTPMethod = {}));
/**
 * @private
 */
exports.STORAGE_POST_POLICY_BASE_URL = 'https://storage.googleapis.com';
/**
 * @private
 */
const GS_URL_REGEXP = /^gs:\/\/([a-z0-9_.-]+)\/(.+)$/;
class RequestError extends Error {
}
const SEVEN_DAYS = 7 * 24 * 60 * 60;
var FileExceptionMessages;
(function (FileExceptionMessages) {
    FileExceptionMessages["EXPIRATION_TIME_NA"] = "An expiration time is not available.";
    FileExceptionMessages["DESTINATION_NO_NAME"] = "Destination file should have a name.";
    FileExceptionMessages["INVALID_VALIDATION_FILE_RANGE"] = "Cannot use validation with file ranges (start/end).";
    FileExceptionMessages["MD5_NOT_AVAILABLE"] = "MD5 verification was specified, but is not available for the requested object. MD5 is not available for composite objects.";
    FileExceptionMessages["EQUALS_CONDITION_TWO_ELEMENTS"] = "Equals condition must be an array of 2 elements.";
    FileExceptionMessages["STARTS_WITH_TWO_ELEMENTS"] = "StartsWith condition must be an array of 2 elements.";
    FileExceptionMessages["CONTENT_LENGTH_RANGE_MIN_MAX"] = "ContentLengthRange must have numeric min & max fields.";
    FileExceptionMessages["DOWNLOAD_MISMATCH"] = "The downloaded data did not match the data from the server. To be sure the content is the same, you should download the file again.";
    FileExceptionMessages["UPLOAD_MISMATCH_DELETE_FAIL"] = "The uploaded data did not match the data from the server.\n    As a precaution, we attempted to delete the file, but it was not successful.\n    To be sure the content is the same, you should try removing the file manually,\n    then uploading the file again.\n    \n\nThe delete attempt failed with this message:\n\n  ";
    FileExceptionMessages["UPLOAD_MISMATCH"] = "The uploaded data did not match the data from the server.\n    As a precaution, the file has been deleted.\n    To be sure the content is the same, you should try uploading the file again.";
})(FileExceptionMessages = exports.FileExceptionMessages || (exports.FileExceptionMessages = {}));
/**
 * A File object is created from your {@link Bucket} object using
 * {@link Bucket#file}.
 *
 * @class
 */
class File extends nodejs_common_1.ServiceObject {
    /**
     * 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 File instance provides methods to get you a list of
     * the ACLs defined on your bucket, as well as set, update, and delete them.
     *
     * See {@link http://goo.gl/6qBBPO| About Access Control lists}
     *
     * @name File#acl
     * @mixes Acl
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     * //-
     * // Make a file publicly readable.
     * //-
     * const options = {
     *   entity: 'allUsers',
     *   role: storage.acl.READER_ROLE
     * };
     *
     * file.acl.add(options, function(err, aclObject) {});
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.acl.add(options).then(function(data) {
     *   const aclObject = data[0];
     *   const apiResponse = data[1];
     * });
     * ```
     */
    /**
     * The API-formatted resource description of the file.
     *
     * Note: This is not guaranteed to be up-to-date when accessed. To get the
     * latest record, call the `getMetadata()` method.
     *
     * @name File#metadata
     * @type {object}
     */
    /**
     * The file's name.
     * @name File#name
     * @type {string}
     */
    /**
     * @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}
     */
    /**
     * @callback Crc32cGeneratorCallback
     * @returns {CRC32CValidator}
     */
    /**
     * @typedef {object} FileOptions Options passed to the File constructor.
     * @property {string} [encryptionKey] A custom encryption key.
     * @property {number} [generation] Generation to scope the file to.
     * @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this
     *     object, if the object is encrypted by such a key. Limited availability;
     *     usable only by enabled projects.
     * @property {string} [userProject] The ID of the project which will be
     *     billed for all requests made from File object.
     * @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C}
     */
    /**
     * Constructs a file object.
     *
     * @param {Bucket} bucket The Bucket instance this file is
     *     attached to.
     * @param {string} name The name of the remote file.
     * @param {FileOptions} [options] Configuration options.
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     * ```
     */
    constructor(bucket, name, options = {}) {
        var _a, _b;
        const requestQueryObject = {};
        let generation;
        if (options.generation !== null) {
            if (typeof options.generation === 'string') {
                generation = Number(options.generation);
            }
            else {
                generation = options.generation;
            }
            if (!isNaN(generation)) {
                requestQueryObject.generation = generation;
            }
        }
        Object.assign(requestQueryObject, options.preconditionOpts);
        const userProject = options.userProject || bucket.userProject;
        if (typeof userProject === 'string') {
            requestQueryObject.userProject = userProject;
        }
        const methods = {
            /**
             * @typedef {array} DeleteFileResponse
             * @property {object} 0 The full API response.
             */
            /**
             * @callback DeleteFileCallback
             * @param {?Error} err Request error, if any.
             * @param {object} apiResponse The full API response.
             */
            /**
             * Delete the file.
             *
             * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete| Objects: delete API Documentation}
             *
             * @method File#delete
             * @param {object} [options] Configuration options.
             * @param {boolean} [options.ignoreNotFound = false] Ignore an error if
             *     the file does not exist.
             * @param {string} [options.userProject] The ID of the project which will be
             *     billed for the request.
             * @param {DeleteFileCallback} [callback] Callback function.
             * @returns {Promise<DeleteFileResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const myBucket = storage.bucket('my-bucket');
             *
             * const file = myBucket.file('my-file');
             * file.delete(function(err, apiResponse) {});
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * file.delete().then(function(data) {
             *   const apiResponse = data[0];
             * });
             *
             * ```
             * @example <caption>include:samples/files.js</caption>
             * region_tag:storage_delete_file
             * Another example:
             */
            delete: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
            /**
             * @typedef {array} FileExistsResponse
             * @property {boolean} 0 Whether the {@link File} exists.
             */
            /**
             * @callback FileExistsCallback
             * @param {?Error} err Request error, if any.
             * @param {boolean} exists Whether the {@link File} exists.
             */
            /**
             * Check if the file exists.
             *
             * @method File#exists
             * @param {options} [options] Configuration options.
             * @param {string} [options.userProject] The ID of the project which will be
             *     billed for the request.
             * @param {FileExistsCallback} [callback] Callback function.
             * @returns {Promise<FileExistsResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const myBucket = storage.bucket('my-bucket');
             *
             * const file = myBucket.file('my-file');
             *
             * file.exists(function(err, exists) {});
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * file.exists().then(function(data) {
             *   const exists = data[0];
             * });
             * ```
             */
            exists: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
            /**
             * @typedef {array} GetFileResponse
             * @property {File} 0 The {@link File}.
             * @property {object} 1 The full API response.
             */
            /**
             * @callback GetFileCallback
             * @param {?Error} err Request error, if any.
             * @param {File} file The {@link File}.
             * @param {object} apiResponse The full API response.
             */
            /**
             * Get a file object and its metadata if it exists.
             *
             * @method File#get
             * @param {options} [options] Configuration options.
             * @param {string} [options.userProject] The ID of the project which will be
             *     billed for the request.
             * @param {GetFileCallback} [callback] Callback function.
             * @returns {Promise<GetFileResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const myBucket = storage.bucket('my-bucket');
             *
             * const file = myBucket.file('my-file');
             *
             * file.get(function(err, file, apiResponse) {
             *   // file.metadata` has been populated.
             * });
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * file.get().then(function(data) {
             *   const file = data[0];
             *   const apiResponse = data[1];
             * });
             * ```
             */
            get: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
            /**
             * @typedef {array} GetFileMetadataResponse
             * @property {object} 0 The {@link File} metadata.
             * @property {object} 1 The full API response.
             */
            /**
             * @callback GetFileMetadataCallback
             * @param {?Error} err Request error, if any.
             * @param {object} metadata The {@link File} metadata.
             * @param {object} apiResponse The full API response.
             */
            /**
             * Get the file's metadata.
             *
             * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/get| Objects: get API Documentation}
             *
             * @method File#getMetadata
             * @param {object} [options] Configuration options.
             * @param {string} [options.userProject] The ID of the project which will be
             *     billed for the request.
             * @param {GetFileMetadataCallback} [callback] Callback function.
             * @returns {Promise<GetFileMetadataResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const myBucket = storage.bucket('my-bucket');
             *
             * const file = myBucket.file('my-file');
             *
             * file.getMetadata(function(err, metadata, apiResponse) {});
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * file.getMetadata().then(function(data) {
             *   const metadata = data[0];
             *   const apiResponse = data[1];
             * });
             *
             * ```
             * @example <caption>include:samples/files.js</caption>
             * region_tag:storage_get_metadata
             * Another example:
             */
            getMetadata: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
            /**
             * @typedef {object} SetFileMetadataOptions Configuration options for File#setMetadata().
             * @param {string} [userProject] The ID of the project which will be billed for the request.
             */
            /**
             * @callback SetFileMetadataCallback
             * @param {?Error} err Request error, if any.
             * @param {object} apiResponse The full API response.
             */
            /**
             * @typedef {array} SetFileMetadataResponse
             * @property {object} 0 The full API response.
             */
            /**
             * Merge the given metadata with the current remote file's metadata. This
             * will set metadata if it was previously unset or update previously set
             * metadata. To unset previously set metadata, set its value to null.
             *
             * You can set custom key/value pairs in the metadata key of the given
             * object, however the other properties outside of this object must adhere
             * to the {@link https://goo.gl/BOnnCK| official API documentation}.
             *
             *
             * See the examples below for more information.
             *
             * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch| Objects: patch API Documentation}
             *
             * @method File#setMetadata
             * @param {object} [metadata] The metadata you wish to update.
             * @param {SetFileMetadataOptions} [options] Configuration options.
             * @param {SetFileMetadataCallback} [callback] Callback function.
             * @returns {Promise<SetFileMetadataResponse>}
             *
             * @example
             * ```
             * const {Storage} = require('@google-cloud/storage');
             * const storage = new Storage();
             * const myBucket = storage.bucket('my-bucket');
             *
             * const file = myBucket.file('my-file');
             *
             * const metadata = {
             *   contentType: 'application/x-font-ttf',
             *   metadata: {
             *     my: 'custom',
             *     properties: 'go here'
             *   }
             * };
             *
             * file.setMetadata(metadata, function(err, apiResponse) {});
             *
             * // Assuming current metadata = { hello: 'world', unsetMe: 'will do' }
             * file.setMetadata({
             *   metadata: {
             *     abc: '123', // will be set.
             *     unsetMe: null, // will be unset (deleted).
             *     hello: 'goodbye' // will be updated from 'world' to 'goodbye'.
             *   }
             * }, function(err, apiResponse) {
             *   // metadata should now be { abc: '123', hello: 'goodbye' }
             * });
             *
             * //-
             * // Set a temporary hold on this file from its bucket's retention period
             * // configuration.
             * //
             * file.setMetadata({
             *   temporaryHold: true
             * }, function(err, apiResponse) {});
             *
             * //-
             * // Alternatively, you may set a temporary hold. This will follow the
             * // same behavior as an event-based hold, with the exception that the
             * // bucket's retention policy will not renew for this file from the time
             * // the hold is released.
             * //-
             * file.setMetadata({
             *   eventBasedHold: true
             * }, function(err, apiResponse) {});
             *
             * //-
             * // If the callback is omitted, we'll return a Promise.
             * //-
             * file.setMetadata(metadata).then(function(data) {
             *   const apiResponse = data[0];
             * });
             * ```
             */
            setMetadata: {
                reqOpts: {
                    qs: requestQueryObject,
                },
            },
        };
        super({
            parent: bucket,
            baseUrl: '/o',
            id: encodeURIComponent(name),
            methods,
        });
        _File_instances.add(this);
        this.bucket = bucket;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        this.storage = bucket.parent;
        // @TODO Can this duplicate code from above be avoided?
        if (options.generation !== null) {
            let generation;
            if (typeof options.generation === 'string') {
                generation = Number(options.generation);
            }
            else {
                generation = options.generation;
            }
            if (!isNaN(generation)) {
                this.generation = generation;
            }
        }
        this.kmsKeyName = options.kmsKeyName;
        this.userProject = userProject;
        this.name = name;
        if (options.encryptionKey) {
            this.setEncryptionKey(options.encryptionKey);
        }
        this.acl = new acl_1.Acl({
            request: this.request.bind(this),
            pathPrefix: '/acl',
        });
        this.crc32cGenerator =
            options.crc32cGenerator || this.bucket.crc32cGenerator;
        this.instanceRetryValue = (_b = (_a = this.storage) === null || _a === void 0 ? void 0 : _a.retryOptions) === null || _b === void 0 ? void 0 : _b.autoRetry;
        this.instancePreconditionOpts = options === null || options === void 0 ? void 0 : options.preconditionOpts;
    }
    /**
     * The object's Cloud Storage URI (`gs://`)
     *
     * @example
     * ```ts
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('my-bucket');
     * const file = bucket.file('image.png');
     *
     * // `gs://my-bucket/image.png`
     * const href = file.cloudStorageURI.href;
     * ```
     */
    get cloudStorageURI() {
        const uri = this.bucket.cloudStorageURI;
        uri.pathname = this.name;
        return uri;
    }
    /**
     * A helper method for determining if a request should be retried based on preconditions.
     * This should only be used for methods where the idempotency is determined by
     * `ifGenerationMatch`
     * @private
     *
     * A request should not be retried under the following conditions:
     * - if precondition option `ifGenerationMatch` is not set OR
     * - if `idempotencyStrategy` is set to `RetryNever`
     */
    shouldRetryBasedOnPreconditionAndIdempotencyStrat(options) {
        var _a;
        return !(((options === null || options === void 0 ? void 0 : options.ifGenerationMatch) === undefined &&
            ((_a = this.instancePreconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) === undefined &&
            this.storage.retryOptions.idempotencyStrategy ===
                storage_1.IdempotencyStrategy.RetryConditional) ||
            this.storage.retryOptions.idempotencyStrategy ===
                storage_1.IdempotencyStrategy.RetryNever);
    }
    /**
     * @typedef {array} CopyResponse
     * @property {File} 0 The copied {@link File}.
     * @property {object} 1 The full API response.
     */
    /**
     * @callback CopyCallback
     * @param {?Error} err Request error, if any.
     * @param {File} copiedFile The copied {@link File}.
     * @param {object} apiResponse The full API response.
     */
    /**
     * @typedef {object} CopyOptions Configuration options for File#copy(). See an
     *     {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}.
     * @property {string} [cacheControl] The cacheControl setting for the new file.
     * @property {string} [contentEncoding] The contentEncoding setting for the new file.
     * @property {string} [contentType] The contentType setting for the new file.
     * @property {string} [destinationKmsKeyName] 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 {Metadata} [metadata] Metadata to specify on the copied file.
     * @property {string} [predefinedAcl] Set the ACL for the new file.
     * @property {string} [token] A previously-returned `rewriteToken` from an
     *     unfinished rewrite request.
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * Copy this file to another file. By default, this will copy the file to the
     * same bucket, but you can choose to copy it to another Bucket by providing
     * a Bucket or File object or a URL starting with "gs://".
     * The generation of the file will not be preserved.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/rewrite| Objects: rewrite API Documentation}
     *
     * @throws {Error} If the destination file is not provided.
     *
     * @param {string|Bucket|File} destination Destination file.
     * @param {CopyOptions} [options] Configuration options. See an
     * @param {CopyCallback} [callback] Callback function.
     * @returns {Promise<CopyResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     *
     * //-
     * // You can pass in a variety of types for the destination.
     * //
     * // For all of the below examples, assume we are working with the following
     * // Bucket and File objects.
     * //-
     * const bucket = storage.bucket('my-bucket');
     * const file = bucket.file('my-image.png');
     *
     * //-
     * // If you pass in a string for the destination, the file is copied to its
     * // current bucket, under the new name provided.
     * //-
     * file.copy('my-image-copy.png', function(err, copiedFile, apiResponse) {
     *   // `my-bucket` now contains:
     *   // - "my-image.png"
     *   // - "my-image-copy.png"
     *
     *   // `copiedFile` is an instance of a File object that refers to your new
     *   // file.
     * });
     *
     * //-
     * // If you pass in a string starting with "gs://" for the destination, the
     * // file is copied to the other bucket and under the new name provided.
     * //-
     * const newLocation = 'gs://another-bucket/my-image-copy.png';
     * file.copy(newLocation, function(err, copiedFile, apiResponse) {
     *   // `my-bucket` still contains:
     *   // - "my-image.png"
     *   //
     *   // `another-bucket` now contains:
     *   // - "my-image-copy.png"
     *
     *   // `copiedFile` is an instance of a File object that refers to your new
     *   // file.
     * });
     *
     * //-
     * // If you pass in a Bucket object, the file will be copied to that bucket
     * // using the same name.
     * //-
     * const anotherBucket = storage.bucket('another-bucket');
     * file.copy(anotherBucket, function(err, copiedFile, apiResponse) {
     *   // `my-bucket` still contains:
     *   // - "my-image.png"
     *   //
     *   // `another-bucket` now contains:
     *   // - "my-image.png"
     *
     *   // `copiedFile` is an instance of a File object that refers to your new
     *   // file.
     * });
     *
     * //-
     * // If you pass in a File object, you have complete control over the new
     * // bucket and filename.
     * //-
     * const anotherFile = anotherBucket.file('my-awesome-image.png');
     * file.copy(anotherFile, function(err, copiedFile, apiResponse) {
     *   // `my-bucket` still contains:
     *   // - "my-image.png"
     *   //
     *   // `another-bucket` now contains:
     *   // - "my-awesome-image.png"
     *
     *   // Note:
     *   // The `copiedFile` parameter is equal to `anotherFile`.
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.copy(newLocation).then(function(data) {
     *   const newFile = data[0];
     *   const apiResponse = data[1];
     * });
     *
     * ```
     * @example <caption>include:samples/files.js</caption>
     * region_tag:storage_copy_file
     * Another example:
     */
    copy(destination, optionsOrCallback, callback) {
        var _a, _b;
        const noDestinationError = new Error(FileExceptionMessages.DESTINATION_NO_NAME);
        if (!destination) {
            throw noDestinationError;
        }
        let options = {};
        if (typeof optionsOrCallback === 'function') {
            callback = optionsOrCallback;
        }
        else if (optionsOrCallback) {
            options = optionsOrCallback;
        }
        options = extend(true, {}, options);
        callback = callback || nodejs_common_1.util.noop;
        let destBucket;
        let destName;
        let newFile;
        if (typeof destination === 'string') {
            const parsedDestination = GS_URL_REGEXP.exec(destination);
            if (parsedDestination !== null && parsedDestination.length === 3) {
                destBucket = this.storage.bucket(parsedDestination[1]);
                destName = parsedDestination[2];
            }
            else {
                destBucket = this.bucket;
                destName = destination;
            }
        }
        else if (destination instanceof bucket_1.Bucket) {
            destBucket = destination;
            destName = this.name;
        }
        else if (destination instanceof File) {
            destBucket = destination.bucket;
            destName = destination.name;
            newFile = destination;
        }
        else {
            throw noDestinationError;
        }
        const query = {};
        if (this.generation !== undefined) {
            query.sourceGeneration = this.generation;
        }
        if (options.token !== undefined) {
            query.rewriteToken = options.token;
        }
        if (options.userProject !== undefined) {
            query.userProject = options.userProject;
            delete options.userProject;
        }
        if (options.predefinedAcl !== undefined) {
            query.destinationPredefinedAcl = options.predefinedAcl;
            delete options.predefinedAcl;
        }
        newFile = newFile || destBucket.file(destName);
        const headers = {};
        if (this.encryptionKey !== undefined) {
            headers['x-goog-copy-source-encryption-algorithm'] = 'AES256';
            headers['x-goog-copy-source-encryption-key'] = this.encryptionKeyBase64;
            headers['x-goog-copy-source-encryption-key-sha256'] =
                this.encryptionKeyHash;
        }
        if (newFile.encryptionKey !== undefined) {
            this.setEncryptionKey(newFile.encryptionKey);
        }
        else if (options.destinationKmsKeyName !== undefined) {
            query.destinationKmsKeyName = options.destinationKmsKeyName;
            delete options.destinationKmsKeyName;
        }
        else if (newFile.kmsKeyName !== undefined) {
            query.destinationKmsKeyName = newFile.kmsKeyName;
        }
        if (query.destinationKmsKeyName) {
            this.kmsKeyName = query.destinationKmsKeyName;
            const keyIndex = this.interceptors.indexOf(this.encryptionKeyInterceptor);
            if (keyIndex > -1) {
                this.interceptors.splice(keyIndex, 1);
            }
        }
        if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options === null || options === void 0 ? void 0 : options.preconditionOpts)) {
            this.storage.retryOptions.autoRetry = false;
        }
        if (((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) !== undefined) {
            query.ifGenerationMatch = (_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch;
            delete options.preconditionOpts;
        }
        this.request({
            method: 'POST',
            uri: `/rewriteTo/b/${destBucket.name}/o/${encodeURIComponent(newFile.name)}`,
            qs: query,
            json: options,
            headers,
        }, (err, resp) => {
            this.storage.retryOptions.autoRetry = this.instanceRetryValue;
            if (err) {
                callback(err, null, resp);
                return;
            }
            if (resp.rewriteToken) {
                const options = {
                    token: resp.rewriteToken,
                };
                if (query.userProject) {
                    options.userProject = query.userProject;
                }
                if (query.destinationKmsKeyName) {
                    options.destinationKmsKeyName = query.destinationKmsKeyName;
                }
                this.copy(newFile, options, callback);
                return;
            }
            callback(null, newFile, resp);
        });
    }
    /**
     * @typedef {object} CreateReadStreamOptions Configuration options for File#createReadStream.
     * @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 a
     *     CRC32c checksum. You may use MD5 if preferred, but that hash is not
     *     supported for composite objects. An error will be raised if MD5 is
     *     specified but is not available. You may also choose to skip validation
     *     completely, however this is **not recommended**.
     * @property {number} [start] A byte offset to begin the file's download
     *     from. Default is 0. NOTE: Byte ranges are inclusive; that is,
     *     `options.start = 0` and `options.end = 999` represent the first 1000
     *     bytes in a file or object. NOTE: when specifying a byte range, data
     *     integrity is not available.
     * @property {number} [end] A byte offset to stop reading the file at.
     *     NOTE: Byte ranges are inclusive; that is, `options.start = 0` and
     *     `options.end = 999` represent the first 1000 bytes in a file or object.
     *     NOTE: when specifying a byte range, data integrity is not available.
     * @property {boolean} [decompress=true] Disable auto decompression of the
     *     received data. By default this option is set to `true`.
     *     Applicable in cases where the data was uploaded with
     *     `gzip: true` option. See {@link File#createWriteStream}.
     */
    /**
     * Create a readable stream to read the contents of the remote file. It can be
     * piped to a writable stream or listened to for 'data' events to read a
     * file's contents.
     *
     * In the unlikely event there is a mismatch between what you downloaded and
     * the version in your Bucket, your error handler will receive an error with
     * code "CONTENT_DOWNLOAD_MISMATCH". If you receive this error, the best
     * recourse is to try downloading the file again.
     *
     * NOTE: Readable streams will emit the `end` event when the file is fully
     * downloaded.
     *
     * @param {CreateReadStreamOptions} [options] Configuration options.
     * @returns {ReadableStream}
     *
     * @example
     * ```
     * //-
     * // <h4>Downloading a File</h4>
     * //
     * // The example below demonstrates how we can reference a remote file, then
     * // pipe its contents to a local file. This is effectively creating a local
     * // backup of your remote data.
     * //-
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('my-bucket');
     *
     * const fs = require('fs');
     * const remoteFile = bucket.file('image.png');
     * const localFilename = '/Users/stephen/Photos/image.png';
     *
     * remoteFile.createReadStream()
     *   .on('error', function(err) {})
     *   .on('response', function(response) {
     *     // Server connected and responded with the specified status and headers.
     *    })
     *   .on('end', function() {
     *     // The file is fully downloaded.
     *   })
     *   .pipe(fs.createWriteStream(localFilename));
     *
     * //-
     * // To limit the downloaded data to only a byte range, pass an options
     * // object.
     * //-
     * const logFile = myBucket.file('access_log');
     * logFile.createReadStream({
     *     start: 10000,
     *     end: 20000
     *   })
     *   .on('error', function(err) {})
     *   .pipe(fs.createWriteStream('/Users/stephen/logfile.txt'));
     *
     * //-
     * // To read a tail byte range, specify only `options.end` as a negative
     * // number.
     * //-
     * const logFile = myBucket.file('access_log');
     * logFile.createReadStream({
     *     end: -100
     *   })
     *   .on('error', function(err) {})
     *   .pipe(fs.createWriteStream('/Users/stephen/logfile.txt'));
     * ```
     */
    createReadStream(options = {}) {
        options = Object.assign({ decompress: true }, options);
        const rangeRequest = typeof options.start === 'number' || typeof options.end === 'number';
        const tailRequest = options.end < 0;
        let validateStream = undefined;
        const throughStream = new util_1.PassThroughShim();
        let isCompressed = true;
        let crc32c = true;
        let md5 = false;
        let safeToValidate = true;
        if (typeof options.validation === 'string') {
            const value = options.validation.toLowerCase().trim();
            crc32c = value === 'crc32c';
            md5 = value === 'md5';
        }
        else if (options.validation === false) {
            crc32c = false;
        }
        const shouldRunValidation = !rangeRequest && (crc32c || md5);
        if (rangeRequest) {
            if (typeof options.validation === 'string' ||
                options.validation === true) {
                throw new Error(FileExceptionMessages.INVALID_VALIDATION_FILE_RANGE);
            }
            // Range requests can't receive data integrity checks.
            crc32c = false;
            md5 = false;
        }
        // Authenticate the request, then pipe the remote API request to the stream
        // returned to the user.
        const makeRequest = () => {
            const query = { alt: 'media' };
            if (this.generation) {
                query.generation = this.generation;
            }
            if (options.userProject) {
                query.userProject = options.userProject;
            }
            const headers = {
                'Accept-Encoding': 'gzip',
                'Cache-Control': 'no-store',
            };
            if (rangeRequest) {
                const start = typeof options.start === 'number' ? options.start : '0';
                const end = typeof options.end === 'number' ? options.end : '';
                headers.Range = `bytes=${tailRequest ? end : `${start}-${end}`}`;
            }
            const reqOpts = {
                forever: false,
                uri: '',
                headers,
                qs: query,
            };
            const hashes = {};
            this.requestStream(reqOpts)
                .on('error', err => {
                throughStream.destroy(err);
            })
                .on('response', res => {
                throughStream.emit('response', res);
                nodejs_common_1.util.handleResp(null, res, null, onResponse);
            })
                .resume();
            // We listen to the response event from the request stream so that we
            // can...
            //
            //   1) Intercept any data from going to the user if an error occurred.
            //   2) Calculate the hashes from the http.IncomingMessage response
            //   stream,
            //      which will return the bytes from the source without decompressing
            //      gzip'd content. We then send it through decompressed, if
            //      applicable, to the user.
            const onResponse = (err, _body, rawResponseStream) => {
                if (err) {
                    // Get error message from the body.
                    this.getBufferFromReadable(rawResponseStream).then(body => {
                        err.message = body.toString('utf8');
                        throughStream.destroy(err);
                    });
                    return;
                }
                rawResponseStream.on('error', onComplete);
                const headers = rawResponseStream.toJSON().headers;
                isCompressed = headers['content-encoding'] === 'gzip';
                // The object is safe to validate if:
                // 1. It was stored gzip and returned to us gzip OR
                // 2. It was never stored as gzip
                safeToValidate =
                    (headers['x-goog-stored-content-encoding'] === 'gzip' &&
                        isCompressed) ||
                        headers['x-goog-stored-content-encoding'] === 'identity';
                const transformStreams = [];
                if (shouldRunValidation) {
                    // The x-goog-hash header should be set with a crc32c and md5 hash.
                    // ex: headers['x-goog-hash'] = 'crc32c=xxxx,md5=xxxx'
                    if (typeof headers['x-goog-hash'] === 'string') {
                        headers['x-goog-hash']
                            .split(',')
                            .forEach((hashKeyValPair) => {
                            const delimiterIndex = hashKeyValPair.indexOf('=');
                            const hashType = hashKeyValPair.substr(0, delimiterIndex);
                            const hashValue = hashKeyValPair.substr(delimiterIndex + 1);
                            hashes[hashType] = hashValue;
                        });
                    }
                    validateStream = new hash_stream_validator_1.HashStreamValidator({
                        crc32c,
                        md5,
                        crc32cGenerator: this.crc32cGenerator,
                    });
                    transformStreams.push(validateStream);
                }
                if (isCompressed && options.decompress) {
                    transformStreams.push(zlib.createGunzip());
                }
                const handoffStream = new stream_1.PassThrough({
                    final: cb => {
                        // Preserving `onComplete`'s ability to
                        // destroy `throughStream` before pipeline
                        // attempts to.
                        onComplete(null)
                            .then(() => {
                            cb();
                        })
                            .catch(cb);
                    },
                });
                (0, stream_1.pipeline)(rawResponseStream, ...transformStreams, handoffStream, throughStream, onComplete);
            };
            // This is hooked to the `complete` event from the request stream. This is
            // our chance to validate the data and let the user know if anything went
            // wrong.
            let onCompleteCalled = false;
            const onComplete = async (err) => {
                if (onCompleteCalled) {
                    return;
                }
                onCompleteCalled = true;
                if (err) {
                    throughStream.destroy(err);
                    return;
                }
                if (rangeRequest || !shouldRunValidation) {
                    return;
                }
                // If we're doing validation, assume the worst-- a data integrity
                // mismatch. If not, these tests won't be performed, and we can assume
                // the best.
                // We must check if the server decompressed the data on serve because hash
                // validation is not possible in this case.
                let failed = (crc32c || md5) && safeToValidate;
                if (validateStream && safeToValidate) {
                    if (crc32c && hashes.crc32c) {
                        failed = !validateStream.test('crc32c', hashes.crc32c);
                    }
                    if (md5 && hashes.md5) {
                        failed = !validateStream.test('md5', hashes.md5);
                    }
                }
                if (md5 && !hashes.md5) {
                    const hashError = new RequestError(FileExceptionMessages.MD5_NOT_AVAILABLE);
                    hashError.code = 'MD5_NOT_AVAILABLE';
                    throughStream.destroy(hashError);
                }
                else if (failed) {
                    const mismatchError = new RequestError(FileExceptionMessages.DOWNLOAD_MISMATCH);
                    mismatchError.code = 'CONTENT_DOWNLOAD_MISMATCH';
                    throughStream.destroy(mismatchError);
                }
                else {
                    return;
                }
            };
        };
        throughStream.on('reading', makeRequest);
        return throughStream;
    }
    /**
     * @callback CreateResumableUploadCallback
     * @param {?Error} err Request error, if any.
     * @param {string} uri The resumable upload's unique session URI.
     */
    /**
     * @typedef {array} CreateResumableUploadResponse
     * @property {string} 0 The resumable upload's unique session URI.
     */
    /**
     * @typedef {object} CreateResumableUploadOptions
     * @property {object} [metadata] Metadata to set on the file.
     * @property {number} [offset] The starting byte of the upload stream for resuming an interrupted upload.
     * @property {string} [origin] Origin header to set for the upload.
     * @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 {string} [userProject] The ID of the project which will be
     *     billed for the request.
     * @property {string} [chunkSize] Create a separate request per chunk. This
     *     value is in bytes and should be a multiple of 256 KiB (2^18).
     *     {@link https://cloud.google.com/storage/docs/performing-resumable-uploads#chunked-upload| We recommend using at least 8 MiB for the chunk size.}
     */
    /**
     * Create a unique resumable upload session URI. This is the first step when
     * performing a resumable upload.
     *
     * See the {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload| Resumable upload guide}
     * for more on how the entire process works.
     *
     * <h4>Note</h4>
     *
     * If you are just looking to perform a resumable upload without worrying
     * about any of the details, see {@link File#createWriteStream}. Resumable
     * uploads are performed by default.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload| Resumable upload guide}
     *
     * @param {CreateResumableUploadOptions} [options] Configuration options.
     * @param {CreateResumableUploadCallback} [callback] Callback function.
     * @returns {Promise<CreateResumableUploadResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     * file.createResumableUpload(function(err, uri) {
     *   if (!err) {
     *     // `uri` can be used to PUT data to.
     *   }
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.createResumableUpload().then(function(data) {
     *   const uri = data[0];
     * });
     * ```
     */
    createResumableUpload(optionsOrCallback, callback) {
        var _a, _b;
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        const retryOptions = this.storage.retryOptions;
        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) {
            retryOptions.autoRetry = false;
        }
        resumableUpload.createURI({
            authClient: this.storage.authClient,
            apiEndpoint: this.storage.apiEndpoint,
            bucket: this.bucket.name,
            customRequestOptions: this.getRequestInterceptors().reduce((reqOpts, interceptorFn) => interceptorFn(reqOpts), {}),
            file: this.name,
            generation: this.generation,
            key: this.encryptionKey,
            kmsKeyName: this.kmsKeyName,
            metadata: options.metadata,
            offset: options.offset,
            origin: options.origin,
            predefinedAcl: options.predefinedAcl,
            private: options.private,
            public: options.public,
            userProject: options.userProject || this.userProject,
            retryOptions: retryOptions,
            params: (options === null || options === void 0 ? void 0 : options.preconditionOpts) || this.instancePreconditionOpts,
        }, callback);
        this.storage.retryOptions.autoRetry = this.instanceRetryValue;
    }
    /**
     * @typedef {object} CreateWriteStreamOptions Configuration options for File#createWriteStream().
     * @property {string} [contentType] Alias for
     *     `options.metadata.contentType`. If set to `auto`, the file name is used
     *     to determine the contentType.
     * @property {string|boolean} [gzip] If true, automatically gzip the file.
     *     If set to `auto`, the contentType is used to determine if the file
     * should be gzipped. This will set `options.metadata.contentEncoding` to
     * `gzip` if necessary.
     * @property {object} [metadata] See the examples below or
     *     {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}
     *     for more details.
     * @property {number} [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] Force a resumable upload. NOTE: When
     *     working with streams, the file format and size is unknown until it's
     *     completely consumed. Because of this, it's best for you to be explicit
     *     for what makes sense given your input.
     * @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 a
     *     CRC32c checksum. You may use MD5 if preferred, but that hash is not
     *     supported for composite objects. An error will be raised if MD5 is
     *     specified but is not available. You may also choose to skip validation
     *     completely, however this is **not recommended**. In addition to specifying
     *     validation type, providing `metadata.crc32c` or `metadata.md5Hash` will
     *     cause the server to perform validation in addition to client validation.
     *     NOTE: Validation is automatically skipped for objects that were
     *     uploaded using the `gzip` option and have already compressed content.
     */
    /**
     * Create a writable stream to overwrite the contents of the file in your
     * bucket.
     *
     * A File object can also be used to create files for the first time.
     *
     * Resumable uploads are automatically enabled and must be shut off explicitly
     * by setting `options.resumable` to `false`.
     *
     *
     * <p class="notice">
     *   There is some overhead when using a resumable upload that can cause
     *   noticeable performance degradation while uploading a series of small
     *   files. When uploading files less than 10MB, it is recommended that the
     *   resumable feature is disabled.
     * </p>
     *
     * NOTE: Writable streams will emit the `finish` event when the file is fully
     * uploaded.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload| Upload Options (Simple or Resumable)}
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert| Objects: insert API Documentation}
     *
     * @param {CreateWriteStreamOptions} [options] Configuration options.
     * @returns {WritableStream}
     *
     * @example
     * ```
     * const fs = require('fs');
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     *
     * //-
     * // <h4>Uploading a File</h4>
     * //
     * // Now, consider a case where we want to upload a file to your bucket. You
     * // have the option of using {@link Bucket#upload}, but that is just
     * // a convenience method which will do the following.
     * //-
     * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
     *   .pipe(file.createWriteStream())
     *   .on('error', function(err) {})
     *   .on('finish', function() {
     *     // The file upload is complete.
     *   });
     *
     * //-
     * // <h4>Uploading a File with gzip compression</h4>
     * //-
     * fs.createReadStream('/Users/stephen/site/index.html')
     *   .pipe(file.createWriteStream({ gzip: true }))
     *   .on('error', function(err) {})
     *   .on('finish', function() {
     *     // The file upload is complete.
     *   });
     *
     * //-
     * // Downloading the file with `createReadStream` will automatically decode
     * // the file.
     * //-
     *
     * //-
     * // <h4>Uploading a File with Metadata</h4>
     * //
     * // One last case you may run into is when you want to upload a file to your
     * // bucket and set its metadata at the same time. Like above, you can use
     * // {@link Bucket#upload} to do this, which is just a wrapper around
     * // the following.
     * //-
     * fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
     *   .pipe(file.createWriteStream({
     *     metadata: {
     *       contentType: 'image/jpeg',
     *       metadata: {
     *         custom: 'metadata'
     *       }
     *     }
     *   }))
     *   .on('error', function(err) {})
     *   .on('finish', function() {
     *     // The file upload is complete.
     *   });
     * ```
     */
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    createWriteStream(options = {}) {
        options = extend(true, { metadata: {} }, options);
        if (options.contentType) {
            options.metadata.contentType = options.contentType;
        }
        if (!options.metadata.contentType ||
            options.metadata.contentType === 'auto') {
            const detectedContentType = mime.getType(this.name);
            if (detectedContentType) {
                options.metadata.contentType = detectedContentType;
            }
        }
        let gzip = options.gzip;
        if (gzip === 'auto') {
            gzip = compressible(options.metadata.contentType);
        }
        if (gzip) {
            options.metadata.contentEncoding = 'gzip';
        }
        let crc32c = true;
        let md5 = false;
        if (typeof options.validation === 'string') {
            options.validation = options.validation.toLowerCase();
            crc32c = options.validation === 'crc32c';
            md5 = options.validation === 'md5';
        }
        else if (options.validation === false) {
            crc32c = false;
        }
        /**
         * A callback for determining when the underlying pipeline is complete.
         * It's possible the pipeline callback could error before the write stream
         * calls `final` so by default this will destroy the write stream unless the
         * write stream sets this callback via its `final` handler.
         * @param error An optional error
         */
        let pipelineCallback = error => {
            writeStream.destroy(error || undefined);
        };
        // A stream for consumer to write to
        const writeStream = new stream_1.Writable({
            final(cb) {
                // Set the pipeline callback to this callback so the pipeline's results
                // can be populated to the consumer
                pipelineCallback = cb;
                emitStream.end();
            },
            write(chunk, encoding, cb) {
                emitStream.write(chunk, encoding, cb);
            },
        });
        const emitStream = new util_1.PassThroughShim();
        const hashCalculatingStream = new hash_stream_validator_1.HashStreamValidator({
            crc32c,
            md5,
            crc32cGenerator: this.crc32cGenerator,
        });
        const fileWriteStream = duplexify();
        let fileWriteStreamMetadataReceived = false;
        // Handing off emitted events to users
        emitStream.on('reading', () => writeStream.emit('reading'));
        emitStream.on('writing', () => writeStream.emit('writing'));
        fileWriteStream.on('progress', evt => writeStream.emit('progress', evt));
        fileWriteStream.on('response', resp => writeStream.emit('response', resp));
        fileWriteStream.once('metadata', () => {
            fileWriteStreamMetadataReceived = true;
        });
        writeStream.on('writing', () => {
            if (options.resumable === false) {
                this.startSimpleUpload_(fileWriteStream, options);
            }
            else {
                this.startResumableUpload_(fileWriteStream, options);
            }
            (0, stream_1.pipeline)(emitStream, gzip ? zlib.createGzip() : new stream_1.PassThrough(), hashCalculatingStream, fileWriteStream, async (e) => {
                if (e) {
                    return pipelineCallback(e);
                }
                // We want to make sure we've received the metadata from the server in order
                // to properly validate the object's integrity. Depending on the type of upload,
                // the stream could close before the response is returned.
                if (!fileWriteStreamMetadataReceived) {
                    try {
                        await new Promise((resolve, reject) => {
                            fileWriteStream.once('metadata', resolve);
                            fileWriteStream.once('error', reject);
                        });
                    }
                    catch (e) {
                        return pipelineCallback(e);
                    }
                }
                try {
                    await __classPrivateFieldGet(this, _File_instances, "m", _File_validateIntegrity).call(this, hashCalculatingStream, { crc32c, md5 });
                    pipelineCallback();
                }
                catch (e) {
                    pipelineCallback(e);
                }
            });
        });
        return writeStream;
    }
    delete(optionsOrCallback, cb) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        cb = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
        this.disableAutoRetryConditionallyIdempotent_(this.methods.delete, bucket_1.AvailableServiceObjectMethods.delete, options);
        super
            .delete(options)
            .then(resp => cb(null, ...resp))
            .catch(cb)
            .finally(() => {
            this.storage.retryOptions.autoRetry = this.instanceRetryValue;
        });
    }
    /**
     * @typedef {array} DownloadResponse
     * @property [0] The contents of a File.
     */
    /**
     * @callback DownloadCallback
     * @param err Request error, if any.
     * @param contents The contents of a File.
     */
    /**
     * Convenience method to download a file into memory or to a local
     * destination.
     *
     * @param {object} [options] Configuration options. The arguments match those
     *     passed to {@link File#createReadStream}.
     * @param {string} [options.destination] Local file path to write the file's
     *     contents to.
     * @param {string} [options.userProject] The ID of the project which will be
     *     billed for the request.
     * @param {DownloadCallback} [callback] Callback function.
     * @returns {Promise<DownloadResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     *
     * //-
     * // Download a file into memory. The contents will be available as the
     * second
     * // argument in the demonstration below, `contents`.
     * //-
     * file.download(function(err, contents) {});
     *
     * //-
     * // Download a file to a local destination.
     * //-
     * file.download({
     *   destination: '/Users/me/Desktop/file-backup.txt'
     * }, function(err) {});
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.download().then(function(data) {
     *   const contents = data[0];
     * });
     *
     * ```
     * @example <caption>include:samples/files.js</caption>
     * region_tag:storage_download_file
     * Another example:
     *
     * @example <caption>include:samples/encryption.js</caption>
     * region_tag:storage_download_encrypted_file
     * Example of downloading an encrypted file:
     *
     * @example <caption>include:samples/requesterPays.js</caption>
     * region_tag:storage_download_file_requester_pays
     * Example of downloading a file where the requester pays:
     */
    download(optionsOrCallback, cb) {
        let options;
        if (typeof optionsOrCallback === 'function') {
            cb = optionsOrCallback;
            options = {};
        }
        else {
            options = optionsOrCallback;
        }
        let called = false;
        const callback = ((...args) => {
            if (!called)
                cb(...args);
            called = true;
        });
        const destination = options.destination;
        delete options.destination;
        const fileStream = this.createReadStream(options);
        let receivedData = false;
        if (destination) {
            fileStream
                .on('error', callback)
                .once('data', data => {
                // We know that the file exists the server - now we can truncate/write to a file
                receivedData = true;
                const writable = fs.createWriteStream(destination);
                writable.write(data);
                fileStream
                    .pipe(writable)
                    .on('error', callback)
                    .on('finish', callback);
            })
                .on('end', () => {
                // In the case of an empty file no data will be received before the end event fires
                if (!receivedData) {
                    fs.openSync(destination, 'w');
                    callback(null, Buffer.alloc(0));
                }
            });
        }
        else {
            this.getBufferFromReadable(fileStream)
                .then(contents => callback === null || callback === void 0 ? void 0 : callback(null, contents))
                .catch(callback);
        }
    }
    /**
     * The Storage API allows you to use a custom key for server-side encryption.
     *
     * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}
     *
     * @param {string|buffer} encryptionKey An AES-256 encryption key.
     * @returns {File}
     *
     * @example
     * ```
     * const crypto = require('crypto');
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const encryptionKey = crypto.randomBytes(32);
     *
     * const fileWithCustomEncryption = myBucket.file('my-file');
     * fileWithCustomEncryption.setEncryptionKey(encryptionKey);
     *
     * const fileWithoutCustomEncryption = myBucket.file('my-file');
     *
     * fileWithCustomEncryption.save('data', function(err) {
     *   // Try to download with the File object that hasn't had
     *   // `setEncryptionKey()` called:
     *   fileWithoutCustomEncryption.download(function(err) {
     *     // We will receive an error:
     *     //   err.message === 'Bad Request'
     *
     *     // Try again with the File object we called `setEncryptionKey()` on:
     *     fileWithCustomEncryption.download(function(err, contents) {
     *       // contents.toString() === 'data'
     *     });
     *   });
     * });
     *
     * ```
     * @example <caption>include:samples/encryption.js</caption>
     * region_tag:storage_upload_encrypted_file
     * Example of uploading an encrypted file:
     *
     * @example <caption>include:samples/encryption.js</caption>
     * region_tag:storage_download_encrypted_file
     * Example of downloading an encrypted file:
     */
    setEncryptionKey(encryptionKey) {
        this.encryptionKey = encryptionKey;
        this.encryptionKeyBase64 = Buffer.from(encryptionKey).toString('base64');
        this.encryptionKeyHash = crypto
            .createHash('sha256')
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            .update(this.encryptionKeyBase64, 'base64')
            .digest('base64');
        this.encryptionKeyInterceptor = {
            request: reqOpts => {
                reqOpts.headers = reqOpts.headers || {};
                reqOpts.headers['x-goog-encryption-algorithm'] = 'AES256';
                reqOpts.headers['x-goog-encryption-key'] = this.encryptionKeyBase64;
                reqOpts.headers['x-goog-encryption-key-sha256'] =
                    this.encryptionKeyHash;
                return reqOpts;
            },
        };
        this.interceptors.push(this.encryptionKeyInterceptor);
        return this;
    }
    /**
     * @typedef {array} GetExpirationDateResponse
     * @property {date} 0 A Date object representing the earliest time this file's
     *     retention policy will expire.
     */
    /**
     * @callback GetExpirationDateCallback
     * @param {?Error} err Request error, if any.
     * @param {date} expirationDate A Date object representing the earliest time
     *     this file's retention policy will expire.
     */
    /**
     * If this bucket has a retention policy defined, use this method to get a
     * Date object representing the earliest time this file will expire.
     *
     * @param {GetExpirationDateCallback} [callback] Callback function.
     * @returns {Promise<GetExpirationDateResponse>}
     *
     * @example
     * ```
     * const storage = require('@google-cloud/storage')();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     *
     * file.getExpirationDate(function(err, expirationDate) {
     *   // expirationDate is a Date object.
     * });
     * ```
     */
    getExpirationDate(callback) {
        this.getMetadata((err, metadata, apiResponse) => {
            if (err) {
                callback(err, null, apiResponse);
                return;
            }
            if (!metadata.retentionExpirationTime) {
                const error = new Error(FileExceptionMessages.EXPIRATION_TIME_NA);
                callback(error, null, apiResponse);
                return;
            }
            callback(null, new Date(metadata.retentionExpirationTime), apiResponse);
        });
    }
    /**
     * @typedef {array} GenerateSignedPostPolicyV2Response
     * @property {object} 0 The document policy.
     */
    /**
     * @callback GenerateSignedPostPolicyV2Callback
     * @param {?Error} err Request error, if any.
     * @param {object} policy The document policy.
     */
    /**
     * Get a signed policy document to allow a user to upload data with a POST
     * request.
     *
     * 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 policy. 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/xml-api/post-object-v2| POST Object with the V2 signing process}
     *
     * @throws {Error} If an expiration timestamp from the past is given.
     * @throws {Error} If options.equals has an array with less or more than two
     *     members.
     * @throws {Error} If options.startsWith has an array with less or more than two
     *     members.
     *
     * @param {object} options Configuration options.
     * @param {array|array[]} [options.equals] Array of request parameters and
     *     their expected value (e.g. [['$<field>', '<value>']]). Values are
     *     translated into equality constraints in the conditions field of the
     *     policy document (e.g. ['eq', '$<field>', '<value>']). If only one
     *     equality condition is to be specified, options.equals can be a one-
     *     dimensional array (e.g. ['$<field>', '<value>']).
     * @param {*} options.expires - A timestamp when this policy will expire. Any
     *     value given is passed to `new Date()`.
     * @param {array|array[]} [options.startsWith] Array of request parameters and
     *     their expected prefixes (e.g. [['$<field>', '<value>']). Values are
     *     translated into starts-with constraints in the conditions field of the
     *     policy document (e.g. ['starts-with', '$<field>', '<value>']). If only
     *     one prefix condition is to be specified, options.startsWith can be a
     * one- dimensional array (e.g. ['$<field>', '<value>']).
     * @param {string} [options.acl] ACL for the object from possibly predefined
     *     ACLs.
     * @param {string} [options.successRedirect] The URL to which the user client
     *     is redirected if the upload is successful.
     * @param {string} [options.successStatus] - The status of the Google Storage
     *     response if the upload is successful (must be string).
     * @param {object} [options.contentLengthRange]
     * @param {number} [options.contentLengthRange.min] Minimum value for the
     *     request's content length.
     * @param {number} [options.contentLengthRange.max] Maximum value for the
     *     request's content length.
     * @param {GenerateSignedPostPolicyV2Callback} [callback] Callback function.
     * @returns {Promise<GenerateSignedPostPolicyV2Response>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     * const options = {
     *   equals: ['$Content-Type', 'image/jpeg'],
     *   expires: '10-25-2022',
     *   contentLengthRange: {
     *     min: 0,
     *     max: 1024
     *   }
     * };
     *
     * file.generateSignedPostPolicyV2(options, function(err, policy) {
     *   // policy.string: the policy document in plain text.
     *   // policy.base64: the policy document in base64.
     *   // policy.signature: the policy signature in base64.
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.generateSignedPostPolicyV2(options).then(function(data) {
     *   const policy = data[0];
     * });
     * ```
     */
    generateSignedPostPolicyV2(optionsOrCallback, cb) {
        const args = (0, util_1.normalize)(optionsOrCallback, cb);
        let options = args.options;
        const callback = args.callback;
        const expires = new Date(options.expires);
        if (isNaN(expires.getTime())) {
            throw new Error(storage_1.ExceptionMessages.EXPIRATION_DATE_INVALID);
        }
        if (expires.valueOf() < Date.now()) {
            throw new Error(storage_1.ExceptionMessages.EXPIRATION_DATE_PAST);
        }
        options = Object.assign({}, options);
        const conditions = [
            ['eq', '$key', this.name],
            {
                bucket: this.bucket.name,
            },
        ];
        if (Array.isArray(options.equals)) {
            if (!Array.isArray(options.equals[0])) {
                options.equals = [options.equals];
            }
            options.equals.forEach(condition => {
                if (!Array.isArray(condition) || condition.length !== 2) {
                    throw new Error(FileExceptionMessages.EQUALS_CONDITION_TWO_ELEMENTS);
                }
                conditions.push(['eq', condition[0], condition[1]]);
            });
        }
        if (Array.isArray(options.startsWith)) {
            if (!Array.isArray(options.startsWith[0])) {
                options.startsWith = [options.startsWith];
            }
            options.startsWith.forEach(condition => {
                if (!Array.isArray(condition) || condition.length !== 2) {
                    throw new Error(FileExceptionMessages.STARTS_WITH_TWO_ELEMENTS);
                }
                conditions.push(['starts-with', condition[0], condition[1]]);
            });
        }
        if (options.acl) {
            conditions.push({
                acl: options.acl,
            });
        }
        if (options.successRedirect) {
            conditions.push({
                success_action_redirect: options.successRedirect,
            });
        }
        if (options.successStatus) {
            conditions.push({
                success_action_status: options.successStatus,
            });
        }
        if (options.contentLengthRange) {
            const min = options.contentLengthRange.min;
            const max = options.contentLengthRange.max;
            if (typeof min !== 'number' || typeof max !== 'number') {
                throw new Error(FileExceptionMessages.CONTENT_LENGTH_RANGE_MIN_MAX);
            }
            conditions.push(['content-length-range', min, max]);
        }
        const policy = {
            expiration: expires.toISOString(),
            conditions,
        };
        const policyString = JSON.stringify(policy);
        const policyBase64 = Buffer.from(policyString).toString('base64');
        this.storage.authClient.sign(policyBase64).then(signature => {
            callback(null, {
                string: policyString,
                base64: policyBase64,
                signature,
            });
        }, err => {
            callback(new signer_1.SigningError(err.message));
        });
    }
    /**
     * @typedef {object} SignedPostPolicyV4Output
     * @property {string} url The request URL.
     * @property {object} fields The form fields to include in the POST request.
     */
    /**
     * @typedef {array} GenerateSignedPostPolicyV4Response
     * @property {SignedPostPolicyV4Output} 0 An object containing the request URL and form fields.
     */
    /**
     * @callback GenerateSignedPostPolicyV4Callback
     * @param {?Error} err Request error, if any.
     * @param {SignedPostPolicyV4Output} output An object containing the request URL and form fields.
     */
    /**
     * Get a v4 signed policy document to allow a user to upload data with a POST
     * request.
     *
     * 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 policy. 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/xml-api/post-object#policydocument| Policy Document Reference}
     *
     * @param {object} options Configuration options.
     * @param {Date|number|string} options.expires - A timestamp when this policy will expire. Any
     *     value given is passed to `new Date()`.
     * @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 instead of path-style URL.
     *     Currently defaults to `false` for path-style, although this may change in a
     *     future major-version release.
     * @param {string} [config.bucketBoundHostname] The bucket-bound hostname to return in
     *     the result, e.g. "https://cdn.example.com".
     * @param {object} [config.fields] [Form fields]{@link https://cloud.google.com/storage/docs/xml-api/post-object#policydocument}
     *     to include in the signed policy. Any fields with key beginning with 'x-ignore-'
     *     will not be included in the policy to be signed.
     * @param {object[]} [config.conditions] [Conditions]{@link https://cloud.google.com/storage/docs/authentication/signatures#policy-document}
     *     to include in the signed policy. All fields given in `config.fields` are
     *     automatically included in the conditions array, adding the same entry
     *     in both `fields` and `conditions` will result in duplicate entries.
     *
     * @param {GenerateSignedPostPolicyV4Callback} [callback] Callback function.
     * @returns {Promise<GenerateSignedPostPolicyV4Response>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     * const options = {
     *   expires: '10-25-2022',
     *   conditions: [
     *     ['eq', '$Content-Type', 'image/jpeg'],
     *     ['content-length-range', 0, 1024],
     *   ],
     *   fields: {
     *     acl: 'public-read',
     *     'x-goog-meta-foo': 'bar',
     *     'x-ignore-mykey': 'data'
     *   }
     * };
     *
     * file.generateSignedPostPolicyV4(options, function(err, response) {
     *   // response.url The request URL
     *   // response.fields The form fields (including the signature) to include
     *   //     to be used to upload objects by HTML forms.
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.generateSignedPostPolicyV4(options).then(function(data) {
     *   const response = data[0];
     *   // response.url The request URL
     *   // response.fields The form fields (including the signature) to include
     *   //     to be used to upload objects by HTML forms.
     * });
     * ```
     */
    generateSignedPostPolicyV4(optionsOrCallback, cb) {
        const args = (0, util_1.normalize)(optionsOrCallback, cb);
        let options = args.options;
        const callback = args.callback;
        const expires = new Date(options.expires);
        if (isNaN(expires.getTime())) {
            throw new Error(storage_1.ExceptionMessages.EXPIRATION_DATE_INVALID);
        }
        if (expires.valueOf() < Date.now()) {
            throw new Error(storage_1.ExceptionMessages.EXPIRATION_DATE_PAST);
        }
        if (expires.valueOf() - Date.now() > SEVEN_DAYS * 1000) {
            throw new Error(`Max allowed expiration is seven days (${SEVEN_DAYS} seconds).`);
        }
        options = Object.assign({}, options);
        let fields = Object.assign({}, options.fields);
        const now = new Date();
        const nowISO = (0, util_1.formatAsUTCISO)(now, true);
        const todayISO = (0, util_1.formatAsUTCISO)(now);
        const sign = async () => {
            const { client_email } = await this.storage.authClient.getCredentials();
            const credential = `${client_email}/${todayISO}/auto/storage/goog4_request`;
            fields = {
                ...fields,
                bucket: this.bucket.name,
                key: this.name,
                'x-goog-date': nowISO,
                'x-goog-credential': credential,
                'x-goog-algorithm': 'GOOG4-RSA-SHA256',
            };
            const conditions = options.conditions || [];
            Object.entries(fields).forEach(([key, value]) => {
                if (!key.startsWith('x-ignore-')) {
                    conditions.push({ [key]: value });
                }
            });
            delete fields.bucket;
            const expiration = (0, util_1.formatAsUTCISO)(expires, true, '-', ':');
            const policy = {
                conditions,
                expiration,
            };
            const policyString = (0, util_1.unicodeJSONStringify)(policy);
            const policyBase64 = Buffer.from(policyString).toString('base64');
            try {
                const signature = await this.storage.authClient.sign(policyBase64);
                const signatureHex = Buffer.from(signature, 'base64').toString('hex');
                fields['policy'] = policyBase64;
                fields['x-goog-signature'] = signatureHex;
                let url;
                if (options.virtualHostedStyle) {
                    url = `https://${this.bucket.name}.storage.googleapis.com/`;
                }
                else if (options.bucketBoundHostname) {
                    url = `${options.bucketBoundHostname}/`;
                }
                else {
                    url = `${exports.STORAGE_POST_POLICY_BASE_URL}/${this.bucket.name}/`;
                }
                return {
                    url,
                    fields,
                };
            }
            catch (err) {
                throw new signer_1.SigningError(err.message);
            }
        };
        sign().then(res => callback(null, res), callback);
    }
    /**
     * @typedef {array} GetSignedUrlResponse
     * @property {object} 0 The signed URL.
     */
    /**
     * @callback GetSignedUrlCallback
     * @param {?Error} err Request error, if any.
     * @param {object} url The signed URL.
     */
    /**
     * Get a signed URL to allow limited time access to the file.
     *
     * 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 {object} config Configuration object.
     * @param {string} config.action "read" (HTTP: GET), "write" (HTTP: PUT), or
     *     "delete" (HTTP: DELETE), "resumable" (HTTP: POST).
     *     When using "resumable", the header `X-Goog-Resumable: start` has
     *     to be sent when making a request with the signed URL.
     * @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.
     *     See [reference]{@link https://cloud.google.com/storage/docs/access-control/signed-urls#example}
     * @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".
     * @param {string} [config.contentMd5] The MD5 digest value in base64. Just like
     *     if you provide this, the client must provide this HTTP header with this same
     *     value in its request, so to if this parameter is not provided here,
     *     the client must not provide any value for this HTTP header in its request.
     * @param {string} [config.contentType] Just like if you provide this, the client
     *     must provide this HTTP header with this same value in its request, so to if
     *     this parameter is not provided here, the client must not provide any value
     *     for this HTTP header in its request.
     * @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.
     * @param {object} [config.queryParams] Additional query parameters to include
     *     in the signed URL.
     * @param {string} [config.promptSaveAs] The filename to prompt the user to
     *     save the file as when the signed url is accessed. This is ignored if
     *     `config.responseDisposition` is set.
     * @param {string} [config.responseDisposition] The
     *     {@link http://goo.gl/yMWxQV| response-content-disposition parameter} of the
     *     signed url.
     * @param {*} [config.accessibleAt=Date.now()] A timestamp when this link became usable. Any value
     *     given is passed to `new Date()`.
     *     Note: Use for 'v4' only.
     * @param {string} [config.responseType] The response-content-type parameter
     *     of 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');
     *
     * const file = myBucket.file('my-file');
     *
     * //-
     * // Generate a URL that allows temporary access to download your file.
     * //-
     * const request = require('request');
     *
     * const config = {
     *   action: 'read',
     *   expires: '03-17-2025',
     * };
     *
     * file.getSignedUrl(config, function(err, url) {
     *   if (err) {
     *     console.error(err);
     *     return;
     *   }
     *
     *   // The file is now available to read from this URL.
     *   request(url, function(err, resp) {
     *     // resp.statusCode = 200
     *   });
     * });
     *
     * //-
     * // Generate a URL that allows temporary access to download your file.
     * // Access will begin at accessibleAt and end at expires.
     * //-
     * const request = require('request');
     *
     * const config = {
     *   action: 'read',
     *   expires: '03-17-2025',
     *   accessibleAt: '03-13-2025'
     * };
     *
     * file.getSignedUrl(config, function(err, url) {
     *   if (err) {
     *     console.error(err);
     *     return;
     *   }
     *
     *   // The file will be available to read from this URL from 03-13-2025 to 03-17-2025.
     *   request(url, function(err, resp) {
     *     // resp.statusCode = 200
     *   });
     * });
     *
     * //-
     * // Generate a URL to allow write permissions. This means anyone with this
     * URL
     * // can send a POST request with new data that will overwrite the file.
     * //-
     * file.getSignedUrl({
     *   action: 'write',
     *   expires: '03-17-2025'
     * }, function(err, url) {
     *   if (err) {
     *     console.error(err);
     *     return;
     *   }
     *
     *   // The file is now available to be written to.
     *   const writeStream = request.put(url);
     *   writeStream.end('New data');
     *
     *   writeStream.on('complete', function(resp) {
     *     // Confirm the new content was saved.
     *     file.download(function(err, fileContents) {
     *       console.log('Contents:', fileContents.toString());
     *       // Contents: New data
     *     });
     *   });
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.getSignedUrl(config).then(function(data) {
     *   const url = data[0];
     * });
     *
     * ```
     * @example <caption>include:samples/files.js</caption>
     * region_tag:storage_generate_signed_url
     * Another example:
     */
    getSignedUrl(cfg, callback) {
        const method = ActionToHTTPMethod[cfg.action];
        if (!method) {
            throw new Error(storage_1.ExceptionMessages.INVALID_ACTION);
        }
        const extensionHeaders = (0, util_1.objectKeyToLowercase)(cfg.extensionHeaders || {});
        if (cfg.action === 'resumable') {
            extensionHeaders['x-goog-resumable'] = 'start';
        }
        const queryParams = Object.assign({}, cfg.queryParams);
        if (typeof cfg.responseType === 'string') {
            queryParams['response-content-type'] = cfg.responseType;
        }
        if (typeof cfg.promptSaveAs === 'string') {
            queryParams['response-content-disposition'] =
                'attachment; filename="' + cfg.promptSaveAs + '"';
        }
        if (typeof cfg.responseDisposition === 'string') {
            queryParams['response-content-disposition'] = cfg.responseDisposition;
        }
        if (this.generation) {
            queryParams['generation'] = this.generation.toString();
        }
        const signConfig = {
            method,
            expires: cfg.expires,
            accessibleAt: cfg.accessibleAt,
            extensionHeaders,
            queryParams,
            contentMd5: cfg.contentMd5,
            contentType: cfg.contentType,
        };
        if (cfg.cname) {
            signConfig.cname = cfg.cname;
        }
        if (cfg.version) {
            signConfig.version = cfg.version;
        }
        if (cfg.virtualHostedStyle) {
            signConfig.virtualHostedStyle = cfg.virtualHostedStyle;
        }
        if (!this.signer) {
            this.signer = new signer_1.URLSigner(this.storage.authClient, this.bucket, this);
        }
        this.signer
            .getSignedUrl(signConfig)
            .then(signedUrl => callback(null, signedUrl), callback);
    }
    /**
     * @callback IsPublicCallback
     * @param {?Error} err Request error, if any.
     * @param {boolean} resp Whether file is public or not.
     */
    /**
     * @typedef {array} IsPublicResponse
     * @property {boolean} 0 Whether file is public or not.
     */
    /**
     * Check whether this file is public or not by sending
     * a HEAD request without credentials.
     * No errors from the server indicates that the current
     * file is public.
     * A 403-Forbidden error {@link https://cloud.google.com/storage/docs/json_api/v1/status-codes#403_Forbidden}
     * indicates that file is private.
     * Any other non 403 error is propagated to user.
     *
     * @param {IsPublicCallback} [callback] Callback function.
     * @returns {Promise<IsPublicResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     *
     * //-
     * // Check whether the file is publicly accessible.
     * //-
     * file.isPublic(function(err, resp) {
     *   if (err) {
     *     console.error(err);
     *     return;
     *   }
     *   console.log(`the file ${file.id} is public: ${resp}`) ;
     * })
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.isPublic().then(function(data) {
     *   const resp = data[0];
     * });
     * ```
     */
    isPublic(callback) {
        var _a;
        // Build any custom headers based on the defined interceptors on the parent
        // storage object and this object
        const storageInterceptors = ((_a = this.storage) === null || _a === void 0 ? void 0 : _a.interceptors) || [];
        const fileInterceptors = this.interceptors || [];
        const allInterceptors = storageInterceptors.concat(fileInterceptors);
        const headers = allInterceptors.reduce((acc, curInterceptor) => {
            const currentHeaders = curInterceptor.request({
                uri: `${this.storage.apiEndpoint}/${this.bucket.name}/${encodeURIComponent(this.name)}`,
            });
            Object.assign(acc, currentHeaders.headers);
            return acc;
        }, {});
        nodejs_common_1.util.makeRequest({
            method: 'GET',
            uri: `${this.storage.apiEndpoint}/${this.bucket.name}/${encodeURIComponent(this.name)}`,
            headers,
        }, {
            retryOptions: this.storage.retryOptions,
        }, (err) => {
            if (err) {
                const apiError = err;
                if (apiError.code === 403) {
                    callback(null, false);
                }
                else {
                    callback(err);
                }
            }
            else {
                callback(null, true);
            }
        });
    }
    /**
     * @typedef {object} MakeFilePrivateOptions Configuration options for File#makePrivate().
     * @property {Metadata} [metadata] Define custom metadata properties to define
     *     along with the operation.
     * @property {boolean} [strict] If true, set the file to be private to
     *     only the owner user. Otherwise, it will be private to the project.
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * @callback MakeFilePrivateCallback
     * @param {?Error} err Request error, if any.
     * @param {object} apiResponse The full API response.
     */
    /**
     * @typedef {array} MakeFilePrivateResponse
     * @property {object} 0 The full API response.
     */
    /**
     * Make a file private to the project and remove all other permissions.
     * Set `options.strict` to true to make the file private to only the owner.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch| Objects: patch API Documentation}
     *
     * @param {MakeFilePrivateOptions} [options] Configuration options.
     * @param {MakeFilePrivateCallback} [callback] Callback function.
     * @returns {Promise<MakeFilePrivateResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     *
     * //-
     * // Set the file private so only project maintainers can see and modify it.
     * //-
     * file.makePrivate(function(err) {});
     *
     * //-
     * // Set the file private so only the owner can see and modify it.
     * //-
     * file.makePrivate({ strict: true }, function(err) {});
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.makePrivate().then(function(data) {
     *   const apiResponse = data[0];
     * });
     * ```
     */
    makePrivate(optionsOrCallback, callback) {
        var _a, _b;
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        const query = {
            predefinedAcl: options.strict ? 'private' : 'projectPrivate',
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
        };
        if (((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) !== undefined) {
            query.ifGenerationMatch = (_b = options.preconditionOpts) === null || _b === void 0 ? void 0 : _b.ifGenerationMatch;
            delete options.preconditionOpts;
        }
        if (options.userProject) {
            query.userProject = options.userProject;
        }
        // You aren't allowed to set both predefinedAcl & acl properties on a file,
        // so acl must explicitly be nullified, destroying all previous acls on the
        // file.
        const metadata = extend({}, options.metadata, { acl: null });
        this.setMetadata(metadata, query, callback);
    }
    /**
     * @typedef {array} MakeFilePublicResponse
     * @property {object} 0 The full API response.
     */
    /**
     * @callback MakeFilePublicCallback
     * @param {?Error} err Request error, if any.
     * @param {object} apiResponse The full API response.
     */
    /**
     * Set a file to be publicly readable and maintain all previous permissions.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert| ObjectAccessControls: insert API Documentation}
     *
     * @param {MakeFilePublicCallback} [callback] Callback function.
     * @returns {Promise<MakeFilePublicResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     *
     * file.makePublic(function(err, apiResponse) {});
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.makePublic().then(function(data) {
     *   const apiResponse = data[0];
     * });
     *
     * ```
     * @example <caption>include:samples/files.js</caption>
     * region_tag:storage_make_public
     * Another example:
     */
    makePublic(callback) {
        callback = callback || nodejs_common_1.util.noop;
        this.acl.add({
            entity: 'allUsers',
            role: 'READER',
        }, (err, acl, resp) => {
            callback(err, resp);
        });
    }
    /**
     * The public URL of this File
     * Use {@link File#makePublic} to enable anonymous access via the returned URL.
     *
     * @returns {string}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     * const file = bucket.file('my-file');
     *
     * // publicUrl will be "https://storage.googleapis.com/albums/my-file"
     * const publicUrl = file.publicUrl();
     * ```
     */
    publicUrl() {
        return `${this.storage.apiEndpoint}/${this.bucket.name}/${encodeURIComponent(this.name)}`;
    }
    /**
     * @typedef {array} MoveResponse
     * @property {File} 0 The destination File.
     * @property {object} 1 The full API response.
     */
    /**
     * @callback MoveCallback
     * @param {?Error} err Request error, if any.
     * @param {?File} destinationFile The destination File.
     * @param {object} apiResponse The full API response.
     */
    /**
     * @typedef {object} MoveOptions Configuration options for File#move(). See an
     *     {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}.
     * @param {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * Move this file to another location. By default, this will rename the file
     * and keep it in the same bucket, but you can choose to move it to another
     * Bucket by providing a Bucket or File object or a URL beginning with
     * "gs://".
     *
     * **Warning**:
     * There is currently no atomic `move` method in the Cloud Storage API,
     * so this method is a composition of {@link File#copy} (to the new
     * location) and {@link File#delete} (from the old location). While
     * unlikely, it is possible that an error returned to your callback could be
     * triggered from either one of these API calls failing, which could leave a
     * duplicate file lingering. The error message will indicate what operation
     * has failed.
     *
     * See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/copy| Objects: copy API Documentation}
     *
     * @throws {Error} If the destination file is not provided.
     *
     * @param {string|Bucket|File} destination Destination file.
     * @param {MoveCallback} [callback] Callback function.
     * @returns {Promise<MoveResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * //-
     * // You can pass in a variety of types for the destination.
     * //
     * // For all of the below examples, assume we are working with the following
     * // Bucket and File objects.
     * //-
     * const bucket = storage.bucket('my-bucket');
     * const file = bucket.file('my-image.png');
     *
     * //-
     * // If you pass in a string for the destination, the file is moved to its
     * // current bucket, under the new name provided.
     * //-
     * file.move('my-image-new.png', function(err, destinationFile, apiResponse) {
     *   // `my-bucket` no longer contains:
     *   // - "my-image.png"
     *   // but contains instead:
     *   // - "my-image-new.png"
     *
     *   // `destinationFile` is an instance of a File object that refers to your
     *   // new file.
     * });
     *
     * //-
     * // If you pass in a string starting with "gs://" for the destination, the
     * // file is copied to the other bucket and under the new name provided.
     * //-
     * const newLocation = 'gs://another-bucket/my-image-new.png';
     * file.move(newLocation, function(err, destinationFile, apiResponse) {
     *   // `my-bucket` no longer contains:
     *   // - "my-image.png"
     *   //
     *   // `another-bucket` now contains:
     *   // - "my-image-new.png"
     *
     *   // `destinationFile` is an instance of a File object that refers to your
     *   // new file.
     * });
     *
     * //-
     * // If you pass in a Bucket object, the file will be moved to that bucket
     * // using the same name.
     * //-
     * const anotherBucket = gcs.bucket('another-bucket');
     *
     * file.move(anotherBucket, function(err, destinationFile, apiResponse) {
     *   // `my-bucket` no longer contains:
     *   // - "my-image.png"
     *   //
     *   // `another-bucket` now contains:
     *   // - "my-image.png"
     *
     *   // `destinationFile` is an instance of a File object that refers to your
     *   // new file.
     * });
     *
     * //-
     * // If you pass in a File object, you have complete control over the new
     * // bucket and filename.
     * //-
     * const anotherFile = anotherBucket.file('my-awesome-image.png');
     *
     * file.move(anotherFile, function(err, destinationFile, apiResponse) {
     *   // `my-bucket` no longer contains:
     *   // - "my-image.png"
     *   //
     *   // `another-bucket` now contains:
     *   // - "my-awesome-image.png"
     *
     *   // Note:
     *   // The `destinationFile` parameter is equal to `anotherFile`.
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.move('my-image-new.png').then(function(data) {
     *   const destinationFile = data[0];
     *   const apiResponse = data[1];
     * });
     *
     * ```
     * @example <caption>include:samples/files.js</caption>
     * region_tag:storage_move_file
     * Another example:
     */
    move(destination, optionsOrCallback, callback) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        callback = callback || nodejs_common_1.util.noop;
        this.copy(destination, options, (err, destinationFile, copyApiResponse) => {
            if (err) {
                err.message = 'file#copy failed with an error - ' + err.message;
                callback(err, null, copyApiResponse);
                return;
            }
            if (this.name !== destinationFile.name ||
                this.bucket.name !== destinationFile.bucket.name) {
                this.delete(options, (err, apiResponse) => {
                    if (err) {
                        err.message = 'file#delete failed with an error - ' + err.message;
                        callback(err, destinationFile, apiResponse);
                        return;
                    }
                    callback(null, destinationFile, copyApiResponse);
                });
            }
            else {
                callback(null, destinationFile, copyApiResponse);
            }
        });
    }
    /**
     * @typedef {array} RenameResponse
     * @property {File} 0 The destination File.
     * @property {object} 1 The full API response.
     */
    /**
     * @callback RenameCallback
     * @param {?Error} err Request error, if any.
     * @param {?File} destinationFile The destination File.
     * @param {object} apiResponse The full API response.
     */
    /**
     * @typedef {object} RenameOptions Configuration options for File#move(). See an
     *     {@link https://cloud.google.com/storage/docs/json_api/v1/objects#resource| Object resource}.
     * @param {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * Rename this file.
     *
     * **Warning**:
     * There is currently no atomic `rename` method in the Cloud Storage API,
     * so this method is an alias of {@link File#move}, which in turn is a
     * composition of {@link File#copy} (to the new location) and
     * {@link File#delete} (from the old location). While
     * unlikely, it is possible that an error returned to your callback could be
     * triggered from either one of these API calls failing, which could leave a
     * duplicate file lingering. The error message will indicate what operation
     * has failed.
     *
     * @param {string|File} destinationFile Destination file.
     * @param {RenameCallback} [callback] Callback function.
     * @returns {Promise<RenameResponse>}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     *
     * //-
     * // You can pass in a string or a File object.
     * //
     * // For all of the below examples, assume we are working with the following
     * // Bucket and File objects.
     * //-
     *
     * const bucket = storage.bucket('my-bucket');
     * const file = bucket.file('my-image.png');
     *
     * //-
     * // You can pass in a string for the destinationFile.
     * //-
     * file.rename('renamed-image.png', function(err, renamedFile, apiResponse) {
     *   // `my-bucket` no longer contains:
     *   // - "my-image.png"
     *   // but contains instead:
     *   // - "renamed-image.png"
     *
     *   // `renamedFile` is an instance of a File object that refers to your
     *   // renamed file.
     * });
     *
     * //-
     * // You can pass in a File object.
     * //-
     * const anotherFile = anotherBucket.file('my-awesome-image.png');
     *
     * file.rename(anotherFile, function(err, renamedFile, apiResponse) {
     *   // `my-bucket` no longer contains:
     *   // - "my-image.png"
     *
     *   // Note:
     *   // The `renamedFile` parameter is equal to `anotherFile`.
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.rename('my-renamed-image.png').then(function(data) {
     *   const renamedFile = data[0];
     *   const apiResponse = data[1];
     * });
     * ```
     */
    rename(destinationFile, optionsOrCallback, callback) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        callback = callback || nodejs_common_1.util.noop;
        this.move(destinationFile, 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) {
        return this.parent.request.call(this, reqOpts, callback);
    }
    /**
     * @callback RotateEncryptionKeyCallback
     * @extends CopyCallback
     */
    /**
     * @typedef RotateEncryptionKeyResponse
     * @extends CopyResponse
     */
    /**
     * @param {string|buffer|object} RotateEncryptionKeyOptions Configuration options
     *     for File#rotateEncryptionKey().
     * If a string or Buffer is provided, it is interpreted as an AES-256,
     * customer-supplied encryption key. If you'd like to use a Cloud KMS key
     * name, you must specify an options object with the property name:
     * `kmsKeyName`.
     * @param {string|buffer} [options.encryptionKey] An AES-256 encryption key.
     * @param {string} [options.kmsKeyName] A Cloud KMS key name.
     */
    /**
     * This method allows you to update the encryption key associated with this
     * file.
     *
     * See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}
     *
     * @param {RotateEncryptionKeyOptions} [options] - Configuration options.
     * @param {RotateEncryptionKeyCallback} [callback]
     * @returns {Promise<File>}
     *
     * @example <caption>include:samples/encryption.js</caption>
     * region_tag:storage_rotate_encryption_key
     * Example of rotating the encryption key for this file:
     */
    rotateEncryptionKey(optionsOrCallback, callback) {
        var _a;
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        let options = {};
        if (typeof optionsOrCallback === 'string' ||
            optionsOrCallback instanceof Buffer) {
            options = {
                encryptionKey: optionsOrCallback,
            };
        }
        else if (typeof optionsOrCallback === 'object') {
            options = optionsOrCallback;
        }
        const newFile = this.bucket.file(this.id, options);
        const copyOptions = ((_a = options.preconditionOpts) === null || _a === void 0 ? void 0 : _a.ifGenerationMatch) !== undefined
            ? { preconditionOpts: options.preconditionOpts }
            : {};
        this.copy(newFile, copyOptions, callback);
    }
    /**
     * @typedef {object} SaveOptions
     * @extends CreateWriteStreamOptions
     */
    /**
     * @callback SaveCallback
     * @param {?Error} err Request error, if any.
     */
    /**
     * Write strings or buffers to a file.
     *
     * *This is a convenience method which wraps {@link File#createWriteStream}.*
     * To upload arbitrary data to a file, please use {@link File#createWriteStream} directly.
     *
     * Resumable uploads are automatically enabled and must be shut off explicitly
     * by setting `options.resumable` to `false`.
     *
     * Multipart uploads with retryable error codes will be retried 3 times with exponential backoff.
     *
     * <p class="notice">
     *   There is some overhead when using a resumable upload that can cause
     *   noticeable performance degradation while uploading a series of small
     * files. When uploading files less than 10MB, it is recommended that the
     * resumable feature is disabled.
     * </p>
     *
     * @param {string | Buffer} data The data to write to a file.
     * @param {SaveOptions} [options] See {@link File#createWriteStream}'s `options`
     *     parameter.
     * @param {SaveCallback} [callback] Callback function.
     * @returns {Promise}
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const myBucket = storage.bucket('my-bucket');
     *
     * const file = myBucket.file('my-file');
     * const contents = 'This is the contents of the file.';
     *
     * file.save(contents, function(err) {
     *   if (!err) {
     *     // File written successfully.
     *   }
     * });
     *
     * //-
     * // If the callback is omitted, we'll return a Promise.
     * //-
     * file.save(contents).then(function() {});
     * ```
     */
    save(data, optionsOrCallback, callback) {
        // tslint:enable:no-any
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        let maxRetries = this.storage.retryOptions.maxRetries;
        if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options === null || options === void 0 ? void 0 : options.preconditionOpts)) {
            maxRetries = 0;
        }
        const returnValue = retry(async (bail) => {
            await new Promise((resolve, reject) => {
                if (maxRetries === 0) {
                    this.storage.retryOptions.autoRetry = false;
                }
                const writable = this.createWriteStream(options)
                    .on('error', err => {
                    if (this.storage.retryOptions.autoRetry &&
                        this.storage.retryOptions.retryableErrorFn(err)) {
                        return reject(err);
                    }
                    else {
                        return bail(err);
                    }
                })
                    .on('finish', () => {
                    return resolve();
                });
                if (options.onUploadProgress) {
                    writable.on('progress', options.onUploadProgress);
                }
                writable.end(data);
            });
        }, {
            retries: maxRetries,
            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();
                }
            })
                .catch(callback);
        }
    }
    setMetadata(metadata, optionsOrCallback, cb) {
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        cb =
            typeof optionsOrCallback === 'function'
                ? optionsOrCallback
                : cb;
        this.disableAutoRetryConditionallyIdempotent_(this.methods.setMetadata, bucket_1.AvailableServiceObjectMethods.setMetadata, options);
        super
            .setMetadata(metadata, options)
            .then(resp => cb(null, ...resp))
            .catch(cb)
            .finally(() => {
            this.storage.retryOptions.autoRetry = this.instanceRetryValue;
        });
    }
    /**
     * @typedef {array} SetStorageClassResponse
     * @property {object} 0 The full API response.
     */
    /**
     * @typedef {object} SetStorageClassOptions Configuration options for File#setStorageClass().
     * @property {string} [userProject] The ID of the project which will be
     *     billed for the request.
     */
    /**
     * @callback SetStorageClassCallback
     * @param {?Error} err Request error, if any.
     * @param {object} apiResponse The full API response.
     */
    /**
     * Set the storage class for this file.
     *
     * See {@link https://cloud.google.com/storage/docs/per-object-storage-class| Per-Object Storage Class}
     * 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` and `regional`
     *     are now legacy and will be deprecated in the future.
     * @param {SetStorageClassOptions} [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<SetStorageClassResponse>}
     *
     * @example
     * ```
     * file.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.
     * //-
     * file.setStorageClass('nearline').then(function() {});
     * ```
     */
    setStorageClass(storageClass, optionsOrCallback, callback) {
        callback =
            typeof optionsOrCallback === 'function' ? optionsOrCallback : callback;
        const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
        const req = extend(true, {}, options);
        // In case we get input like `storageClass`, convert to `storage_class`.
        req.storageClass = storageClass
            .replace(/-/g, '_')
            .replace(/([a-z])([A-Z])/g, (_, low, up) => {
            return low + '_' + up;
        })
            .toUpperCase();
        this.copy(this, req, (err, file, apiResponse) => {
            if (err) {
                callback(err, apiResponse);
                return;
            }
            this.metadata = file.metadata;
            callback(null, apiResponse);
        });
    }
    /**
     * Set a user project to be billed for all requests made from this File
     * object.
     *
     * @param {string} userProject The user project.
     *
     * @example
     * ```
     * const {Storage} = require('@google-cloud/storage');
     * const storage = new Storage();
     * const bucket = storage.bucket('albums');
     * const file = bucket.file('my-file');
     *
     * file.setUserProject('grape-spaceship-123');
     * ```
     */
    setUserProject(userProject) {
        this.bucket.setUserProject.call(this, userProject);
    }
    /**
     * This creates a resumable-upload upload stream.
     *
     * @param {Duplexify} stream - Duplexify stream of data to pipe to the file.
     * @param {object=} options - Configuration object.
     *
     * @private
     */
    startResumableUpload_(dup, options) {
        options = extend(true, {
            metadata: {},
        }, options);
        const retryOptions = this.storage.retryOptions;
        if (!this.shouldRetryBasedOnPreconditionAndIdempotencyStrat(options === null || options === void 0 ? void 0 : options.preconditionOpts)) {
            retryOptions.autoRetry = false;
        }
        const uploadStream = resumableUpload.upload({
            authClient: this.storage.authClient,
            apiEndpoint: this.storage.apiEndpoint,
            bucket: this.bucket.name,
            customRequestOptions: this.getRequestInterceptors().reduce((reqOpts, interceptorFn) => interceptorFn(reqOpts), {}),
            file: this.name,
            generation: this.generation,
            key: this.encryptionKey,
            kmsKeyName: this.kmsKeyName,
            metadata: options.metadata,
            offset: options.offset,
            predefinedAcl: options.predefinedAcl,
            private: options.private,
            public: options.public,
            uri: options.uri,
            userProject: options.userProject || this.userProject,
            retryOptions: { ...retryOptions },
            params: (options === null || options === void 0 ? void 0 : options.preconditionOpts) || this.instancePreconditionOpts,
            chunkSize: options === null || options === void 0 ? void 0 : options.chunkSize,
        });
        uploadStream
            .on('response', resp => {
            dup.emit('response', resp);
        })
            .on('metadata', metadata => {
            this.metadata = metadata;
            dup.emit('metadata');
        })
            .on('finish', () => {
            dup.emit('complete');
        })
            .on('progress', evt => dup.emit('progress', evt));
        dup.setWritable(uploadStream);
        this.storage.retryOptions.autoRetry = this.instanceRetryValue;
    }
    /**
     * Takes a readable stream and pipes it to a remote file. Unlike
     * `startResumableUpload_`, which uses the resumable upload technique, this
     * method uses a simple upload (all or nothing).
     *
     * @param {Duplexify} dup - Duplexify stream of data to pipe to the file.
     * @param {object=} options - Configuration object.
     *
     * @private
     */
    startSimpleUpload_(dup, options) {
        options = extend(true, {
            metadata: {},
        }, options);
        const apiEndpoint = this.storage.apiEndpoint;
        const bucketName = this.bucket.name;
        const uri = `${apiEndpoint}/upload/storage/v1/b/${bucketName}/o`;
        const reqOpts = {
            qs: {
                name: this.name,
            },
            uri: uri,
        };
        if (this.generation !== undefined) {
            reqOpts.qs.ifGenerationMatch = this.generation;
        }
        if (this.kmsKeyName !== undefined) {
            reqOpts.qs.kmsKeyName = this.kmsKeyName;
        }
        if (typeof options.timeout === 'number') {
            reqOpts.timeout = options.timeout;
        }
        if (options.userProject || this.userProject) {
            reqOpts.qs.userProject = options.userProject || this.userProject;
        }
        if (options.predefinedAcl) {
            reqOpts.qs.predefinedAcl = options.predefinedAcl;
        }
        else if (options.private) {
            reqOpts.qs.predefinedAcl = 'private';
        }
        else if (options.public) {
            reqOpts.qs.predefinedAcl = 'publicRead';
        }
        Object.assign(reqOpts.qs, this.instancePreconditionOpts, options.preconditionOpts);
        nodejs_common_1.util.makeWritableStream(dup, {
            makeAuthenticatedRequest: (reqOpts) => {
                this.request(reqOpts, (err, body, resp) => {
                    if (err) {
                        dup.destroy(err);
                        return;
                    }
                    this.metadata = body;
                    dup.emit('metadata', body);
                    dup.emit('response', resp);
                    dup.emit('complete');
                });
            },
            metadata: options.metadata,
            request: reqOpts,
        });
    }
    disableAutoRetryConditionallyIdempotent_(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    coreOpts, 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.ifGenerationMatch) === undefined &&
            (localPreconditionOptions === null || localPreconditionOptions === void 0 ? void 0 : localPreconditionOptions.ifGenerationMatch) === undefined &&
            (methodType === bucket_1.AvailableServiceObjectMethods.setMetadata ||
                methodType === bucket_1.AvailableServiceObjectMethods.delete) &&
            this.storage.retryOptions.idempotencyStrategy ===
                storage_1.IdempotencyStrategy.RetryConditional) ||
            this.storage.retryOptions.idempotencyStrategy ===
                storage_1.IdempotencyStrategy.RetryNever) {
            this.storage.retryOptions.autoRetry = false;
        }
    }
    async getBufferFromReadable(readable) {
        const buf = [];
        for await (const chunk of readable) {
            buf.push(chunk);
        }
        return Buffer.concat(buf);
    }
}
exports.File = File;
_File_instances = new WeakSet(), _File_validateIntegrity = 
/**
 *
 * @param hashCalculatingStream
 * @param verify
 * @returns {boolean} Returns `true` if valid, throws with error otherwise
 */
async function _File_validateIntegrity(hashCalculatingStream, verify = {}) {
    const metadata = this.metadata;
    // If we're doing validation, assume the worst
    let dataMismatch = !!(verify.crc32c || verify.md5);
    if (verify.crc32c && metadata.crc32c) {
        dataMismatch = !hashCalculatingStream.test('crc32c', metadata.crc32c);
    }
    if (verify.md5 && metadata.md5Hash) {
        dataMismatch = !hashCalculatingStream.test('md5', metadata.md5Hash);
    }
    if (dataMismatch) {
        const errors = [];
        let code = '';
        let message = '';
        try {
            await this.delete();
            if (verify.md5 && !metadata.md5Hash) {
                code = 'MD5_NOT_AVAILABLE';
                message = FileExceptionMessages.MD5_NOT_AVAILABLE;
            }
            else {
                code = 'FILE_NO_UPLOAD';
                message = FileExceptionMessages.UPLOAD_MISMATCH;
            }
        }
        catch (e) {
            const error = e;
            code = 'FILE_NO_UPLOAD_DELETE';
            message = `${FileExceptionMessages.UPLOAD_MISMATCH_DELETE_FAIL}${error.message}`;
            errors.push(error);
        }
        const error = new RequestError(message);
        error.code = code;
        error.errors = errors;
        throw error;
    }
    return true;
};
/*! Developer Documentation
 *
 * All async methods (except for streams) will return a Promise in the event
 * that a callback is omitted.
 */
(0, promisify_1.promisifyAll)(File, {
    exclude: [
        'cloudStorageURI',
        'publicUrl',
        'request',
        'save',
        'setEncryptionKey',
        'shouldRetryBasedOnPreconditionAndIdempotencyStrat',
        'getBufferFromReadable',
    ],
});
//# sourceMappingURL=file.js.map