wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
/*! @azure/msal-browser v5.7.0 2026-04-16 */
'use strict';
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.msal = {}));
})(this, (function (exports) { 'use strict';
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const SKU = "msal.js.common";
    // default authority
    const DEFAULT_AUTHORITY = "https://login.microsoftonline.com/common/";
    const DEFAULT_AUTHORITY_HOST = "login.microsoftonline.com";
    const DEFAULT_COMMON_TENANT = "common";
    // ADFS String
    const ADFS = "adfs";
    const DSTS = "dstsv2";
    // Default AAD Instance Discovery Endpoint
    const AAD_INSTANCE_DISCOVERY_ENDPT = `${DEFAULT_AUTHORITY}discovery/instance?api-version=1.1&authorization_endpoint=`;
    // CIAM URL
    const CIAM_AUTH_URL = ".ciamlogin.com";
    const AAD_TENANT_DOMAIN_SUFFIX = ".onmicrosoft.com";
    // Resource delimiter - used for certain cache entries
    const RESOURCE_DELIM = "|";
    // Default scopes
    const OPENID_SCOPE = "openid";
    const PROFILE_SCOPE = "profile";
    const OFFLINE_ACCESS_SCOPE = "offline_access";
    const EMAIL_SCOPE = "email";
    const S256_CODE_CHALLENGE_METHOD = "S256";
    const URL_FORM_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=utf-8";
    const NOT_AVAILABLE = "Not Available";
    const FORWARD_SLASH = "/";
    const IMDS_ENDPOINT = "http://169.254.169.254/metadata/instance/compute/location";
    const IMDS_VERSION = "2020-06-01";
    const IMDS_TIMEOUT = 2000;
    const AZURE_REGION_AUTO_DISCOVER_FLAG = "TryAutoDetect";
    const REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX = "login.microsoft.com";
    const KNOWN_PUBLIC_CLOUDS = [
        "login.microsoftonline.com",
        "login.windows.net",
        "login.microsoft.com",
        "sts.windows.net",
    ];
    const SHR_NONCE_VALIDITY = 240;
    const INVALID_INSTANCE = "invalid_instance";
    const HTTP_SUCCESS = 200;
    const HTTP_CLIENT_ERROR_RANGE_START = 400;
    const HTTP_BAD_REQUEST = 400;
    const HTTP_CLIENT_ERROR_RANGE_END = 499;
    const HTTP_SERVER_ERROR_RANGE_START = 500;
    const HTTP_SERVER_ERROR_RANGE_END = 599;
    const HttpMethod = {
        GET: "GET",
        POST: "POST",
    };
    const OIDC_DEFAULT_SCOPES$1 = [
        OPENID_SCOPE,
        PROFILE_SCOPE,
        OFFLINE_ACCESS_SCOPE,
    ];
    const OIDC_SCOPES = [...OIDC_DEFAULT_SCOPES$1, EMAIL_SCOPE];
    /**
     * Request header names
     */
    const HeaderNames = {
        CONTENT_TYPE: "Content-Type",
        CONTENT_LENGTH: "Content-Length",
        RETRY_AFTER: "Retry-After",
        CCS_HEADER: "X-AnchorMailbox",
        WWWAuthenticate: "WWW-Authenticate",
        AuthenticationInfo: "Authentication-Info",
        X_MS_REQUEST_ID: "x-ms-request-id",
        X_MS_HTTP_VERSION: "x-ms-httpver",
    };
    /**
     * Persistent cache keys MSAL which stay while user is logged in.
     */
    const PersistentCacheKeys = {
        ACTIVE_ACCOUNT_FILTERS: "active-account-filters", // new cache entry for active_account for a more robust version for browser
    };
    /**
     * String constants related to AAD Authority
     */
    const AADAuthority = {
        COMMON: "common",
        ORGANIZATIONS: "organizations",
        CONSUMERS: "consumers",
    };
    /**
     * Claims request keys
     */
    const ClaimsRequestKeys = {
        ACCESS_TOKEN: "access_token",
        XMS_CC: "xms_cc",
    };
    /**
     * we considered making this "enum" in the request instead of string, however it looks like the allowed list of
     * prompt values kept changing over past couple of years. There are some undocumented prompt values for some
     * internal partners too, hence the choice of generic "string" type instead of the "enum"
     */
    const PromptValue$1 = {
        LOGIN: "login",
        SELECT_ACCOUNT: "select_account",
        CONSENT: "consent",
        NONE: "none",
        CREATE: "create",
        NO_SESSION: "no_session",
    };
    /**
     * Allowed values for response_type
     */
    const OAuthResponseType = {
        CODE: "code",
        IDTOKEN_TOKEN_REFRESHTOKEN: "id_token token refresh_token",
    };
    /**
     * allowed values for response_mode
     */
    const ResponseMode$1 = {
        QUERY: "query",
        FRAGMENT: "fragment",
        FORM_POST: "form_post",
    };
    /**
     * allowed grant_type
     */
    const GrantType = {
        AUTHORIZATION_CODE_GRANT: "authorization_code",
        REFRESH_TOKEN_GRANT: "refresh_token"};
    /**
     * Account types in Cache
     */
    const CACHE_ACCOUNT_TYPE_MSSTS = "MSSTS";
    const CACHE_ACCOUNT_TYPE_ADFS = "ADFS";
    const CACHE_ACCOUNT_TYPE_GENERIC = "Generic";
    /**
     * Separators used in cache
     */
    const CACHE_KEY_SEPARATOR$1 = "-";
    const CLIENT_INFO_SEPARATOR = ".";
    /**
     * Credential Type stored in the cache
     */
    const CredentialType = {
        ID_TOKEN: "IdToken",
        ACCESS_TOKEN: "AccessToken",
        ACCESS_TOKEN_WITH_AUTH_SCHEME: "AccessToken_With_AuthScheme",
        REFRESH_TOKEN: "RefreshToken",
    };
    /**
     * More Cache related constants
     */
    const APP_METADATA = "appmetadata";
    const CLIENT_INFO = "client_info";
    const THE_FAMILY_ID = "1";
    const AUTHORITY_METADATA_CACHE_KEY = "authority-metadata";
    const AUTHORITY_METADATA_REFRESH_TIME_SECONDS = 3600 * 24; // 24 Hours
    const AuthorityMetadataSource = {
        CONFIG: "config",
        CACHE: "cache",
        NETWORK: "network",
        HARDCODED_VALUES: "hardcoded_values",
    };
    const SERVER_TELEM_SCHEMA_VERSION = 5;
    const SERVER_TELEM_MAX_LAST_HEADER_BYTES = 330; // ESTS limit is 350B, set to 330 to provide a 20B buffer,
    const SERVER_TELEM_MAX_CACHED_ERRORS = 50; // Limit the number of errors that can be stored to prevent uncontrolled size gains
    const SERVER_TELEM_CACHE_KEY = "server-telemetry";
    const SERVER_TELEM_CATEGORY_SEPARATOR = "|";
    const SERVER_TELEM_VALUE_SEPARATOR = ",";
    const SERVER_TELEM_OVERFLOW_TRUE = "1";
    const SERVER_TELEM_OVERFLOW_FALSE = "0";
    const SERVER_TELEM_UNKNOWN_ERROR = "unknown_error";
    /**
     * Type of the authentication request
     */
    const AuthenticationScheme$1 = {
        BEARER: "Bearer",
        POP: "pop",
        SSH: "ssh-cert",
    };
    /**
     * Constants related to throttling
     */
    const DEFAULT_THROTTLE_TIME_SECONDS = 60;
    // Default maximum time to throttle in seconds, overrides what the server sends back
    const DEFAULT_MAX_THROTTLE_TIME_SECONDS = 3600;
    // Prefix for storing throttling entries
    const THROTTLING_PREFIX = "throttling";
    // Value assigned to the x-ms-lib-capability header to indicate to the server the library supports throttling
    const X_MS_LIB_CAPABILITY_VALUE = "retry-after, h429";
    /**
     * Errors
     */
    const INVALID_GRANT_ERROR = "invalid_grant";
    const CLIENT_MISMATCH_ERROR = "client_mismatch";
    /**
     * Region Discovery Sources
     */
    const RegionDiscoverySources = {
        FAILED_AUTO_DETECTION: "1",
        INTERNAL_CACHE: "2",
        ENVIRONMENT_VARIABLE: "3",
        IMDS: "4",
    };
    /**
     * Region Discovery Outcomes
     */
    const RegionDiscoveryOutcomes = {
        CONFIGURED_NO_AUTO_DETECTION: "2",
        AUTO_DETECTION_REQUESTED_SUCCESSFUL: "4",
        AUTO_DETECTION_REQUESTED_FAILED: "5",
    };
    /**
     * Specifies the reason for fetching the access token from the identity provider
     */
    const CacheOutcome = {
        // When a token is found in the cache or the cache is not supposed to be hit when making the request
        NOT_APPLICABLE: "0",
        // When the token request goes to the identity provider because force_refresh was set to true. Also occurs if claims were requested
        FORCE_REFRESH_OR_CLAIMS: "1",
        // When the token request goes to the identity provider because no cached access token exists
        NO_CACHED_ACCESS_TOKEN: "2",
        // When the token request goes to the identity provider because cached access token expired
        CACHED_ACCESS_TOKEN_EXPIRED: "3",
        // When the token request goes to the identity provider because refresh_in was used and the existing token needs to be refreshed
        PROACTIVELY_REFRESHED: "4",
    };
    const JsonWebTokenTypes$1 = {
        Jwt: "JWT",
        Jwk: "JWK",
        Pop: "pop",
    };
    // Token renewal offset default in seconds
    const DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300;
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const CLIENT_ID = "client_id";
    const REDIRECT_URI = "redirect_uri";
    const RESPONSE_TYPE = "response_type";
    const RESPONSE_MODE = "response_mode";
    const GRANT_TYPE = "grant_type";
    const CLAIMS = "claims";
    const SCOPE = "scope";
    const REFRESH_TOKEN = "refresh_token";
    const STATE = "state";
    const NONCE = "nonce";
    const PROMPT = "prompt";
    const CODE = "code";
    const CODE_CHALLENGE = "code_challenge";
    const CODE_CHALLENGE_METHOD = "code_challenge_method";
    const CODE_VERIFIER = "code_verifier";
    const CLIENT_REQUEST_ID = "client-request-id";
    const X_CLIENT_SKU = "x-client-SKU";
    const X_CLIENT_VER = "x-client-VER";
    const X_CLIENT_OS = "x-client-OS";
    const X_CLIENT_CPU = "x-client-CPU";
    const X_CLIENT_CURR_TELEM = "x-client-current-telemetry";
    const X_CLIENT_LAST_TELEM = "x-client-last-telemetry";
    const X_MS_LIB_CAPABILITY = "x-ms-lib-capability";
    const X_APP_NAME = "x-app-name";
    const X_APP_VER = "x-app-ver";
    const POST_LOGOUT_URI = "post_logout_redirect_uri";
    const ID_TOKEN_HINT = "id_token_hint";
    const CLIENT_SECRET = "client_secret";
    const CLIENT_ASSERTION = "client_assertion";
    const CLIENT_ASSERTION_TYPE = "client_assertion_type";
    const TOKEN_TYPE = "token_type";
    const REQ_CNF = "req_cnf";
    const RETURN_SPA_CODE = "return_spa_code";
    const NATIVE_BROKER = "nativebroker";
    const LOGOUT_HINT = "logout_hint";
    const SID = "sid";
    const LOGIN_HINT = "login_hint";
    const DOMAIN_HINT = "domain_hint";
    const X_CLIENT_EXTRA_SKU = "x-client-xtra-sku";
    const BROKER_CLIENT_ID = "brk_client_id";
    const BROKER_REDIRECT_URI = "brk_redirect_uri";
    const INSTANCE_AWARE = "instance_aware";
    const EAR_JWK = "ear_jwk";
    const EAR_JWE_CRYPTO = "ear_jwe_crypto";
    const RESOURCE = "resource";
    const CLI_DATA = "clidata";
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function getDefaultErrorMessage$1(code) {
        return `See https://aka.ms/msal.js.errors#${code} for details`;
    }
    /**
     * General error class thrown by the MSAL.js library.
     */
    class AuthError extends Error {
        constructor(errorCode, errorMessage, suberror) {
            const message = errorMessage ||
                (errorCode ? getDefaultErrorMessage$1(errorCode) : "");
            const errorString = message ? `${errorCode}: ${message}` : errorCode;
            super(errorString);
            Object.setPrototypeOf(this, AuthError.prototype);
            this.errorCode = errorCode || "";
            this.errorMessage = message || "";
            this.subError = suberror || "";
            this.name = "AuthError";
        }
        setCorrelationId(correlationId) {
            this.correlationId = correlationId;
        }
    }
    function createAuthError(code, additionalMessage) {
        return new AuthError(code, additionalMessage || getDefaultErrorMessage$1(code));
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Error thrown when there is an error in configuration of the MSAL.js library.
     */
    class ClientConfigurationError extends AuthError {
        constructor(errorCode) {
            super(errorCode);
            this.name = "ClientConfigurationError";
            Object.setPrototypeOf(this, ClientConfigurationError.prototype);
        }
    }
    function createClientConfigurationError(errorCode) {
        return new ClientConfigurationError(errorCode);
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * @hidden
     */
    class StringUtils {
        /**
         * Check if stringified object is empty
         * @param strObj
         */
        static isEmptyObj(strObj) {
            if (strObj) {
                try {
                    const obj = JSON.parse(strObj);
                    return Object.keys(obj).length === 0;
                }
                catch (e) { }
            }
            return true;
        }
        static startsWith(str, search) {
            return str.indexOf(search) === 0;
        }
        static endsWith(str, search) {
            return (str.length >= search.length &&
                str.lastIndexOf(search) === str.length - search.length);
        }
        /**
         * Parses string into an object.
         *
         * @param query
         */
        static queryStringToObject(query) {
            const obj = {};
            const params = query.split("&");
            const decode = (s) => decodeURIComponent(s.replace(/\+/g, " "));
            params.forEach((pair) => {
                if (pair.trim()) {
                    const [key, value] = pair.split(/=(.+)/g, 2); // Split on the first occurence of the '=' character
                    if (key && value) {
                        obj[decode(key)] = decode(value);
                    }
                }
            });
            return obj;
        }
        /**
         * Trims entries in an array.
         *
         * @param arr
         */
        static trimArrayEntries(arr) {
            return arr.map((entry) => entry.trim());
        }
        /**
         * Removes empty strings from array
         * @param arr
         */
        static removeEmptyStringsFromArray(arr) {
            return arr.filter((entry) => {
                return !!entry;
            });
        }
        /**
         * Attempts to parse a string into JSON
         * @param str
         */
        static jsonParseHelper(str) {
            try {
                return JSON.parse(str);
            }
            catch (e) {
                return null;
            }
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * ClientAuthErrorMessage class containing string constants used by error codes and messages.
     */
    /**
     * Error thrown when there is an error in the client code running on the browser.
     */
    class ClientAuthError extends AuthError {
        constructor(errorCode, additionalMessage) {
            super(errorCode, additionalMessage);
            this.name = "ClientAuthError";
            Object.setPrototypeOf(this, ClientAuthError.prototype);
        }
    }
    function createClientAuthError(errorCode, additionalMessage) {
        return new ClientAuthError(errorCode, additionalMessage);
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const redirectUriEmpty = "redirect_uri_empty";
    const claimsRequestParsingError = "claims_request_parsing_error";
    const authorityUriInsecure = "authority_uri_insecure";
    const urlParseError = "url_parse_error";
    const urlEmptyError = "empty_url_error";
    const emptyInputScopesError = "empty_input_scopes_error";
    const invalidClaims = "invalid_claims";
    const tokenRequestEmpty = "token_request_empty";
    const logoutRequestEmpty = "logout_request_empty";
    const invalidCodeChallengeMethod = "invalid_code_challenge_method";
    const pkceParamsMissing = "pkce_params_missing";
    const invalidCloudDiscoveryMetadata = "invalid_cloud_discovery_metadata";
    const invalidAuthorityMetadata = "invalid_authority_metadata";
    const untrustedAuthority = "untrusted_authority";
    const missingSshJwk = "missing_ssh_jwk";
    const missingSshKid = "missing_ssh_kid";
    const missingNonceAuthenticationHeader = "missing_nonce_authentication_header";
    const invalidAuthenticationHeader = "invalid_authentication_header";
    const cannotSetOIDCOptions = "cannot_set_OIDCOptions";
    const cannotAllowPlatformBroker = "cannot_allow_platform_broker";
    const authorityMismatch = "authority_mismatch";
    const invalidRequestMethodForEAR = "invalid_request_method_for_EAR";
 
    var ClientConfigurationErrorCodes = /*#__PURE__*/Object.freeze({
        __proto__: null,
        authorityMismatch: authorityMismatch,
        authorityUriInsecure: authorityUriInsecure,
        cannotAllowPlatformBroker: cannotAllowPlatformBroker,
        cannotSetOIDCOptions: cannotSetOIDCOptions,
        claimsRequestParsingError: claimsRequestParsingError,
        emptyInputScopesError: emptyInputScopesError,
        invalidAuthenticationHeader: invalidAuthenticationHeader,
        invalidAuthorityMetadata: invalidAuthorityMetadata,
        invalidClaims: invalidClaims,
        invalidCloudDiscoveryMetadata: invalidCloudDiscoveryMetadata,
        invalidCodeChallengeMethod: invalidCodeChallengeMethod,
        invalidRequestMethodForEAR: invalidRequestMethodForEAR,
        logoutRequestEmpty: logoutRequestEmpty,
        missingNonceAuthenticationHeader: missingNonceAuthenticationHeader,
        missingSshJwk: missingSshJwk,
        missingSshKid: missingSshKid,
        pkceParamsMissing: pkceParamsMissing,
        redirectUriEmpty: redirectUriEmpty,
        tokenRequestEmpty: tokenRequestEmpty,
        untrustedAuthority: untrustedAuthority,
        urlEmptyError: urlEmptyError,
        urlParseError: urlParseError
    });
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const clientInfoDecodingError = "client_info_decoding_error";
    const clientInfoEmptyError = "client_info_empty_error";
    const tokenParsingError = "token_parsing_error";
    const nullOrEmptyToken = "null_or_empty_token";
    const endpointResolutionError = "endpoints_resolution_error";
    const networkError = "network_error";
    const openIdConfigError = "openid_config_error";
    const hashNotDeserialized = "hash_not_deserialized";
    const invalidState = "invalid_state";
    const stateMismatch = "state_mismatch";
    const stateNotFound = "state_not_found";
    const nonceMismatch = "nonce_mismatch";
    const authTimeNotFound = "auth_time_not_found";
    const maxAgeTranspired = "max_age_transpired";
    const multipleMatchingTokens = "multiple_matching_tokens";
    const multipleMatchingAppMetadata = "multiple_matching_appMetadata";
    const requestCannotBeMade = "request_cannot_be_made";
    const cannotRemoveEmptyScope = "cannot_remove_empty_scope";
    const cannotAppendScopeSet = "cannot_append_scopeset";
    const emptyInputScopeSet = "empty_input_scopeset";
    const noAccountInSilentRequest = "no_account_in_silent_request";
    const invalidCacheRecord = "invalid_cache_record";
    const invalidCacheEnvironment = "invalid_cache_environment";
    const noAccountFound = "no_account_found";
    const noCryptoObject = "no_crypto_object";
    const unexpectedCredentialType = "unexpected_credential_type";
    const tokenRefreshRequired = "token_refresh_required";
    const tokenClaimsCnfRequiredForSignedJwt = "token_claims_cnf_required_for_signedjwt";
    const authorizationCodeMissingFromServerResponse = "authorization_code_missing_from_server_response";
    const bindingKeyNotRemoved = "binding_key_not_removed";
    const endSessionEndpointNotSupported = "end_session_endpoint_not_supported";
    const keyIdMissing = "key_id_missing";
    const noNetworkConnectivity$1 = "no_network_connectivity";
    const userCanceled = "user_canceled";
    const methodNotImplemented = "method_not_implemented";
    const nestedAppAuthBridgeDisabled = "nested_app_auth_bridge_disabled";
    const platformBrokerError = "platform_broker_error";
    const resourceParameterRequired = "resource_parameter_required";
    const misplacedResourceParam = "misplaced_resource_parameter";
 
    var ClientAuthErrorCodes = /*#__PURE__*/Object.freeze({
        __proto__: null,
        authTimeNotFound: authTimeNotFound,
        authorizationCodeMissingFromServerResponse: authorizationCodeMissingFromServerResponse,
        bindingKeyNotRemoved: bindingKeyNotRemoved,
        cannotAppendScopeSet: cannotAppendScopeSet,
        cannotRemoveEmptyScope: cannotRemoveEmptyScope,
        clientInfoDecodingError: clientInfoDecodingError,
        clientInfoEmptyError: clientInfoEmptyError,
        emptyInputScopeSet: emptyInputScopeSet,
        endSessionEndpointNotSupported: endSessionEndpointNotSupported,
        endpointResolutionError: endpointResolutionError,
        hashNotDeserialized: hashNotDeserialized,
        invalidCacheEnvironment: invalidCacheEnvironment,
        invalidCacheRecord: invalidCacheRecord,
        invalidState: invalidState,
        keyIdMissing: keyIdMissing,
        maxAgeTranspired: maxAgeTranspired,
        methodNotImplemented: methodNotImplemented,
        misplacedResourceParam: misplacedResourceParam,
        multipleMatchingAppMetadata: multipleMatchingAppMetadata,
        multipleMatchingTokens: multipleMatchingTokens,
        nestedAppAuthBridgeDisabled: nestedAppAuthBridgeDisabled,
        networkError: networkError,
        noAccountFound: noAccountFound,
        noAccountInSilentRequest: noAccountInSilentRequest,
        noCryptoObject: noCryptoObject,
        noNetworkConnectivity: noNetworkConnectivity$1,
        nonceMismatch: nonceMismatch,
        nullOrEmptyToken: nullOrEmptyToken,
        openIdConfigError: openIdConfigError,
        platformBrokerError: platformBrokerError,
        requestCannotBeMade: requestCannotBeMade,
        resourceParameterRequired: resourceParameterRequired,
        stateMismatch: stateMismatch,
        stateNotFound: stateNotFound,
        tokenClaimsCnfRequiredForSignedJwt: tokenClaimsCnfRequiredForSignedJwt,
        tokenParsingError: tokenParsingError,
        tokenRefreshRequired: tokenRefreshRequired,
        unexpectedCredentialType: unexpectedCredentialType,
        userCanceled: userCanceled
    });
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * The ScopeSet class creates a set of scopes. Scopes are case-insensitive, unique values, so the Set object in JS makes
     * the most sense to implement for this class. All scopes are trimmed and converted to lower case strings in intersection and union functions
     * to ensure uniqueness of strings.
     */
    class ScopeSet {
        constructor(inputScopes) {
            // Filter empty string and null/undefined array items
            const scopeArr = inputScopes
                ? StringUtils.trimArrayEntries([...inputScopes])
                : [];
            const filteredInput = scopeArr
                ? StringUtils.removeEmptyStringsFromArray(scopeArr)
                : [];
            // Check if scopes array has at least one member
            if (!filteredInput || !filteredInput.length) {
                throw createClientConfigurationError(emptyInputScopesError);
            }
            this.scopes = new Set(); // Iterator in constructor not supported by IE11
            filteredInput.forEach((scope) => this.scopes.add(scope));
        }
        /**
         * Factory method to create ScopeSet from space-delimited string
         * @param inputScopeString
         * @param appClientId
         * @param scopesRequired
         */
        static fromString(inputScopeString) {
            const scopeString = inputScopeString || "";
            const inputScopes = scopeString.split(" ");
            return new ScopeSet(inputScopes);
        }
        /**
         * Creates the set of scopes to search for in cache lookups
         * @param inputScopeString
         * @returns
         */
        static createSearchScopes(inputScopeString) {
            // Handle empty scopes by using default OIDC scopes for cache lookup
            const scopesToUse = inputScopeString && inputScopeString.length > 0
                ? inputScopeString
                : [...OIDC_DEFAULT_SCOPES$1];
            const scopeSet = new ScopeSet(scopesToUse);
            if (!scopeSet.containsOnlyOIDCScopes()) {
                scopeSet.removeOIDCScopes();
            }
            else {
                scopeSet.removeScope(OFFLINE_ACCESS_SCOPE);
            }
            return scopeSet;
        }
        /**
         * Check if a given scope is present in this set of scopes.
         * @param scope
         */
        containsScope(scope) {
            const lowerCaseScopes = this.printScopesLowerCase().split(" ");
            const lowerCaseScopesSet = new ScopeSet(lowerCaseScopes);
            // compare lowercase scopes
            return scope
                ? lowerCaseScopesSet.scopes.has(scope.toLowerCase())
                : false;
        }
        /**
         * Check if a set of scopes is present in this set of scopes.
         * @param scopeSet
         */
        containsScopeSet(scopeSet) {
            if (!scopeSet || scopeSet.scopes.size <= 0) {
                return false;
            }
            return (this.scopes.size >= scopeSet.scopes.size &&
                scopeSet.asArray().every((scope) => this.containsScope(scope)));
        }
        /**
         * Check if set of scopes contains only the defaults
         */
        containsOnlyOIDCScopes() {
            let defaultScopeCount = 0;
            OIDC_SCOPES.forEach((defaultScope) => {
                if (this.containsScope(defaultScope)) {
                    defaultScopeCount += 1;
                }
            });
            return this.scopes.size === defaultScopeCount;
        }
        /**
         * Appends single scope if passed
         * @param newScope
         */
        appendScope(newScope) {
            if (newScope) {
                this.scopes.add(newScope.trim());
            }
        }
        /**
         * Appends multiple scopes if passed
         * @param newScopes
         */
        appendScopes(newScopes) {
            try {
                newScopes.forEach((newScope) => this.appendScope(newScope));
            }
            catch (e) {
                throw createClientAuthError(cannotAppendScopeSet);
            }
        }
        /**
         * Removes element from set of scopes.
         * @param scope
         */
        removeScope(scope) {
            if (!scope) {
                throw createClientAuthError(cannotRemoveEmptyScope);
            }
            this.scopes.delete(scope.trim());
        }
        /**
         * Removes default scopes from set of scopes
         * Primarily used to prevent cache misses if the default scopes are not returned from the server
         */
        removeOIDCScopes() {
            OIDC_SCOPES.forEach((defaultScope) => {
                this.scopes.delete(defaultScope);
            });
        }
        /**
         * Combines an array of scopes with the current set of scopes.
         * @param otherScopes
         */
        unionScopeSets(otherScopes) {
            if (!otherScopes) {
                throw createClientAuthError(emptyInputScopeSet);
            }
            const unionScopes = new Set(); // Iterator in constructor not supported in IE11
            otherScopes.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));
            this.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));
            return unionScopes;
        }
        /**
         * Check if scopes intersect between this set and another.
         * @param otherScopes
         */
        intersectingScopeSets(otherScopes) {
            if (!otherScopes) {
                throw createClientAuthError(emptyInputScopeSet);
            }
            // Do not allow OIDC scopes to be the only intersecting scopes
            if (!otherScopes.containsOnlyOIDCScopes()) {
                otherScopes.removeOIDCScopes();
            }
            const unionScopes = this.unionScopeSets(otherScopes);
            const sizeOtherScopes = otherScopes.getScopeCount();
            const sizeThisScopes = this.getScopeCount();
            const sizeUnionScopes = unionScopes.size;
            return sizeUnionScopes < sizeThisScopes + sizeOtherScopes;
        }
        /**
         * Returns size of set of scopes.
         */
        getScopeCount() {
            return this.scopes.size;
        }
        /**
         * Returns the scopes as an array of string values
         */
        asArray() {
            const array = [];
            this.scopes.forEach((val) => array.push(val));
            return array;
        }
        /**
         * Prints scopes into a space-delimited string
         */
        printScopes() {
            if (this.scopes) {
                const scopeArr = this.asArray();
                return scopeArr.join(" ");
            }
            return "";
        }
        /**
         * Prints scopes into a space-delimited lower-case string (used for caching)
         */
        printScopesLowerCase() {
            return this.printScopes().toLowerCase();
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function instrumentBrokerParams(parameters, correlationId, performanceClient) {
        if (!correlationId) {
            return;
        }
        const clientId = parameters.get(CLIENT_ID);
        if (clientId && parameters.has(BROKER_CLIENT_ID)) {
            performanceClient?.addFields({
                embeddedClientId: clientId,
                embeddedRedirectUri: parameters.get(REDIRECT_URI),
            }, correlationId);
        }
    }
    /**
     * Add the given response_type
     * @param parameters
     * @param responseType
     */
    function addResponseType(parameters, responseType) {
        parameters.set(RESPONSE_TYPE, responseType);
    }
    /**
     * add response_mode. defaults to query.
     * @param responseMode
     */
    function addResponseMode(parameters, responseMode) {
        parameters.set(RESPONSE_MODE, responseMode ? responseMode : ResponseMode$1.QUERY);
    }
    /**
     * Add flag to indicate STS should attempt to use WAM if available
     */
    function addNativeBroker(parameters) {
        parameters.set(NATIVE_BROKER, "1");
    }
    /**
     * add scopes. set addOidcScopes to false to prevent default scopes in non-user scenarios
     * @param scopeSet
     * @param addOidcScopes
     */
    function addScopes(parameters, scopes, addOidcScopes = true, defaultScopes = OIDC_DEFAULT_SCOPES$1) {
        // Always add openid to the scopes when adding OIDC scopes
        if (addOidcScopes &&
            !defaultScopes.includes("openid") &&
            !scopes.includes("openid")) {
            defaultScopes.push("openid");
        }
        const requestScopes = addOidcScopes
            ? [...(scopes || []), ...defaultScopes]
            : scopes || [];
        const scopeSet = new ScopeSet(requestScopes);
        parameters.set(SCOPE, scopeSet.printScopes());
    }
    /**
     * add clientId
     * @param clientId
     */
    function addClientId(parameters, clientId) {
        parameters.set(CLIENT_ID, clientId);
    }
    /**
     * add redirect_uri
     * @param redirectUri
     */
    function addRedirectUri(parameters, redirectUri) {
        parameters.set(REDIRECT_URI, redirectUri);
    }
    /**
     * add post logout redirectUri
     * @param redirectUri
     */
    function addPostLogoutRedirectUri(parameters, redirectUri) {
        parameters.set(POST_LOGOUT_URI, redirectUri);
    }
    /**
     * add id_token_hint to logout request
     * @param idTokenHint
     */
    function addIdTokenHint(parameters, idTokenHint) {
        parameters.set(ID_TOKEN_HINT, idTokenHint);
    }
    /**
     * add domain_hint
     * @param domainHint
     */
    function addDomainHint(parameters, domainHint) {
        parameters.set(DOMAIN_HINT, domainHint);
    }
    /**
     * add login_hint
     * @param loginHint
     */
    function addLoginHint(parameters, loginHint) {
        parameters.set(LOGIN_HINT, loginHint);
    }
    /**
     * Adds the CCS (Cache Credential Service) query parameter for login_hint
     * @param loginHint
     */
    function addCcsUpn(parameters, loginHint) {
        parameters.set(HeaderNames.CCS_HEADER, `UPN:${loginHint}`);
    }
    /**
     * Adds the CCS (Cache Credential Service) query parameter for account object
     * @param loginHint
     */
    function addCcsOid(parameters, clientInfo) {
        parameters.set(HeaderNames.CCS_HEADER, `Oid:${clientInfo.uid}@${clientInfo.utid}`);
    }
    /**
     * add sid
     * @param sid
     */
    function addSid(parameters, sid) {
        parameters.set(SID, sid);
    }
    /**
     * Adds claims to request parameters, conditionally excluding clientCapabilities
     * when skipBrokerClaims is true and a brokered flow is in effect.
     * @param parameters - The request parameters map
     * @param claims - The claims string from the request
     * @param clientCapabilities - The client capabilities from configuration
     * @param skipBrokerClaims - When true and BROKER_CLIENT_ID is present, excludes clientCapabilities from claims
     */
    function addClaims(parameters, claims, clientCapabilities, skipBrokerClaims) {
        // Skip clientCapabilities if skipBrokerClaims is set to true and this is a brokered authentication flow
        const configClaims = skipBrokerClaims && parameters.has(BROKER_CLIENT_ID)
            ? undefined
            : clientCapabilities;
        if (!StringUtils.isEmptyObj(claims) ||
            (configClaims && configClaims.length > 0)) {
            const mergedClaims = addClientCapabilitiesToClaims$1(claims, configClaims);
            try {
                JSON.parse(mergedClaims);
            }
            catch (e) {
                throw createClientConfigurationError(invalidClaims);
            }
            parameters.set(CLAIMS, mergedClaims);
        }
    }
    /**
     * add correlationId
     * @param correlationId
     */
    function addCorrelationId(parameters, correlationId) {
        parameters.set(CLIENT_REQUEST_ID, correlationId);
    }
    /**
     * add library info query params
     * @param libraryInfo
     */
    function addLibraryInfo(parameters, libraryInfo) {
        // Telemetry Info
        parameters.set(X_CLIENT_SKU, libraryInfo.sku);
        parameters.set(X_CLIENT_VER, libraryInfo.version);
        if (libraryInfo.os) {
            parameters.set(X_CLIENT_OS, libraryInfo.os);
        }
        if (libraryInfo.cpu) {
            parameters.set(X_CLIENT_CPU, libraryInfo.cpu);
        }
    }
    /**
     * Add client telemetry parameters
     * @param appTelemetry
     */
    function addApplicationTelemetry(parameters, appTelemetry) {
        if (appTelemetry?.appName) {
            parameters.set(X_APP_NAME, appTelemetry.appName);
        }
        if (appTelemetry?.appVersion) {
            parameters.set(X_APP_VER, appTelemetry.appVersion);
        }
    }
    /**
     * add prompt
     * @param prompt
     */
    function addPrompt(parameters, prompt) {
        parameters.set(PROMPT, prompt);
    }
    /**
     * add state
     * @param state
     */
    function addState(parameters, state) {
        if (state) {
            parameters.set(STATE, state);
        }
    }
    /**
     * add nonce
     * @param nonce
     */
    function addNonce(parameters, nonce) {
        parameters.set(NONCE, nonce);
    }
    /**
     * add code_challenge and code_challenge_method
     * - throw if either of them are not passed
     * @param codeChallenge
     * @param codeChallengeMethod
     */
    function addCodeChallengeParams(parameters, codeChallenge, codeChallengeMethod) {
        if (codeChallenge && codeChallengeMethod) {
            parameters.set(CODE_CHALLENGE, codeChallenge);
            parameters.set(CODE_CHALLENGE_METHOD, codeChallengeMethod);
        }
        else {
            throw createClientConfigurationError(pkceParamsMissing);
        }
    }
    /**
     * add the `authorization_code` passed by the user to exchange for a token
     * @param code
     */
    function addAuthorizationCode(parameters, code) {
        parameters.set(CODE, code);
    }
    /**
     * add the `refreshToken` passed by the user
     * @param refreshToken
     */
    function addRefreshToken(parameters, refreshToken) {
        parameters.set(REFRESH_TOKEN, refreshToken);
    }
    /**
     * add the `code_verifier` passed by the user to exchange for a token
     * @param codeVerifier
     */
    function addCodeVerifier(parameters, codeVerifier) {
        parameters.set(CODE_VERIFIER, codeVerifier);
    }
    /**
     * add client_secret
     * @param clientSecret
     */
    function addClientSecret(parameters, clientSecret) {
        parameters.set(CLIENT_SECRET, clientSecret);
    }
    /**
     * add clientAssertion for confidential client flows
     * @param clientAssertion
     */
    function addClientAssertion(parameters, clientAssertion) {
        if (clientAssertion) {
            parameters.set(CLIENT_ASSERTION, clientAssertion);
        }
    }
    /**
     * add clientAssertionType for confidential client flows
     * @param clientAssertionType
     */
    function addClientAssertionType(parameters, clientAssertionType) {
        if (clientAssertionType) {
            parameters.set(CLIENT_ASSERTION_TYPE, clientAssertionType);
        }
    }
    /**
     * add grant type
     * @param grantType
     */
    function addGrantType(parameters, grantType) {
        parameters.set(GRANT_TYPE, grantType);
    }
    /**
     * add client info
     *
     */
    function addClientInfo(parameters) {
        parameters.set(CLIENT_INFO, "1");
    }
    /**
     * add clidata=1 to request to indicate client data support
     */
    function addCliData(parameters) {
        parameters.set(CLI_DATA, "1");
    }
    function addInstanceAware(parameters) {
        if (!parameters.has(INSTANCE_AWARE)) {
            parameters.set(INSTANCE_AWARE, "true");
        }
    }
    /**
     * Add extraParameters
     * @param extraParams - String dictionary containing extra parameters to be added.
     */
    function addExtraParameters(parameters, extraParams) {
        Object.entries(extraParams).forEach(([key, value]) => {
            if (!parameters.has(key) && value) {
                parameters.set(key, value);
            }
        });
    }
    function addClientCapabilitiesToClaims$1(claims, clientCapabilities) {
        let mergedClaims;
        // Parse provided claims into JSON object or initialize empty object
        if (!claims) {
            mergedClaims = {};
        }
        else {
            try {
                mergedClaims = JSON.parse(claims);
            }
            catch (e) {
                throw createClientConfigurationError(invalidClaims);
            }
        }
        if (clientCapabilities && clientCapabilities.length > 0) {
            if (!mergedClaims.hasOwnProperty(ClaimsRequestKeys.ACCESS_TOKEN)) {
                // Add access_token key to claims object
                mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN] = {};
            }
            // Add xms_cc claim with provided clientCapabilities to access_token key
            mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN][ClaimsRequestKeys.XMS_CC] = {
                values: clientCapabilities,
            };
        }
        return JSON.stringify(mergedClaims);
    }
    /**
     * add pop_jwk to query params
     * @param cnfString
     */
    function addPopToken(parameters, cnfString) {
        if (cnfString) {
            parameters.set(TOKEN_TYPE, AuthenticationScheme$1.POP);
            parameters.set(REQ_CNF, cnfString);
        }
    }
    /**
     * add SSH JWK and key ID to query params
     */
    function addSshJwk(parameters, sshJwkString) {
        if (sshJwkString) {
            parameters.set(TOKEN_TYPE, AuthenticationScheme$1.SSH);
            parameters.set(REQ_CNF, sshJwkString);
        }
    }
    /**
     * add server telemetry fields
     * @param serverTelemetryManager
     */
    function addServerTelemetry(parameters, serverTelemetryManager) {
        parameters.set(X_CLIENT_CURR_TELEM, serverTelemetryManager.generateCurrentRequestHeaderValue());
        parameters.set(X_CLIENT_LAST_TELEM, serverTelemetryManager.generateLastRequestHeaderValue());
    }
    /**
     * Adds parameter that indicates to the server that throttling is supported
     */
    function addThrottling(parameters) {
        parameters.set(X_MS_LIB_CAPABILITY, X_MS_LIB_CAPABILITY_VALUE);
    }
    /**
     * Adds logout_hint parameter for "silent" logout which prevent server account picker
     */
    function addLogoutHint(parameters, logoutHint) {
        parameters.set(LOGOUT_HINT, logoutHint);
    }
    function addBrokerParameters(parameters, brokerClientId, brokerRedirectUri) {
        if (!parameters.has(BROKER_CLIENT_ID)) {
            parameters.set(BROKER_CLIENT_ID, brokerClientId);
        }
        if (!parameters.has(BROKER_REDIRECT_URI)) {
            parameters.set(BROKER_REDIRECT_URI, brokerRedirectUri);
        }
    }
    /**
     * Add EAR (Encrypted Authorize Response) request parameters
     * @param parameters
     * @param jwk
     */
    function addEARParameters(parameters, jwk) {
        parameters.set(EAR_JWK, encodeURIComponent(jwk));
        // ear_jwe_crypto will always have value: {"alg":"dir","enc":"A256GCM"} so we can hardcode this
        const jweCryptoB64Encoded = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0";
        parameters.set(EAR_JWE_CRYPTO, jweCryptoB64Encoded);
    }
    function addResource(parameters, resource) {
        if (resource) {
            parameters.set(RESOURCE, resource);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Canonicalizes a URL by making it lowercase and ensuring it ends with /
     * Inlined version of UrlString.canonicalizeUri to avoid circular dependency
     * @param url - URL to canonicalize
     * @returns Canonicalized URL
     */
    function canonicalizeUrl(url) {
        if (!url) {
            return url;
        }
        let lowerCaseUrl = url.toLowerCase();
        if (StringUtils.endsWith(lowerCaseUrl, "?")) {
            lowerCaseUrl = lowerCaseUrl.slice(0, -1);
        }
        else if (StringUtils.endsWith(lowerCaseUrl, "?/")) {
            lowerCaseUrl = lowerCaseUrl.slice(0, -2);
        }
        if (!StringUtils.endsWith(lowerCaseUrl, "/")) {
            lowerCaseUrl += "/";
        }
        return lowerCaseUrl;
    }
    /**
     * Parses hash string from given string. Returns empty string if no hash symbol is found.
     * @param hashString
     */
    function stripLeadingHashOrQuery(responseString) {
        if (responseString.startsWith("#/")) {
            return responseString.substring(2);
        }
        else if (responseString.startsWith("#") ||
            responseString.startsWith("?")) {
            return responseString.substring(1);
        }
        return responseString;
    }
    /**
     * Returns URL hash as server auth code response object.
     */
    function getDeserializedResponse(responseString) {
        // Check if given hash is empty
        if (!responseString || responseString.indexOf("=") < 0) {
            return null;
        }
        try {
            // Strip the # or ? symbol if present
            const normalizedResponse = stripLeadingHashOrQuery(responseString);
            // If # symbol was not present, above will return empty string, so give original hash value
            const deserializedHash = Object.fromEntries(new URLSearchParams(normalizedResponse));
            // Check for known response properties
            if (deserializedHash.code ||
                deserializedHash.ear_jwe ||
                deserializedHash.error ||
                deserializedHash.error_description ||
                deserializedHash.state) {
                return deserializedHash;
            }
        }
        catch (e) {
            throw createClientAuthError(hashNotDeserialized);
        }
        return null;
    }
    /**
     * Utility to create a URL from the params map
     */
    function mapToQueryString(parameters) {
        const queryParameterArray = new Array();
        parameters.forEach((value, key) => {
            queryParameterArray.push(`${key}=${encodeURIComponent(value)}`);
        });
        return queryParameterArray.join("&");
    }
    /**
     * Normalizes URLs for comparison by removing hash, canonicalizing,
     * and ensuring consistent URL encoding in query parameters.
     * This fixes redirect loops when URLs contain encoded characters like apostrophes (%27).
     * @param url - URL to normalize
     * @returns Normalized URL string for comparison
     */
    function normalizeUrlForComparison(url) {
        if (!url) {
            return url;
        }
        // Remove hash first
        const urlWithoutHash = url.split("#")[0];
        try {
            // Parse the URL to handle encoding consistently
            const urlObj = new URL(urlWithoutHash);
            /*
             * Reconstruct the URL with properly decoded query parameters
             * This ensures that %27 and ' are treated as equivalent
             */
            const normalizedUrl = urlObj.origin + urlObj.pathname + urlObj.search;
            // Apply canonicalization logic inline to avoid circular dependency
            return canonicalizeUrl(normalizedUrl);
        }
        catch (e) {
            // Fallback to original logic if URL parsing fails
            return canonicalizeUrl(urlWithoutHash);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const DEFAULT_CRYPTO_IMPLEMENTATION = {
        createNewGuid: () => {
            throw createClientAuthError(methodNotImplemented);
        },
        base64Decode: () => {
            throw createClientAuthError(methodNotImplemented);
        },
        base64Encode: () => {
            throw createClientAuthError(methodNotImplemented);
        },
        base64UrlEncode: () => {
            throw createClientAuthError(methodNotImplemented);
        },
        encodeKid: () => {
            throw createClientAuthError(methodNotImplemented);
        },
        async getPublicKeyThumbprint() {
            throw createClientAuthError(methodNotImplemented);
        },
        async removeTokenBindingKey() {
            throw createClientAuthError(methodNotImplemented);
        },
        async clearKeystore() {
            throw createClientAuthError(methodNotImplemented);
        },
        async signJwt() {
            throw createClientAuthError(methodNotImplemented);
        },
        async hashString() {
            throw createClientAuthError(methodNotImplemented);
        },
    };
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Log message level.
     */
    exports.LogLevel = void 0;
    (function (LogLevel) {
        LogLevel[LogLevel["Error"] = 0] = "Error";
        LogLevel[LogLevel["Warning"] = 1] = "Warning";
        LogLevel[LogLevel["Info"] = 2] = "Info";
        LogLevel[LogLevel["Verbose"] = 3] = "Verbose";
        LogLevel[LogLevel["Trace"] = 4] = "Trace";
    })(exports.LogLevel || (exports.LogLevel = {}));
    // Shared cache state for better minification - using Map's insertion order for LRU
    const CACHE_CAPACITY = 50;
    const MAX_LOGS_PER_CORRELATION = 500;
    const correlationCache = new Map();
    /**
     * Mark correlation ID as recently used by moving it to end of Map
     * @param correlationId
     * @param {CorrelationLogData} data
     */
    function markAsRecentlyUsed(correlationId, data) {
        correlationCache.delete(correlationId);
        correlationCache.set(correlationId, data);
    }
    /**
     * Add log message to cache for specific correlation ID
     * @param correlationId
     * @param {LoggedMessage} loggedMessage
     */
    function addLogToCache(correlationId, loggedMessage) {
        const currentTime = Date.now();
        let data = correlationCache.get(correlationId);
        if (data) {
            // Mark as recently used
            markAsRecentlyUsed(correlationId, data);
        }
        else {
            // Create new entry
            data = { logs: [], firstEventTime: currentTime };
            correlationCache.set(correlationId, data);
            // Remove LRU (first entry) if capacity exceeded
            if (correlationCache.size > CACHE_CAPACITY) {
                const firstKey = correlationCache.keys().next().value;
                if (firstKey) {
                    correlationCache.delete(firstKey);
                }
            }
        }
        // Add log to the data, maintaining max logs per correlation
        data.logs.push({
            ...loggedMessage,
            milliseconds: currentTime - data.firstEventTime,
        });
        if (data.logs.length > MAX_LOGS_PER_CORRELATION) {
            data.logs.shift(); // Remove oldest log
        }
    }
    /**
     * Get logs for correlation ID and flush them from cache
     * Attaches logs with empty correlation id to the requested correlation logs
     * @param correlationId
     */
    function getAndFlushLogsFromCache(correlationId) {
        const res = [];
        for (const id of ["", correlationId]) {
            const data = correlationCache.get(id);
            res.push(...(data?.logs ?? []));
            correlationCache.delete(id); // Remove the correlation ID completely from cache
        }
        return res;
    }
    /**
     * Checks if a string is already a hashed logging string (6 alphanumeric characters)
     */
    function isHashedString(str) {
        if (str.length !== 6) {
            return false;
        }
        for (let i = 0; i < str.length; i++) {
            const char = str[i];
            const isAlphaNumeric = (char >= "a" && char <= "z") ||
                (char >= "A" && char <= "Z") ||
                (char >= "0" && char <= "9");
            if (!isAlphaNumeric) {
                return false;
            }
        }
        return true;
    }
    /**
     * Class which facilitates logging of messages to a specific place.
     */
    class Logger {
        constructor(loggerOptions, packageName, packageVersion) {
            // Current log level, defaults to info.
            this.level = exports.LogLevel.Info;
            const defaultLoggerCallback = () => {
                return;
            };
            const setLoggerOptions = loggerOptions || Logger.createDefaultLoggerOptions();
            this.localCallback =
                setLoggerOptions.loggerCallback || defaultLoggerCallback;
            this.piiLoggingEnabled = setLoggerOptions.piiLoggingEnabled || false;
            this.level =
                typeof setLoggerOptions.logLevel === "number"
                    ? setLoggerOptions.logLevel
                    : exports.LogLevel.Info;
            this.packageName = packageName || "";
            this.packageVersion = packageVersion || "";
        }
        static createDefaultLoggerOptions() {
            return {
                loggerCallback: () => {
                    // allow users to not set loggerCallback
                },
                piiLoggingEnabled: false,
                logLevel: exports.LogLevel.Info,
            };
        }
        /**
         * Create new Logger with existing configurations.
         */
        clone(packageName, packageVersion) {
            return new Logger({
                loggerCallback: this.localCallback,
                piiLoggingEnabled: this.piiLoggingEnabled,
                logLevel: this.level,
            }, packageName, packageVersion);
        }
        /**
         * Log message with required options.
         */
        logMessage(logMessage, options) {
            const correlationId = options.correlationId;
            const isHashedInput = isHashedString(logMessage);
            if (isHashedInput) {
                const loggedMessage = {
                    hash: logMessage,
                    level: options.logLevel,
                    containsPii: options.containsPii || false,
                    milliseconds: 0, // Will be calculated in addLogToCache
                };
                addLogToCache(correlationId, loggedMessage);
            }
            if (options.logLevel > this.level ||
                (!this.piiLoggingEnabled && options.containsPii)) {
                return;
            }
            const timestamp = new Date().toUTCString();
            // Add correlationId to logs if set, correlationId provided on log messages take precedence
            const logHeader = `[${timestamp}] : [${correlationId}]`;
            const log = `${logHeader} : ${this.packageName}@${this.packageVersion} : ${exports.LogLevel[options.logLevel]} - ${logMessage}`;
            this.executeCallback(options.logLevel, log, options.containsPii || false);
        }
        /**
         * Execute callback with message.
         */
        executeCallback(level, message, containsPii) {
            if (this.localCallback) {
                this.localCallback(level, message, containsPii);
            }
        }
        /**
         * Logs error messages.
         */
        error(message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Error,
                containsPii: false,
                correlationId: correlationId,
            });
        }
        /**
         * Logs error messages with PII.
         */
        errorPii(message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Error,
                containsPii: true,
                correlationId: correlationId,
            });
        }
        /**
         * Logs warning messages.
         */
        warning(message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Warning,
                containsPii: false,
                correlationId: correlationId,
            });
        }
        /**
         * Logs warning messages with PII.
         */
        warningPii(message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Warning,
                containsPii: true,
                correlationId: correlationId,
            });
        }
        /**
         * Logs info messages.
         */
        info(message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Info,
                containsPii: false,
                correlationId: correlationId,
            });
        }
        /**
         * Logs info messages with PII.
         */
        infoPii(message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Info,
                containsPii: true,
                correlationId: correlationId,
            });
        }
        /**
         * Logs verbose messages.
         */
        verbose(message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Verbose,
                containsPii: false,
                correlationId: correlationId,
            });
        }
        /**
         * Logs verbose messages with PII.
         */
        verbosePii(message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Verbose,
                containsPii: true,
                correlationId: correlationId,
            });
        }
        /**
         * Logs trace messages.
         */
        trace(message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Trace,
                containsPii: false,
                correlationId: correlationId,
            });
        }
        /**
         * Logs trace messages with PII.
         */
        tracePii(message, correlationId) {
            this.logMessage(message, {
                logLevel: exports.LogLevel.Trace,
                containsPii: true,
                correlationId: correlationId,
            });
        }
        /**
         * Returns whether PII Logging is enabled or not.
         */
        isPiiLoggingEnabled() {
            return this.piiLoggingEnabled || false;
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /* eslint-disable header/header */
    const name$1 = "@azure/msal-common";
    const version$1 = "16.5.0";
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const AzureCloudInstance = {
        // AzureCloudInstance is not specified.
        None: "none",
        // Microsoft Azure public cloud
        AzurePublic: "https://login.microsoftonline.com",
        // Microsoft PPE
        AzurePpe: "https://login.windows-ppe.net",
        // Microsoft Chinese national/regional cloud
        AzureChina: "https://login.chinacloudapi.cn",
        // Microsoft German national/regional cloud ("Black Forest")
        AzureGermany: "https://login.microsoftonline.de",
        // US Government cloud
        AzureUsGovernment: "https://login.microsoftonline.us",
    };
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Returns true if tenantId matches the utid portion of homeAccountId
     * @param tenantId
     * @param homeAccountId
     * @returns
     */
    function tenantIdMatchesHomeTenant(tenantId, homeAccountId) {
        return (!!tenantId &&
            !!homeAccountId &&
            tenantId === homeAccountId.split(".")[1]);
    }
    /**
     * Build tenant profile
     * @param homeAccountId - Home account identifier for this account object
     * @param localAccountId - Local account identifer for this account object
     * @param tenantId - Full tenant or organizational id that this account belongs to
     * @param idTokenClaims - Claims from the ID token
     * @returns
     */
    function buildTenantProfile(homeAccountId, localAccountId, tenantId, idTokenClaims) {
        if (idTokenClaims) {
            const { oid, sub, tid, name, tfp, acr, preferred_username, upn, login_hint, } = idTokenClaims;
            /**
             * Since there is no way to determine if the authority is AAD or B2C, we exhaust all the possible claims that can serve as tenant ID with the following precedence:
             * tid - TenantID claim that identifies the tenant that issued the token in AAD. Expected in all AAD ID tokens, not present in B2C ID Tokens.
             * tfp - Trust Framework Policy claim that identifies the policy that was used to authenticate the user. Functions as tenant for B2C scenarios.
             * acr - Authentication Context Class Reference claim used only with older B2C policies. Fallback in case tfp is not present, but likely won't be present anyway.
             */
            const tenantId = tid || tfp || acr || "";
            return {
                tenantId: tenantId,
                localAccountId: oid || sub || "",
                name: name,
                username: preferred_username || upn || "",
                loginHint: login_hint,
                isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId),
            };
        }
        else {
            return {
                tenantId,
                localAccountId,
                username: "",
                isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId),
            };
        }
    }
    /**
     * Replaces account info that varies by tenant profile sourced from the ID token claims passed in with the tenant-specific account info
     * @param baseAccountInfo
     * @param idTokenClaims
     * @returns
     */
    function updateAccountTenantProfileData(baseAccountInfo, tenantProfile, idTokenClaims, idTokenSecret) {
        let updatedAccountInfo = baseAccountInfo;
        // Tenant Profile overrides passed in account info
        if (tenantProfile) {
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            const { isHomeTenant, ...tenantProfileOverride } = tenantProfile;
            updatedAccountInfo = { ...baseAccountInfo, ...tenantProfileOverride };
        }
        // ID token claims override passed in account info and tenant profile
        if (idTokenClaims) {
            // Ignore isHomeTenant, loginHint, and sid which are part of tenant profile but not base account info
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            const { isHomeTenant, ...claimsSourcedTenantProfile } = buildTenantProfile(baseAccountInfo.homeAccountId, baseAccountInfo.localAccountId, baseAccountInfo.tenantId, idTokenClaims);
            updatedAccountInfo = {
                ...updatedAccountInfo,
                ...claimsSourcedTenantProfile,
                idTokenClaims: idTokenClaims,
                idToken: idTokenSecret,
            };
            return updatedAccountInfo;
        }
        return updatedAccountInfo;
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Extract token by decoding the rawToken
     *
     * @param encodedToken
     */
    function extractTokenClaims(encodedToken, base64Decode) {
        const jswPayload = getJWSPayload(encodedToken);
        // token will be decoded to get the username
        try {
            // base64Decode() should throw an error if there is an issue
            const base64Decoded = base64Decode(jswPayload);
            return JSON.parse(base64Decoded);
        }
        catch (err) {
            throw createClientAuthError(tokenParsingError);
        }
    }
    /**
     * Check if the signin_state claim contains "kmsi"
     * @param idTokenClaims
     * @returns
     */
    function isKmsi(idTokenClaims) {
        if (!idTokenClaims.signin_state) {
            return false;
        }
        /**
         * Signin_state claim known values:
         * dvc_mngd - device is managed
         * dvc_dmjd - device is domain joined
         * kmsi - user opted to "keep me signed in"
         * inknownntwk - Request made inside a known network. Don't use this, use CAE instead.
         */
        const kmsiClaims = ["kmsi", "dvc_dmjd"]; // There are some cases where kmsi may not be returned but persistent storage is still OK - allow dvc_dmjd as well
        return idTokenClaims.signin_state.some((value) => kmsiClaims.includes(value.trim().toLowerCase()));
    }
    /**
     * decode a JWT
     *
     * @param authToken
     */
    function getJWSPayload(authToken) {
        if (!authToken) {
            throw createClientAuthError(nullOrEmptyToken);
        }
        const tokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/;
        const matches = tokenPartsRegex.exec(authToken);
        if (!matches || matches.length < 4) {
            throw createClientAuthError(tokenParsingError);
        }
        /**
         * const crackedToken = {
         *  header: matches[1],
         *  JWSPayload: matches[2],
         *  JWSSig: matches[3],
         * };
         */
        return matches[2];
    }
    /**
     * Determine if the token's max_age has transpired
     */
    function checkMaxAge(authTime, maxAge) {
        /*
         * per https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
         * To force an immediate re-authentication: If an app requires that a user re-authenticate prior to access,
         * provide a value of 0 for the max_age parameter and the AS will force a fresh login.
         */
        const fiveMinuteSkew = 300000; // five minutes in milliseconds
        if (maxAge === 0 || Date.now() - fiveMinuteSkew > authTime + maxAge) {
            throw createClientAuthError(maxAgeTranspired);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Url object class which can perform various transformations on url strings.
     */
    class UrlString {
        get urlString() {
            return this._urlString;
        }
        constructor(url) {
            this._urlString = url;
            if (!this._urlString) {
                // Throws error if url is empty
                throw createClientConfigurationError(urlEmptyError);
            }
            if (!url.includes("#")) {
                this._urlString = UrlString.canonicalizeUri(url);
            }
        }
        /**
         * Ensure urls are lower case and end with a / character.
         * @param url
         */
        static canonicalizeUri(url) {
            if (url) {
                let lowerCaseUrl = url.toLowerCase();
                if (StringUtils.endsWith(lowerCaseUrl, "?")) {
                    lowerCaseUrl = lowerCaseUrl.slice(0, -1);
                }
                else if (StringUtils.endsWith(lowerCaseUrl, "?/")) {
                    lowerCaseUrl = lowerCaseUrl.slice(0, -2);
                }
                if (!StringUtils.endsWith(lowerCaseUrl, "/")) {
                    lowerCaseUrl += "/";
                }
                return lowerCaseUrl;
            }
            return url;
        }
        /**
         * Throws if urlString passed is not a valid authority URI string.
         */
        validateAsUri() {
            // Attempts to parse url for uri components
            let components;
            try {
                components = this.getUrlComponents();
            }
            catch (e) {
                throw createClientConfigurationError(urlParseError);
            }
            // Throw error if URI or path segments are not parseable.
            if (!components.HostNameAndPort || !components.PathSegments) {
                throw createClientConfigurationError(urlParseError);
            }
            // Throw error if uri is insecure.
            if (!components.Protocol ||
                components.Protocol.toLowerCase() !== "https:") {
                throw createClientConfigurationError(authorityUriInsecure);
            }
        }
        /**
         * Given a url and a query string return the url with provided query string appended
         * @param url
         * @param queryString
         */
        static appendQueryString(url, queryString) {
            if (!queryString) {
                return url;
            }
            return url.indexOf("?") < 0
                ? `${url}?${queryString}`
                : `${url}&${queryString}`;
        }
        /**
         * Returns a url with the hash removed
         * @param url
         */
        static removeHashFromUrl(url) {
            return UrlString.canonicalizeUri(url.split("#")[0]);
        }
        /**
         * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d
         * @param href The url
         * @param tenantId The tenant id to replace
         */
        replaceTenantPath(tenantId) {
            const urlObject = this.getUrlComponents();
            const pathArray = urlObject.PathSegments;
            if (tenantId &&
                pathArray.length !== 0 &&
                (pathArray[0] === AADAuthority.COMMON ||
                    pathArray[0] === AADAuthority.ORGANIZATIONS)) {
                pathArray[0] = tenantId;
            }
            return UrlString.constructAuthorityUriFromObject(urlObject);
        }
        /**
         * Parses out the components from a url string.
         * @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url.
         */
        getUrlComponents() {
            // https://gist.github.com/curtisz/11139b2cfcaef4a261e0
            const regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
            // If url string does not match regEx, we throw an error
            const match = this.urlString.match(regEx);
            if (!match) {
                throw createClientConfigurationError(urlParseError);
            }
            // Url component object
            const urlComponents = {
                Protocol: match[1],
                HostNameAndPort: match[4],
                AbsolutePath: match[5],
                QueryString: match[7],
            };
            let pathSegments = urlComponents.AbsolutePath.split("/");
            pathSegments = pathSegments.filter((val) => val && val.length > 0); // remove empty elements
            urlComponents.PathSegments = pathSegments;
            if (urlComponents.QueryString &&
                urlComponents.QueryString.endsWith("/")) {
                urlComponents.QueryString = urlComponents.QueryString.substring(0, urlComponents.QueryString.length - 1);
            }
            return urlComponents;
        }
        static getDomainFromUrl(url) {
            const regEx = RegExp("^([^:/?#]+://)?([^/?#]*)");
            const match = url.match(regEx);
            if (!match) {
                throw createClientConfigurationError(urlParseError);
            }
            return match[2];
        }
        static getAbsoluteUrl(relativeUrl, baseUrl) {
            if (relativeUrl[0] === FORWARD_SLASH) {
                const url = new UrlString(baseUrl);
                const baseComponents = url.getUrlComponents();
                return (baseComponents.Protocol +
                    "//" +
                    baseComponents.HostNameAndPort +
                    relativeUrl);
            }
            return relativeUrl;
        }
        static constructAuthorityUriFromObject(urlObject) {
            return new UrlString(urlObject.Protocol +
                "//" +
                urlObject.HostNameAndPort +
                "/" +
                urlObject.PathSegments.join("/"));
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    // Build endpoint metadata dynamically to avoid string duplication
    const endpointHosts = [
        { host: "login.microsoftonline.com" },
        {
            host: "login.chinacloudapi.cn",
            issuerHost: "login.partner.microsoftonline.cn", // Issuer differs
        },
        { host: "login.microsoftonline.us" },
        { host: "login.sovcloud-identity.fr" },
        { host: "login.sovcloud-identity.de" },
        { host: "login.sovcloud-identity.sg" },
    ];
    function buildOpenIdConfig(host, issuerHost) {
        return {
            token_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/token`,
            jwks_uri: `https://${host}/{tenantid}/discovery/v2.0/keys`,
            issuer: `https://${issuerHost}/{tenantid}/v2.0`,
            authorization_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/authorize`,
            end_session_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/logout`,
        };
    }
    const dynamicEndpointMetadata = endpointHosts.reduce((acc, { host, issuerHost }) => {
        acc[host] = buildOpenIdConfig(host, issuerHost || host);
        return acc;
    }, {});
    const rawMetdataJSON = {
        endpointMetadata: dynamicEndpointMetadata,
        instanceDiscoveryMetadata: {
            metadata: [
                {
                    preferred_network: "login.microsoftonline.com",
                    preferred_cache: "login.windows.net",
                    aliases: [
                        "login.microsoftonline.com",
                        "login.windows.net",
                        "login.microsoft.com",
                        "sts.windows.net",
                    ],
                },
                {
                    preferred_network: "login.partner.microsoftonline.cn",
                    preferred_cache: "login.partner.microsoftonline.cn",
                    aliases: [
                        "login.partner.microsoftonline.cn",
                        "login.chinacloudapi.cn",
                    ],
                },
                {
                    preferred_network: "login.microsoftonline.de",
                    preferred_cache: "login.microsoftonline.de",
                    aliases: ["login.microsoftonline.de"],
                },
                {
                    preferred_network: "login.microsoftonline.us",
                    preferred_cache: "login.microsoftonline.us",
                    aliases: [
                        "login.microsoftonline.us",
                        "login.usgovcloudapi.net",
                    ],
                },
                {
                    preferred_network: "login-us.microsoftonline.com",
                    preferred_cache: "login-us.microsoftonline.com",
                    aliases: ["login-us.microsoftonline.com"],
                },
                {
                    preferred_network: "login.sovcloud-identity.fr",
                    preferred_cache: "login.sovcloud-identity.fr",
                    aliases: ["login.sovcloud-identity.fr"],
                },
                {
                    preferred_network: "login.sovcloud-identity.de",
                    preferred_cache: "login.sovcloud-identity.de",
                    aliases: ["login.sovcloud-identity.de"],
                },
                {
                    preferred_network: "login.sovcloud-identity.sg",
                    preferred_cache: "login.sovcloud-identity.sg",
                    aliases: ["login.sovcloud-identity.sg"],
                },
            ],
        },
    };
    const EndpointMetadata = rawMetdataJSON.endpointMetadata;
    const InstanceDiscoveryMetadata = rawMetdataJSON.instanceDiscoveryMetadata;
    const InstanceDiscoveryMetadataAliases = new Set();
    InstanceDiscoveryMetadata.metadata.forEach((metadataEntry) => {
        metadataEntry.aliases.forEach((alias) => {
            InstanceDiscoveryMetadataAliases.add(alias);
        });
    });
    /**
     * Attempts to get an aliases array from the static authority metadata sources based on the canonical authority host
     * @param staticAuthorityOptions
     * @param logger
     * @returns
     */
    function getAliasesFromStaticSources(staticAuthorityOptions, logger, correlationId) {
        let staticAliases;
        const canonicalAuthority = staticAuthorityOptions.canonicalAuthority;
        if (canonicalAuthority) {
            const authorityHost = new UrlString(canonicalAuthority).getUrlComponents().HostNameAndPort;
            staticAliases =
                getAliasesFromMetadata(logger, correlationId, authorityHost, staticAuthorityOptions.cloudDiscoveryMetadata?.metadata) ||
                    getAliasesFromMetadata(logger, correlationId, authorityHost, InstanceDiscoveryMetadata.metadata) ||
                    staticAuthorityOptions.knownAuthorities;
        }
        return staticAliases || [];
    }
    /**
     * Returns aliases for from the raw cloud discovery metadata passed in
     * @param authorityHost
     * @param rawCloudDiscoveryMetadata
     * @returns
     */
    function getAliasesFromMetadata(logger, correlationId, authorityHost, cloudDiscoveryMetadata, source) {
        logger.trace("1bmquz", correlationId);
        if (authorityHost && cloudDiscoveryMetadata) {
            const metadata = getCloudDiscoveryMetadataFromNetworkResponse(cloudDiscoveryMetadata, authorityHost);
            if (metadata) {
                logger.trace("1fotbt", correlationId);
                return metadata.aliases;
            }
            else {
                logger.trace("14avvj", correlationId);
            }
        }
        return null;
    }
    /**
     * Get cloud discovery metadata for common authorities
     */
    function getCloudDiscoveryMetadataFromHardcodedValues(authorityHost) {
        const metadata = getCloudDiscoveryMetadataFromNetworkResponse(InstanceDiscoveryMetadata.metadata, authorityHost);
        return metadata;
    }
    /**
     * Searches instance discovery network response for the entry that contains the host in the aliases list
     * @param response
     * @param authority
     */
    function getCloudDiscoveryMetadataFromNetworkResponse(response, authorityHost) {
        for (let i = 0; i < response.length; i++) {
            const metadata = response[i];
            if (metadata.aliases.includes(authorityHost)) {
                return metadata;
            }
        }
        return null;
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const cacheQuotaExceeded = "cache_quota_exceeded";
    const cacheErrorUnknown = "cache_error_unknown";
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Error thrown when there is an error with the cache
     */
    class CacheError extends Error {
        constructor(errorCode, errorMessage) {
            const message = errorMessage || getDefaultErrorMessage$1(errorCode);
            super(message);
            Object.setPrototypeOf(this, CacheError.prototype);
            this.name = "CacheError";
            this.errorCode = errorCode;
            this.errorMessage = message;
        }
    }
    /**
     * Helper function to wrap browser errors in a CacheError object
     * @param e
     * @returns
     */
    function createCacheError(e) {
        if (!(e instanceof Error)) {
            return new CacheError(cacheErrorUnknown);
        }
        if (e.name === "QuotaExceededError" ||
            e.name === "NS_ERROR_DOM_QUOTA_REACHED" ||
            e.message.includes("exceeded the quota")) {
            return new CacheError(cacheQuotaExceeded);
        }
        else {
            return new CacheError(e.name, e.message);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Function to build a client info object from server clientInfo string
     * @param rawClientInfo
     * @param crypto
     */
    function buildClientInfo(rawClientInfo, base64Decode) {
        if (!rawClientInfo) {
            throw createClientAuthError(clientInfoEmptyError);
        }
        try {
            const decodedClientInfo = base64Decode(rawClientInfo);
            return JSON.parse(decodedClientInfo);
        }
        catch (e) {
            throw createClientAuthError(clientInfoDecodingError);
        }
    }
    /**
     * Function to build a client info object from cached homeAccountId string
     * @param homeAccountId
     */
    function buildClientInfoFromHomeAccountId(homeAccountId) {
        if (!homeAccountId) {
            throw createClientAuthError(clientInfoDecodingError);
        }
        const clientInfoParts = homeAccountId.split(CLIENT_INFO_SEPARATOR, 2);
        return {
            uid: clientInfoParts[0],
            utid: clientInfoParts.length < 2 ? "" : clientInfoParts[1],
        };
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Authority types supported by MSAL.
     */
    const AuthorityType = {
        Default: 0,
        Adfs: 1,
        Dsts: 2,
        Ciam: 3,
    };
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Gets tenantId from available ID token claims to set as credential realm with the following precedence:
     * 1. tid - if the token is acquired from an Azure AD tenant tid will be present
     * 2. tfp - if the token is acquired from a modern B2C tenant tfp should be present
     * 3. acr - if the token is acquired from a legacy B2C tenant acr should be present
     * Downcased to match the realm case-insensitive comparison requirements
     * @param idTokenClaims
     * @returns
     */
    function getTenantIdFromIdTokenClaims(idTokenClaims) {
        if (idTokenClaims) {
            const tenantId = idTokenClaims.tid || idTokenClaims.tfp || idTokenClaims.acr;
            return tenantId || null;
        }
        return null;
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Protocol modes supported by MSAL.
     */
    const ProtocolMode = {
        /**
         * Auth Code + PKCE with Entra ID (formerly AAD) specific optimizations and features
         */
        AAD: "AAD",
        /**
         * Auth Code + PKCE without Entra ID specific optimizations and features. For use only with non-Microsoft owned authorities.
         * Support is limited for this mode.
         */
        OIDC: "OIDC",
        /**
         * Encrypted Authorize Response (EAR) with Entra ID specific optimizations and features
         */
        EAR: "EAR",
    };
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /**
     * Returns the AccountInfo interface for this account.
     */
    function getAccountInfo(accountEntity) {
        const tenantProfiles = accountEntity.tenantProfiles || [];
        // Ensure at least the home tenant profile exists
        if (tenantProfiles.length === 0 &&
            accountEntity.realm &&
            accountEntity.localAccountId) {
            tenantProfiles.push(buildTenantProfile(accountEntity.homeAccountId, accountEntity.localAccountId, accountEntity.realm));
        }
        return {
            homeAccountId: accountEntity.homeAccountId,
            environment: accountEntity.environment,
            tenantId: accountEntity.realm,
            username: accountEntity.username,
            localAccountId: accountEntity.localAccountId,
            loginHint: accountEntity.loginHint,
            name: accountEntity.name,
            nativeAccountId: accountEntity.nativeAccountId,
            authorityType: accountEntity.authorityType,
            // Deserialize tenant profiles array into a Map
            tenantProfiles: new Map(tenantProfiles.map((tenantProfile) => {
                return [tenantProfile.tenantId, tenantProfile];
            })),
            dataBoundary: accountEntity.dataBoundary,
        };
    }
    /**
     * Build Account cache from IdToken, clientInfo and authority/policy. Associated with AAD.
     * @param accountDetails
     */
    function createAccountEntity(accountDetails, authority, base64Decode) {
        let authorityType;
        if (authority.authorityType === AuthorityType.Adfs) {
            authorityType = CACHE_ACCOUNT_TYPE_ADFS;
        }
        else if (authority.protocolMode === ProtocolMode.OIDC) {
            authorityType = CACHE_ACCOUNT_TYPE_GENERIC;
        }
        else {
            authorityType = CACHE_ACCOUNT_TYPE_MSSTS;
        }
        let clientInfo;
        let dataBoundary;
        if (accountDetails.clientInfo && base64Decode) {
            clientInfo = buildClientInfo(accountDetails.clientInfo, base64Decode);
            if (clientInfo.xms_tdbr) {
                dataBoundary = clientInfo.xms_tdbr === "EU" ? "EU" : "None";
            }
        }
        const env = accountDetails.environment ||
            (authority && authority.getPreferredCache());
        if (!env) {
            throw createClientAuthError(invalidCacheEnvironment);
        }
        /*
         * In B2C scenarios the emails claim is used instead of preferred_username and it is an array.
         * In most cases it will contain a single email. This field should not be relied upon if a custom
         * policy is configured to return more than 1 email.
         */
        const preferredUsername = accountDetails.idTokenClaims?.preferred_username ||
            accountDetails.idTokenClaims?.upn;
        const email = accountDetails.idTokenClaims?.emails
            ? accountDetails.idTokenClaims.emails[0]
            : null;
        const username = preferredUsername || email || "";
        const loginHint = accountDetails.idTokenClaims?.login_hint;
        const realm = clientInfo?.utid ||
            getTenantIdFromIdTokenClaims(accountDetails.idTokenClaims) ||
            ""; // non-AAD scenarios can have empty realm
        // How do you account for MSA CID here?
        const localAccountId = clientInfo?.uid ||
            accountDetails.idTokenClaims?.oid ||
            accountDetails.idTokenClaims?.sub ||
            "";
        let tenantProfiles;
        if (accountDetails.tenantProfiles) {
            tenantProfiles = accountDetails.tenantProfiles;
        }
        else {
            const tenantProfile = buildTenantProfile(accountDetails.homeAccountId, localAccountId, realm, accountDetails.idTokenClaims);
            tenantProfiles = [tenantProfile];
        }
        return {
            homeAccountId: accountDetails.homeAccountId,
            environment: env,
            realm: realm,
            localAccountId: localAccountId,
            username: username,
            authorityType: authorityType,
            loginHint: loginHint,
            clientInfo: accountDetails.clientInfo,
            name: accountDetails.idTokenClaims?.name || "",
            lastModificationTime: undefined,
            lastModificationApp: undefined,
            cloudGraphHostName: accountDetails.cloudGraphHostName,
            msGraphHost: accountDetails.msGraphHost,
            nativeAccountId: accountDetails.nativeAccountId,
            tenantProfiles: tenantProfiles,
            dataBoundary,
        };
    }
    /**
     * Creates an AccountEntity object from AccountInfo
     * @param accountInfo
     * @param cloudGraphHostName
     * @param msGraphHost
     * @returns
     */
    function createAccountEntityFromAccountInfo(accountInfo, cloudGraphHostName, msGraphHost) {
        // Serialize tenant profiles map into an array
        const tenantProfiles = Array.from(accountInfo.tenantProfiles?.values() || []);
        // Ensure at least the home tenant profile exists
        if (tenantProfiles.length === 0 &&
            accountInfo.tenantId &&
            accountInfo.localAccountId) {
            tenantProfiles.push(buildTenantProfile(accountInfo.homeAccountId, accountInfo.localAccountId, accountInfo.tenantId, accountInfo.idTokenClaims));
        }
        return {
            authorityType: accountInfo.authorityType || CACHE_ACCOUNT_TYPE_GENERIC,
            homeAccountId: accountInfo.homeAccountId,
            localAccountId: accountInfo.localAccountId,
            nativeAccountId: accountInfo.nativeAccountId,
            realm: accountInfo.tenantId,
            environment: accountInfo.environment,
            username: accountInfo.username,
            loginHint: accountInfo.loginHint,
            name: accountInfo.name,
            cloudGraphHostName: cloudGraphHostName,
            msGraphHost: msGraphHost,
            tenantProfiles: tenantProfiles,
            dataBoundary: accountInfo.dataBoundary,
        };
    }
    /**
     * Generate HomeAccountId from server response
     * @param serverClientInfo
     * @param authType
     */
    function generateHomeAccountId(serverClientInfo, authType, logger, cryptoObj, correlationId, idTokenClaims) {
        // since ADFS/DSTS do not have tid and does not set client_info
        if (!(authType === AuthorityType.Adfs || authType === AuthorityType.Dsts)) {
            // for cases where there is clientInfo
            if (serverClientInfo) {
                try {
                    const clientInfo = buildClientInfo(serverClientInfo, cryptoObj.base64Decode);
                    if (clientInfo.uid && clientInfo.utid) {
                        return `${clientInfo.uid}.${clientInfo.utid}`;
                    }
                }
                catch (e) { }
            }
            logger.warning("1ub6wv", correlationId);
        }
        // default to "sub" claim
        return idTokenClaims?.sub || "";
    }
    /**
     * Validates an entity: checks for all expected params
     * @param entity
     */
    function isAccountEntity(entity) {
        if (!entity) {
            return false;
        }
        return (entity.hasOwnProperty("homeAccountId") &&
            entity.hasOwnProperty("environment") &&
            entity.hasOwnProperty("realm") &&
            entity.hasOwnProperty("localAccountId") &&
            entity.hasOwnProperty("username") &&
            entity.hasOwnProperty("authorityType"));
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Interface class which implement cache storage functions used by MSAL to perform validity checks, and store tokens.
     * @internal
     */
    class CacheManager {
        constructor(clientId, cryptoImpl, logger, performanceClient, staticAuthorityOptions) {
            this.clientId = clientId;
            this.cryptoImpl = cryptoImpl;
            this.commonLogger = logger.clone(name$1, version$1);
            this.staticAuthorityOptions = staticAuthorityOptions;
            this.performanceClient = performanceClient;
        }
        /**
         * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
         * @param accountFilter - (Optional) filter to narrow down the accounts returned
         * @returns Array of AccountInfo objects in cache
         */
        getAllAccounts(accountFilter = {}, correlationId) {
            return this.buildTenantProfiles(this.getAccountsFilteredBy(accountFilter, correlationId), correlationId, accountFilter);
        }
        /**
         * Gets first tenanted AccountInfo object found based on provided filters
         */
        getAccountInfoFilteredBy(accountFilter, correlationId) {
            if (Object.keys(accountFilter).length === 0 ||
                Object.values(accountFilter).every((value) => value === null || value === undefined || value === "")) {
                this.commonLogger.warning("1skb02", correlationId);
                return null;
            }
            const allAccounts = this.getAllAccounts(accountFilter, correlationId);
            if (allAccounts.length > 1) {
                // If one or more accounts are found, prioritize accounts that have an ID token
                const sortedAccounts = allAccounts.sort((account) => {
                    return account.idTokenClaims ? -1 : 1;
                });
                return sortedAccounts[0];
            }
            else if (allAccounts.length === 1) {
                // If only one account is found, return it regardless of whether a matching ID token was found
                return allAccounts[0];
            }
            else {
                return null;
            }
        }
        /**
         * Returns a single matching
         * @param accountFilter
         * @returns
         */
        getBaseAccountInfo(accountFilter, correlationId) {
            const accountEntities = this.getAccountsFilteredBy(accountFilter, correlationId);
            if (accountEntities.length > 0) {
                return getAccountInfo(accountEntities[0]);
            }
            else {
                return null;
            }
        }
        /**
         * Matches filtered account entities with cached ID tokens that match the tenant profile-specific account filters
         * and builds the account info objects from the matching ID token's claims
         * @param cachedAccounts
         * @param accountFilter
         * @returns Array of AccountInfo objects that match account and tenant profile filters
         */
        buildTenantProfiles(cachedAccounts, correlationId, accountFilter) {
            return cachedAccounts.flatMap((accountEntity) => {
                return this.getTenantProfilesFromAccountEntity(accountEntity, correlationId, accountFilter?.tenantId, accountFilter);
            });
        }
        getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter) {
            let tenantedAccountInfo = null;
            let idTokenClaims;
            if (tenantProfileFilter) {
                if (!this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter)) {
                    return null;
                }
            }
            const idToken = this.getIdToken(accountInfo, correlationId, tokenKeys, tenantProfile.tenantId);
            if (idToken) {
                idTokenClaims = extractTokenClaims(idToken.secret, this.cryptoImpl.base64Decode);
                if (!this.idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter)) {
                    // ID token sourced claims don't match so this tenant profile is not a match
                    return null;
                }
            }
            // Expand tenant profile into account info based on matching tenant profile and if available matching ID token claims
            tenantedAccountInfo = updateAccountTenantProfileData(accountInfo, tenantProfile, idTokenClaims, idToken?.secret);
            return tenantedAccountInfo;
        }
        getTenantProfilesFromAccountEntity(accountEntity, correlationId, targetTenantId, tenantProfileFilter) {
            const accountInfo = getAccountInfo(accountEntity);
            let searchTenantProfiles = accountInfo.tenantProfiles || new Map();
            const tokenKeys = this.getTokenKeys();
            // If a tenant ID was provided, only return the tenant profile for that tenant ID if it exists
            if (targetTenantId) {
                const tenantProfile = searchTenantProfiles.get(targetTenantId);
                if (tenantProfile) {
                    // Reduce search field to just this tenant profile
                    searchTenantProfiles = new Map([
                        [targetTenantId, tenantProfile],
                    ]);
                }
                else {
                    // No tenant profile for search tenant ID, return empty array
                    return [];
                }
            }
            const matchingTenantProfiles = [];
            searchTenantProfiles.forEach((tenantProfile) => {
                const tenantedAccountInfo = this.getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter);
                if (tenantedAccountInfo) {
                    matchingTenantProfiles.push(tenantedAccountInfo);
                }
            });
            return matchingTenantProfiles;
        }
        tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter) {
            if (!!tenantProfileFilter.localAccountId &&
                !this.matchLocalAccountIdFromTenantProfile(tenantProfile, tenantProfileFilter.localAccountId)) {
                return false;
            }
            if (!!tenantProfileFilter.name &&
                !(tenantProfile.name === tenantProfileFilter.name)) {
                return false;
            }
            if (tenantProfileFilter.isHomeTenant !== undefined &&
                !(tenantProfile.isHomeTenant === tenantProfileFilter.isHomeTenant)) {
                return false;
            }
            return true;
        }
        idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter) {
            // Tenant Profile filtering
            if (tenantProfileFilter) {
                if (!!tenantProfileFilter.localAccountId &&
                    !this.matchLocalAccountIdFromTokenClaims(idTokenClaims, tenantProfileFilter.localAccountId)) {
                    return false;
                }
                if (!!tenantProfileFilter.loginHint &&
                    !this.matchLoginHintFromTokenClaims(idTokenClaims, tenantProfileFilter.loginHint)) {
                    return false;
                }
                if (!!tenantProfileFilter.username &&
                    !this.matchUsername(idTokenClaims.preferred_username, tenantProfileFilter.username)) {
                    return false;
                }
                if (!!tenantProfileFilter.name &&
                    !this.matchName(idTokenClaims, tenantProfileFilter.name)) {
                    return false;
                }
                if (!!tenantProfileFilter.sid &&
                    !this.matchSid(idTokenClaims, tenantProfileFilter.sid)) {
                    return false;
                }
            }
            return true;
        }
        /**
         * saves a cache record
         * @param cacheRecord {CacheRecord}
         * @param storeInCache {?StoreInCache}
         * @param correlationId {?string} correlation id
         */
        async saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache) {
            if (!cacheRecord) {
                throw createClientAuthError(invalidCacheRecord);
            }
            try {
                if (!!cacheRecord.account) {
                    await this.setAccount(cacheRecord.account, correlationId, kmsi, apiId);
                }
                if (!!cacheRecord.idToken && storeInCache?.idToken !== false) {
                    await this.setIdTokenCredential(cacheRecord.idToken, correlationId, kmsi);
                }
                if (!!cacheRecord.accessToken &&
                    storeInCache?.accessToken !== false) {
                    await this.saveAccessToken(cacheRecord.accessToken, correlationId, kmsi);
                }
                if (!!cacheRecord.refreshToken &&
                    storeInCache?.refreshToken !== false) {
                    await this.setRefreshTokenCredential(cacheRecord.refreshToken, correlationId, kmsi);
                }
                if (!!cacheRecord.appMetadata) {
                    this.setAppMetadata(cacheRecord.appMetadata, correlationId);
                }
            }
            catch (e) {
                this.commonLogger?.error("0j476p", correlationId);
                if (e instanceof AuthError) {
                    throw e;
                }
                else {
                    throw createCacheError(e);
                }
            }
        }
        /**
         * saves access token credential
         * @param credential
         */
        async saveAccessToken(credential, correlationId, kmsi) {
            const accessTokenFilter = {
                clientId: credential.clientId,
                credentialType: credential.credentialType,
                environment: credential.environment,
                homeAccountId: credential.homeAccountId,
                realm: credential.realm,
                tokenType: credential.tokenType,
            };
            const tokenKeys = this.getTokenKeys();
            const currentScopes = ScopeSet.fromString(credential.target);
            tokenKeys.accessToken.forEach((key) => {
                if (!this.accessTokenKeyMatchesFilter(key, accessTokenFilter, false)) {
                    return;
                }
                const tokenEntity = this.getAccessTokenCredential(key, correlationId);
                if (tokenEntity &&
                    this.credentialMatchesFilter(tokenEntity, accessTokenFilter, correlationId)) {
                    const tokenScopeSet = ScopeSet.fromString(tokenEntity.target);
                    if (tokenScopeSet.intersectingScopeSets(currentScopes)) {
                        this.removeAccessToken(key, correlationId);
                    }
                }
            });
            await this.setAccessTokenCredential(credential, correlationId, kmsi);
        }
        /**
         * Retrieve account entities matching all provided tenant-agnostic filters; if no filter is set, get all account entities in the cache
         * Not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared
         * @param accountFilter - An object containing Account properties to filter by
         */
        getAccountsFilteredBy(accountFilter, correlationId) {
            const allAccountKeys = this.getAccountKeys();
            const matchingAccounts = [];
            allAccountKeys.forEach((cacheKey) => {
                const entity = this.getAccount(cacheKey, correlationId);
                // Match base account fields
                if (!entity) {
                    return;
                }
                if (!!accountFilter.homeAccountId &&
                    !this.matchHomeAccountId(entity, accountFilter.homeAccountId)) {
                    return;
                }
                if (!!accountFilter.username &&
                    !this.matchUsername(entity.username, accountFilter.username)) {
                    return;
                }
                if (!!accountFilter.environment &&
                    !this.matchEnvironment(entity, accountFilter.environment, correlationId)) {
                    return;
                }
                if (!!accountFilter.realm &&
                    !this.matchRealm(entity, accountFilter.realm)) {
                    return;
                }
                if (!!accountFilter.nativeAccountId &&
                    !this.matchNativeAccountId(entity, accountFilter.nativeAccountId)) {
                    return;
                }
                if (!!accountFilter.authorityType &&
                    !this.matchAuthorityType(entity, accountFilter.authorityType)) {
                    return;
                }
                // If at least one tenant profile matches the tenant profile filter, add the account to the list of matching accounts
                const tenantProfileFilter = {
                    localAccountId: accountFilter?.localAccountId,
                    name: accountFilter?.name,
                };
                const matchingTenantProfiles = entity.tenantProfiles?.filter((tenantProfile) => {
                    return this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter);
                });
                if (matchingTenantProfiles && matchingTenantProfiles.length === 0) {
                    // No tenant profile for this account matches filter, don't add to list of matching accounts
                    return;
                }
                matchingAccounts.push(entity);
            });
            return matchingAccounts;
        }
        /**
         * Returns whether or not the given credential entity matches the filter
         * @param entity
         * @param filter
         * @param correlationId
         * @returns
         */
        credentialMatchesFilter(entity, filter, correlationId) {
            if (!!filter.clientId && !this.matchClientId(entity, filter.clientId)) {
                return false;
            }
            if (!!filter.userAssertionHash &&
                !this.matchUserAssertionHash(entity, filter.userAssertionHash)) {
                return false;
            }
            /*
             * homeAccountId can be undefined, and we want to filter out cached items that have a homeAccountId of ""
             * because we don't want a client_credential request to return a cached token that has a homeAccountId
             */
            if (typeof filter.homeAccountId === "string" &&
                !this.matchHomeAccountId(entity, filter.homeAccountId)) {
                return false;
            }
            if (!!filter.environment &&
                !this.matchEnvironment(entity, filter.environment, correlationId)) {
                return false;
            }
            if (!!filter.realm && !this.matchRealm(entity, filter.realm)) {
                return false;
            }
            if (!!filter.credentialType &&
                !this.matchCredentialType(entity, filter.credentialType)) {
                return false;
            }
            if (!!filter.familyId && !this.matchFamilyId(entity, filter.familyId)) {
                return false;
            }
            /*
             * idTokens do not have "target", target specific refreshTokens do exist for some types of authentication
             * Resource specific refresh tokens case will be added when the support is deemed necessary
             */
            if (!!filter.target && !this.matchTarget(entity, filter.target)) {
                return false;
            }
            // Access Token with Auth Scheme specific matching
            if (entity.credentialType ===
                CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME) {
                if (!!filter.tokenType &&
                    !this.matchTokenType(entity, filter.tokenType)) {
                    return false;
                }
                // KeyId (sshKid) in request must match cached SSH certificate keyId because SSH cert is bound to a specific key
                if (filter.tokenType === AuthenticationScheme$1.SSH) {
                    if (filter.keyId && !this.matchKeyId(entity, filter.keyId)) {
                        return false;
                    }
                }
            }
            return true;
        }
        /**
         * retrieve appMetadata matching all provided filters; if no filter is set, get all appMetadata
         * @param filter
         * @param correlationId
         */
        getAppMetadataFilteredBy(filter, correlationId) {
            const allCacheKeys = this.getKeys();
            const matchingAppMetadata = {};
            allCacheKeys.forEach((cacheKey) => {
                // don't parse any non-appMetadata type cache entities
                if (!this.isAppMetadata(cacheKey)) {
                    return;
                }
                // Attempt retrieval
                const entity = this.getAppMetadata(cacheKey, correlationId);
                if (!entity) {
                    return;
                }
                if (!!filter.environment &&
                    !this.matchEnvironment(entity, filter.environment, correlationId)) {
                    return;
                }
                if (!!filter.clientId &&
                    !this.matchClientId(entity, filter.clientId)) {
                    return;
                }
                matchingAppMetadata[cacheKey] = entity;
            });
            return matchingAppMetadata;
        }
        /**
         * retrieve authorityMetadata that contains a matching alias
         * @param host
         * @param correlationId
         */
        getAuthorityMetadataByAlias(host, correlationId) {
            const allCacheKeys = this.getAuthorityMetadataKeys();
            let matchedEntity = null;
            allCacheKeys.forEach((cacheKey) => {
                // don't parse any non-authorityMetadata type cache entities
                if (!this.isAuthorityMetadata(cacheKey) ||
                    cacheKey.indexOf(this.clientId) === -1) {
                    return;
                }
                // Attempt retrieval
                const entity = this.getAuthorityMetadata(cacheKey, correlationId);
                if (!entity) {
                    return;
                }
                if (entity.aliases.indexOf(host) === -1) {
                    return;
                }
                matchedEntity = entity;
            });
            return matchedEntity;
        }
        /**
         * Removes all accounts and related tokens from cache.
         */
        removeAllAccounts(correlationId) {
            const accounts = this.getAllAccounts({}, correlationId);
            accounts.forEach((account) => {
                this.removeAccount(account, correlationId);
            });
        }
        /**
         * Removes the account and related tokens for a given account key
         * @param account
         */
        removeAccount(account, correlationId) {
            this.removeAccountContext(account, correlationId);
            const accountKeys = this.getAccountKeys();
            const keyFilter = (key) => {
                return (key.includes(account.homeAccountId) &&
                    key.includes(account.environment));
            };
            accountKeys.filter(keyFilter).forEach((key) => {
                this.removeItem(key, correlationId);
                this.performanceClient.incrementFields({ accountsRemoved: 1 }, correlationId);
            });
        }
        /**
         * Removes credentials associated with the provided account
         * @param account
         */
        removeAccountContext(account, correlationId) {
            const allTokenKeys = this.getTokenKeys();
            const keyFilter = (key) => {
                return (key.includes(account.homeAccountId) &&
                    key.includes(account.environment));
            };
            allTokenKeys.idToken.filter(keyFilter).forEach((key) => {
                this.removeIdToken(key, correlationId);
            });
            allTokenKeys.accessToken.filter(keyFilter).forEach((key) => {
                this.removeAccessToken(key, correlationId);
            });
            allTokenKeys.refreshToken.filter(keyFilter).forEach((key) => {
                this.removeRefreshToken(key, correlationId);
            });
        }
        /**
         * returns a boolean if the given credential is removed
         * @param key
         * @param correlationId
         */
        removeAccessToken(key, correlationId) {
            const credential = this.getAccessTokenCredential(key, correlationId);
            if (!credential) {
                return;
            }
            this.removeItem(key, correlationId);
            this.performanceClient.incrementFields({ accessTokensRemoved: 1 }, correlationId);
            // Remove Token Binding Key from key store for PoP Tokens Credentials
            if (credential.credentialType.toLowerCase() ===
                CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()) {
                if (credential.tokenType === AuthenticationScheme$1.POP) {
                    const accessTokenWithAuthSchemeEntity = credential;
                    const kid = accessTokenWithAuthSchemeEntity.keyId;
                    if (kid) {
                        void this.cryptoImpl
                            .removeTokenBindingKey(kid, correlationId)
                            .catch(() => {
                            this.commonLogger.error("0cx291", correlationId);
                            this.performanceClient?.incrementFields({ removeTokenBindingKeyFailure: 1 }, correlationId);
                        });
                    }
                }
            }
        }
        /**
         * Removes all app metadata objects from cache.
         */
        removeAppMetadata(correlationId) {
            const allCacheKeys = this.getKeys();
            allCacheKeys.forEach((cacheKey) => {
                if (this.isAppMetadata(cacheKey)) {
                    this.removeItem(cacheKey, correlationId);
                }
            });
            return true;
        }
        /**
         * Retrieve IdTokenEntity from cache
         * @param account {AccountInfo}
         * @param tokenKeys {?TokenKeys}
         * @param targetRealm {?string}
         * @param performanceClient {?IPerformanceClient}
         * @param correlationId {?string}
         */
        getIdToken(account, correlationId, tokenKeys, targetRealm) {
            this.commonLogger.trace("1drz22", correlationId);
            const idTokenFilter = {
                homeAccountId: account.homeAccountId,
                environment: account.environment,
                credentialType: CredentialType.ID_TOKEN,
                clientId: this.clientId,
                realm: targetRealm,
            };
            const idTokenMap = this.getIdTokensByFilter(idTokenFilter, correlationId, tokenKeys);
            const numIdTokens = idTokenMap.size;
            if (numIdTokens < 1) {
                this.commonLogger.info("1atvtd", correlationId);
                return null;
            }
            else if (numIdTokens > 1) {
                let tokensToBeRemoved = idTokenMap;
                // Multiple tenant profiles and no tenant specified, pick home account
                if (!targetRealm) {
                    const homeIdTokenMap = new Map();
                    idTokenMap.forEach((idToken, key) => {
                        if (idToken.realm === account.tenantId) {
                            homeIdTokenMap.set(key, idToken);
                        }
                    });
                    const numHomeIdTokens = homeIdTokenMap.size;
                    if (numHomeIdTokens < 1) {
                        this.commonLogger.info("0ooalx", correlationId);
                        return idTokenMap.values().next().value;
                    }
                    else if (numHomeIdTokens === 1) {
                        this.commonLogger.info("1eq2vc", correlationId);
                        return homeIdTokenMap.values().next().value;
                    }
                    else {
                        // Multiple ID tokens for home tenant profile, remove all and return null
                        tokensToBeRemoved = homeIdTokenMap;
                    }
                }
                // Multiple tokens for a single tenant profile, remove all and return null
                this.commonLogger.info("1ws328", correlationId);
                tokensToBeRemoved.forEach((idToken, key) => {
                    this.removeIdToken(key, correlationId);
                });
                this.performanceClient.addFields({ multiMatchedID: idTokenMap.size }, correlationId);
                return null;
            }
            this.commonLogger.info("1sm769", correlationId);
            return idTokenMap.values().next().value;
        }
        /**
         * Gets all idTokens matching the given filter
         * @param filter
         * @returns
         */
        getIdTokensByFilter(filter, correlationId, tokenKeys) {
            const idTokenKeys = (tokenKeys && tokenKeys.idToken) || this.getTokenKeys().idToken;
            const idTokens = new Map();
            idTokenKeys.forEach((key) => {
                if (!this.idTokenKeyMatchesFilter(key, {
                    clientId: this.clientId,
                    ...filter,
                })) {
                    return;
                }
                const idToken = this.getIdTokenCredential(key, correlationId);
                if (idToken &&
                    this.credentialMatchesFilter(idToken, filter, correlationId)) {
                    idTokens.set(key, idToken);
                }
            });
            return idTokens;
        }
        /**
         * Validate the cache key against filter before retrieving and parsing cache value
         * @param key
         * @param filter
         * @returns
         */
        idTokenKeyMatchesFilter(inputKey, filter) {
            const key = inputKey.toLowerCase();
            if (filter.clientId &&
                key.indexOf(filter.clientId.toLowerCase()) === -1) {
                return false;
            }
            if (filter.homeAccountId &&
                key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
                return false;
            }
            return true;
        }
        /**
         * Removes idToken from the cache
         * @param key
         */
        removeIdToken(key, correlationId) {
            this.removeItem(key, correlationId);
        }
        /**
         * Removes refresh token from the cache
         * @param key
         */
        removeRefreshToken(key, correlationId) {
            this.removeItem(key, correlationId);
        }
        /**
         * Retrieve AccessTokenEntity from cache
         * @param account {AccountInfo}
         * @param request {BaseAuthRequest}
         * @param tokenKeys {?TokenKeys}
         * @param performanceClient {?IPerformanceClient}
         */
        getAccessToken(account, request, tokenKeys, targetRealm) {
            const correlationId = request.correlationId;
            this.commonLogger.trace("1t7hz1", correlationId);
            const scopes = ScopeSet.createSearchScopes(request.scopes);
            const authScheme = request.authenticationScheme ||
                AuthenticationScheme$1.BEARER;
            /*
             * Distinguish between Bearer and PoP/SSH token cache types
             * Cast to lowercase to handle "bearer" from ADFS
             */
            const credentialType = authScheme &&
                authScheme.toLowerCase() !==
                    AuthenticationScheme$1.BEARER.toLowerCase()
                ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME
                : CredentialType.ACCESS_TOKEN;
            const accessTokenFilter = {
                homeAccountId: account.homeAccountId,
                environment: account.environment,
                credentialType: credentialType,
                clientId: this.clientId,
                realm: targetRealm || account.tenantId,
                target: scopes,
                tokenType: authScheme,
                keyId: request.sshKid,
            };
            const accessTokenKeys = (tokenKeys && tokenKeys.accessToken) ||
                this.getTokenKeys().accessToken;
            const accessTokens = [];
            accessTokenKeys.forEach((key) => {
                // Validate key
                if (this.accessTokenKeyMatchesFilter(key, accessTokenFilter, true)) {
                    const accessToken = this.getAccessTokenCredential(key, correlationId);
                    // Validate value
                    if (accessToken &&
                        this.credentialMatchesFilter(accessToken, accessTokenFilter, correlationId)) {
                        accessTokens.push(accessToken);
                    }
                }
            });
            const numAccessTokens = accessTokens.length;
            if (numAccessTokens < 1) {
                this.commonLogger.info("1nckna", correlationId);
                return null;
            }
            else if (numAccessTokens > 1) {
                this.commonLogger.info("1wkfwp", correlationId);
                accessTokens.forEach((accessToken) => {
                    this.removeAccessToken(this.generateCredentialKey(accessToken), correlationId);
                });
                this.performanceClient.addFields({ multiMatchedAT: accessTokens.length }, correlationId);
                return null;
            }
            this.commonLogger.info("06yt98", correlationId);
            return accessTokens[0];
        }
        /**
         * Validate the cache key against filter before retrieving and parsing cache value
         * @param key
         * @param filter
         * @param keyMustContainAllScopes
         * @returns
         */
        accessTokenKeyMatchesFilter(inputKey, filter, keyMustContainAllScopes) {
            const key = inputKey.toLowerCase();
            if (filter.clientId &&
                key.indexOf(filter.clientId.toLowerCase()) === -1) {
                return false;
            }
            if (filter.homeAccountId &&
                key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
                return false;
            }
            if (filter.realm && key.indexOf(filter.realm.toLowerCase()) === -1) {
                return false;
            }
            if (filter.target) {
                const scopes = filter.target.asArray();
                for (let i = 0; i < scopes.length; i++) {
                    if (keyMustContainAllScopes &&
                        !key.includes(scopes[i].toLowerCase())) {
                        // When performing a cache lookup a missing scope would be a cache miss
                        return false;
                    }
                    else if (!keyMustContainAllScopes &&
                        key.includes(scopes[i].toLowerCase())) {
                        // When performing a cache write, any token with a subset of requested scopes should be replaced
                        return true;
                    }
                }
            }
            return true;
        }
        /**
         * Gets all access tokens matching the filter
         * @param filter
         * @returns
         */
        getAccessTokensByFilter(filter, correlationId) {
            const tokenKeys = this.getTokenKeys();
            const accessTokens = [];
            tokenKeys.accessToken.forEach((key) => {
                if (!this.accessTokenKeyMatchesFilter(key, filter, true)) {
                    return;
                }
                const accessToken = this.getAccessTokenCredential(key, correlationId);
                if (accessToken &&
                    this.credentialMatchesFilter(accessToken, filter, correlationId)) {
                    accessTokens.push(accessToken);
                }
            });
            return accessTokens;
        }
        /**
         * Helper to retrieve the appropriate refresh token from cache
         * @param account {AccountInfo}
         * @param familyRT {boolean}
         * @param tokenKeys {?TokenKeys}
         * @param performanceClient {?IPerformanceClient}
         * @param correlationId {?string}
         */
        getRefreshToken(account, familyRT, correlationId, tokenKeys) {
            this.commonLogger.trace("0x53vi", correlationId);
            const id = familyRT ? THE_FAMILY_ID : undefined;
            const refreshTokenFilter = {
                homeAccountId: account.homeAccountId,
                environment: account.environment,
                credentialType: CredentialType.REFRESH_TOKEN,
                clientId: this.clientId,
                familyId: id,
            };
            const refreshTokenKeys = (tokenKeys && tokenKeys.refreshToken) ||
                this.getTokenKeys().refreshToken;
            const refreshTokens = [];
            refreshTokenKeys.forEach((key) => {
                // Validate key
                if (this.refreshTokenKeyMatchesFilter(key, refreshTokenFilter)) {
                    const refreshToken = this.getRefreshTokenCredential(key, correlationId);
                    // Validate value
                    if (refreshToken &&
                        this.credentialMatchesFilter(refreshToken, refreshTokenFilter, correlationId)) {
                        refreshTokens.push(refreshToken);
                    }
                }
            });
            const numRefreshTokens = refreshTokens.length;
            if (numRefreshTokens < 1) {
                this.commonLogger.info("0dlw11", correlationId);
                return null;
            }
            // address the else case after remove functions address environment aliases
            if (numRefreshTokens > 1) {
                this.performanceClient.addFields({ multiMatchedRT: numRefreshTokens }, correlationId);
            }
            this.commonLogger.info("0wcnep", correlationId);
            return refreshTokens[0];
        }
        /**
         * Validate the cache key against filter before retrieving and parsing cache value
         * @param key
         * @param filter
         */
        refreshTokenKeyMatchesFilter(inputKey, filter) {
            const key = inputKey.toLowerCase();
            if (filter.familyId &&
                key.indexOf(filter.familyId.toLowerCase()) === -1) {
                return false;
            }
            // If familyId is used, clientId is not in the key
            if (!filter.familyId &&
                filter.clientId &&
                key.indexOf(filter.clientId.toLowerCase()) === -1) {
                return false;
            }
            if (filter.homeAccountId &&
                key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
                return false;
            }
            return true;
        }
        /**
         * Retrieve AppMetadataEntity from cache
         */
        readAppMetadataFromCache(environment, correlationId) {
            const appMetadataFilter = {
                environment,
                clientId: this.clientId,
            };
            const appMetadata = this.getAppMetadataFilteredBy(appMetadataFilter, correlationId);
            const appMetadataEntries = Object.keys(appMetadata).map((key) => appMetadata[key]);
            const numAppMetadata = appMetadataEntries.length;
            if (numAppMetadata < 1) {
                return null;
            }
            else if (numAppMetadata > 1) {
                throw createClientAuthError(multipleMatchingAppMetadata);
            }
            return appMetadataEntries[0];
        }
        /**
         * Return the family_id value associated  with FOCI
         * @param environment
         * @param clientId
         */
        isAppMetadataFOCI(environment, correlationId) {
            const appMetadata = this.readAppMetadataFromCache(environment, correlationId);
            return !!(appMetadata && appMetadata.familyId === THE_FAMILY_ID);
        }
        /**
         * helper to match account ids
         * @param value
         * @param homeAccountId
         */
        matchHomeAccountId(entity, homeAccountId) {
            return !!(typeof entity.homeAccountId === "string" &&
                homeAccountId === entity.homeAccountId);
        }
        /**
         * helper to match account ids
         * @param entity
         * @param localAccountId
         * @returns
         */
        matchLocalAccountIdFromTokenClaims(tokenClaims, localAccountId) {
            const idTokenLocalAccountId = tokenClaims.oid || tokenClaims.sub;
            return localAccountId === idTokenLocalAccountId;
        }
        matchLocalAccountIdFromTenantProfile(tenantProfile, localAccountId) {
            return tenantProfile.localAccountId === localAccountId;
        }
        /**
         * helper to match names
         * @param entity
         * @param name
         * @returns true if the downcased name properties are present and match in the filter and the entity
         */
        matchName(claims, name) {
            return !!(name.toLowerCase() === claims.name?.toLowerCase());
        }
        /**
         * helper to match usernames
         * @param entity
         * @param username
         * @returns
         */
        matchUsername(cachedUsername, filterUsername) {
            return !!(cachedUsername &&
                typeof cachedUsername === "string" &&
                filterUsername?.toLowerCase() === cachedUsername.toLowerCase());
        }
        /**
         * helper to match assertion
         * @param value
         * @param oboAssertion
         */
        matchUserAssertionHash(entity, userAssertionHash) {
            return !!(entity.userAssertionHash &&
                userAssertionHash === entity.userAssertionHash);
        }
        /**
         * helper to match environment
         * @param value
         * @param environment
         */
        matchEnvironment(entity, environment, correlationId) {
            // Check static authority options first for cases where authority metadata has not been resolved and cached yet
            if (this.staticAuthorityOptions) {
                const staticAliases = getAliasesFromStaticSources(this.staticAuthorityOptions, this.commonLogger, correlationId);
                if (staticAliases.includes(environment) &&
                    staticAliases.includes(entity.environment)) {
                    return true;
                }
            }
            // Query metadata cache if no static authority configuration has aliases that match enviroment
            const cloudMetadata = this.getAuthorityMetadataByAlias(environment, correlationId);
            if (cloudMetadata &&
                cloudMetadata.aliases.indexOf(entity.environment) > -1) {
                return true;
            }
            return false;
        }
        /**
         * helper to match credential type
         * @param entity
         * @param credentialType
         */
        matchCredentialType(entity, credentialType) {
            return (entity.credentialType &&
                credentialType.toLowerCase() === entity.credentialType.toLowerCase());
        }
        /**
         * helper to match client ids
         * @param entity
         * @param clientId
         */
        matchClientId(entity, clientId) {
            return !!(entity.clientId && clientId === entity.clientId);
        }
        /**
         * helper to match family ids
         * @param entity
         * @param familyId
         */
        matchFamilyId(entity, familyId) {
            return !!(entity.familyId && familyId === entity.familyId);
        }
        /**
         * helper to match realm
         * @param entity
         * @param realm
         */
        matchRealm(entity, realm) {
            return !!(entity.realm?.toLowerCase() === realm.toLowerCase());
        }
        /**
         * helper to match nativeAccountId
         * @param entity
         * @param nativeAccountId
         * @returns boolean indicating the match result
         */
        matchNativeAccountId(entity, nativeAccountId) {
            return !!(entity.nativeAccountId && nativeAccountId === entity.nativeAccountId);
        }
        /**
         * helper to match loginHint which can be either:
         * 1. login_hint ID token claim
         * 2. username in cached account object
         * 3. upn in ID token claims
         * @param entity
         * @param loginHint
         * @returns
         */
        matchLoginHintFromTokenClaims(tokenClaims, loginHint) {
            if (tokenClaims.login_hint === loginHint) {
                return true;
            }
            if (tokenClaims.preferred_username === loginHint) {
                return true;
            }
            if (tokenClaims.upn === loginHint) {
                return true;
            }
            return false;
        }
        /**
         * Helper to match sid
         * @param entity
         * @param sid
         * @returns true if the sid claim is present and matches the filter
         */
        matchSid(idTokenClaims, sid) {
            return idTokenClaims.sid === sid;
        }
        matchAuthorityType(entity, authorityType) {
            return !!(entity.authorityType &&
                authorityType.toLowerCase() === entity.authorityType.toLowerCase());
        }
        /**
         * Returns true if the target scopes are a subset of the current entity's scopes, false otherwise.
         * @param entity
         * @param target
         */
        matchTarget(entity, target) {
            const isNotAccessTokenCredential = entity.credentialType !== CredentialType.ACCESS_TOKEN &&
                entity.credentialType !==
                    CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;
            if (isNotAccessTokenCredential || !entity.target) {
                return false;
            }
            const entityScopeSet = ScopeSet.fromString(entity.target);
            return entityScopeSet.containsScopeSet(target);
        }
        /**
         * Returns true if the credential's tokenType or Authentication Scheme matches the one in the request, false otherwise
         * @param entity
         * @param tokenType
         */
        matchTokenType(entity, tokenType) {
            return !!(entity.tokenType && entity.tokenType === tokenType);
        }
        /**
         * Returns true if the credential's keyId matches the one in the request, false otherwise
         * @param entity
         * @param keyId
         */
        matchKeyId(entity, keyId) {
            return !!(entity.keyId && entity.keyId === keyId);
        }
        /**
         * returns if a given cache entity is of the type appmetadata
         * @param key
         */
        isAppMetadata(key) {
            return key.indexOf(APP_METADATA) !== -1;
        }
        /**
         * returns if a given cache entity is of the type authoritymetadata
         * @param key
         */
        isAuthorityMetadata(key) {
            return key.indexOf(AUTHORITY_METADATA_CACHE_KEY) !== -1;
        }
        /**
         * returns cache key used for cloud instance metadata
         */
        generateAuthorityMetadataCacheKey(authority) {
            return `${AUTHORITY_METADATA_CACHE_KEY}-${this.clientId}-${authority}`;
        }
        /**
         * Helper to convert serialized data to object
         * @param obj
         * @param json
         */
        static toObject(obj, json) {
            for (const propertyName in json) {
                obj[propertyName] = json[propertyName];
            }
            return obj;
        }
    }
    /** @internal */
    class DefaultStorageClass extends CacheManager {
        async setAccount() {
            throw createClientAuthError(methodNotImplemented);
        }
        getAccount() {
            throw createClientAuthError(methodNotImplemented);
        }
        async setIdTokenCredential() {
            throw createClientAuthError(methodNotImplemented);
        }
        getIdTokenCredential() {
            throw createClientAuthError(methodNotImplemented);
        }
        async setAccessTokenCredential() {
            throw createClientAuthError(methodNotImplemented);
        }
        getAccessTokenCredential() {
            throw createClientAuthError(methodNotImplemented);
        }
        async setRefreshTokenCredential() {
            throw createClientAuthError(methodNotImplemented);
        }
        getRefreshTokenCredential() {
            throw createClientAuthError(methodNotImplemented);
        }
        setAppMetadata() {
            throw createClientAuthError(methodNotImplemented);
        }
        getAppMetadata() {
            throw createClientAuthError(methodNotImplemented);
        }
        setServerTelemetry() {
            throw createClientAuthError(methodNotImplemented);
        }
        getServerTelemetry() {
            throw createClientAuthError(methodNotImplemented);
        }
        setAuthorityMetadata() {
            throw createClientAuthError(methodNotImplemented);
        }
        getAuthorityMetadata() {
            throw createClientAuthError(methodNotImplemented);
        }
        getAuthorityMetadataKeys() {
            throw createClientAuthError(methodNotImplemented);
        }
        setThrottlingCache() {
            throw createClientAuthError(methodNotImplemented);
        }
        getThrottlingCache() {
            throw createClientAuthError(methodNotImplemented);
        }
        removeItem() {
            throw createClientAuthError(methodNotImplemented);
        }
        getKeys() {
            throw createClientAuthError(methodNotImplemented);
        }
        getAccountKeys() {
            throw createClientAuthError(methodNotImplemented);
        }
        getTokenKeys() {
            throw createClientAuthError(methodNotImplemented);
        }
        generateCredentialKey() {
            throw createClientAuthError(methodNotImplemented);
        }
        generateAccountKey() {
            throw createClientAuthError(methodNotImplemented);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * State of the performance event.
     *
     * @export
     * @enum {number}
     */
    const PerformanceEventStatus = {
        InProgress: 1,
        Completed: 2,
    };
    /**
     * Prefix used to mark telemetry field names as dynamic.
     * Fields with this prefix in addFields/incrementFields calls will be routed
     * to the PerformanceEvent.ext sub-object.
     */
    const EXT_FIELD_PREFIX = "ext.";
    const IntFields = new Set([
        "accessTokenSize",
        "durationMs",
        "idTokenSize",
        "matsSilentStatus",
        "matsHttpStatus",
        "refreshTokenSize",
        "startTimeMs",
        "status",
        "multiMatchedAT",
        "multiMatchedID",
        "multiMatchedRT",
        "unencryptedCacheCount",
        "encryptedCacheExpiredCount",
        "oldAccountCount",
        "oldAccessCount",
        "oldIdCount",
        "oldRefreshCount",
        "currAccountCount",
        "currAccessCount",
        "currIdCount",
        "currRefreshCount",
        "expiredCacheRemovedCount",
        "upgradedCacheCount",
        "cacheMatchedAccounts",
        "networkRtt",
        "redirectBridgeTimeoutMs",
        "redirectBridgeMessageVersion",
    ]);
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class StubPerformanceClient {
        generateId() {
            return "callback-id";
        }
        startMeasurement(measureName, correlationId) {
            return {
                end: () => null,
                discard: () => { },
                add: () => { },
                increment: () => { },
                event: {
                    eventId: this.generateId(),
                    status: PerformanceEventStatus.InProgress,
                    authority: "",
                    libraryName: "",
                    libraryVersion: "",
                    clientId: "",
                    name: measureName,
                    startTimeMs: Date.now(),
                    correlationId: correlationId || "",
                },
            };
        }
        endMeasurement() {
            return null;
        }
        discardMeasurements() {
            return;
        }
        removePerformanceCallback() {
            return true;
        }
        addPerformanceCallback() {
            return "";
        }
        emitEvents() {
            return;
        }
        addFields() {
            return;
        }
        incrementFields() {
            return;
        }
        cacheEventByCorrelationId() {
            return;
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const DEFAULT_SYSTEM_OPTIONS = {
        tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,
        preventCorsPreflight: false,
    };
    const DEFAULT_LOGGER_IMPLEMENTATION = {
        loggerCallback: () => {
            // allow users to not set loggerCallback
        },
        piiLoggingEnabled: false,
        logLevel: exports.LogLevel.Info,
        correlationId: "",
    };
    const DEFAULT_NETWORK_IMPLEMENTATION = {
        async sendGetRequestAsync() {
            throw createClientAuthError(methodNotImplemented);
        },
        async sendPostRequestAsync() {
            throw createClientAuthError(methodNotImplemented);
        },
    };
    const DEFAULT_LIBRARY_INFO = {
        sku: SKU,
        version: version$1,
        cpu: "",
        os: "",
    };
    const DEFAULT_CLIENT_CREDENTIALS = {
        clientSecret: "",
        clientAssertion: undefined,
    };
    const DEFAULT_AZURE_CLOUD_OPTIONS = {
        azureCloudInstance: AzureCloudInstance.None,
        tenant: `${DEFAULT_COMMON_TENANT}`,
    };
    const DEFAULT_TELEMETRY_OPTIONS = {
        application: {
            appName: "",
            appVersion: "",
        },
    };
    /**
     * Function that sets the default options when not explicitly configured from app developer
     *
     * @param Configuration
     *
     * @returns Configuration
     */
    function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions: userSystemOptions, loggerOptions: userLoggerOption, storageInterface: storageImplementation, networkInterface: networkImplementation, cryptoInterface: cryptoImplementation, clientCredentials: clientCredentials, libraryInfo: libraryInfo, telemetry: telemetry, serverTelemetryManager: serverTelemetryManager, persistencePlugin: persistencePlugin, serializableCache: serializableCache, }) {
        const loggerOptions = {
            ...DEFAULT_LOGGER_IMPLEMENTATION,
            ...userLoggerOption,
        };
        return {
            authOptions: buildAuthOptions(userAuthOptions),
            systemOptions: { ...DEFAULT_SYSTEM_OPTIONS, ...userSystemOptions },
            loggerOptions: loggerOptions,
            storageInterface: storageImplementation ||
                new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION, new Logger(loggerOptions), new StubPerformanceClient()),
            networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,
            cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION,
            clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS,
            libraryInfo: { ...DEFAULT_LIBRARY_INFO, ...libraryInfo },
            telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry },
            serverTelemetryManager: serverTelemetryManager || null,
            persistencePlugin: persistencePlugin || null,
            serializableCache: serializableCache || null,
        };
    }
    /**
     * Construct authoptions from the client and platform passed values
     * @param authOptions
     */
    function buildAuthOptions(authOptions) {
        return {
            clientCapabilities: [],
            azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS,
            instanceAware: false,
            isMcp: false,
            ...authOptions,
        };
    }
    /**
     * Returns true if config has protocolMode set to ProtocolMode.OIDC, false otherwise
     * @param ClientConfiguration
     */
    function isOidcProtocolMode(config) {
        return (config.authOptions.authority.options.protocolMode === ProtocolMode.OIDC);
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This class instance helps track the memory changes facilitating
     * decisions to read from and write to the persistent cache
     */ class TokenCacheContext {
        constructor(tokenCache, hasChanged) {
            this.cache = tokenCache;
            this.hasChanged = hasChanged;
        }
        /**
         * boolean which indicates the changes in cache
         */
        get cacheHasChanged() {
            return this.hasChanged;
        }
        /**
         * function to retrieve the token cache
         */
        get tokenCache() {
            return this.cache;
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Utility functions for managing date and time operations.
     */
    /**
     * return the current time in Unix time (seconds).
     */
    function nowSeconds() {
        // Date.getTime() returns in milliseconds.
        return Math.round(new Date().getTime() / 1000.0);
    }
    /**
     * Converts JS Date object to seconds
     * @param date Date
     */
    function toSecondsFromDate(date) {
        // Convert date to seconds
        return date.getTime() / 1000;
    }
    /**
     * Convert seconds to JS Date object. Seconds can be in a number or string format or undefined (will still return a date).
     * @param seconds
     */
    function toDateFromSeconds(seconds) {
        if (seconds) {
            return new Date(Number(seconds) * 1000);
        }
        return new Date();
    }
    /**
     * check if a token is expired based on given UTC time in seconds.
     * @param expiresOn
     */
    function isTokenExpired(expiresOn, offset) {
        // check for access token expiry
        const expirationSec = Number(expiresOn) || 0;
        const offsetCurrentTimeSec = nowSeconds() + offset;
        // If current time + offset is greater than token expiration time, then token is expired.
        return offsetCurrentTimeSec > expirationSec;
    }
    /**
     * Checks if a cache entry is expired based on the last updated time and cache retention days.
     * @param lastUpdatedAt
     * @param cacheRetentionDays
     * @returns
     */
    function isCacheExpired(lastUpdatedAt, cacheRetentionDays) {
        const cacheExpirationTimestamp = Number(lastUpdatedAt) + cacheRetentionDays * 24 * 60 * 60 * 1000;
        return Date.now() > cacheExpirationTimestamp;
    }
    /**
     * If the current time is earlier than the time that a token was cached at, we must discard the token
     * i.e. The system clock was turned back after acquiring the cached token
     * @param cachedAt
     * @param offset
     */
    function wasClockTurnedBack(cachedAt) {
        const cachedAtSec = Number(cachedAt);
        return cachedAtSec > nowSeconds();
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Create IdTokenEntity
     * @param homeAccountId
     * @param authenticationResult
     * @param clientId
     * @param authority
     */
    function createIdTokenEntity(homeAccountId, environment, idToken, clientId, tenantId) {
        const idTokenEntity = {
            credentialType: CredentialType.ID_TOKEN,
            homeAccountId: homeAccountId,
            environment: environment,
            clientId: clientId,
            secret: idToken,
            realm: tenantId,
            lastUpdatedAt: Date.now().toString(), // Set the last updated time to now
        };
        return idTokenEntity;
    }
    /**
     * Create AccessTokenEntity
     * @param homeAccountId
     * @param environment
     * @param accessToken
     * @param clientId
     * @param tenantId
     * @param scopes
     * @param expiresOn
     * @param extExpiresOn
     */
    function createAccessTokenEntity(homeAccountId, environment, accessToken, clientId, tenantId, scopes, expiresOn, extExpiresOn, base64Decode, refreshOn, tokenType, userAssertionHash, keyId) {
        const atEntity = {
            homeAccountId: homeAccountId,
            credentialType: CredentialType.ACCESS_TOKEN,
            secret: accessToken,
            cachedAt: nowSeconds().toString(),
            expiresOn: expiresOn.toString(),
            extendedExpiresOn: extExpiresOn.toString(),
            environment: environment,
            clientId: clientId,
            realm: tenantId,
            target: scopes,
            tokenType: tokenType || AuthenticationScheme$1.BEARER,
            lastUpdatedAt: Date.now().toString(), // Set the last updated time to now
        };
        if (userAssertionHash) {
            atEntity.userAssertionHash = userAssertionHash;
        }
        if (refreshOn) {
            atEntity.refreshOn = refreshOn.toString();
        }
        /*
         * Create Access Token With Auth Scheme instead of regular access token
         * Cast to lower to handle "bearer" from ADFS
         */
        if (atEntity.tokenType?.toLowerCase() !==
            AuthenticationScheme$1.BEARER.toLowerCase()) {
            atEntity.credentialType =
                CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;
            switch (atEntity.tokenType) {
                case AuthenticationScheme$1.POP:
                    // Make sure keyId is present and add it to credential
                    const tokenClaims = extractTokenClaims(accessToken, base64Decode);
                    if (!tokenClaims?.cnf?.kid) {
                        throw createClientAuthError(tokenClaimsCnfRequiredForSignedJwt);
                    }
                    atEntity.keyId = tokenClaims.cnf.kid;
                    break;
                case AuthenticationScheme$1.SSH:
                    atEntity.keyId = keyId;
            }
        }
        return atEntity;
    }
    /**
     * Create RefreshTokenEntity
     * @param homeAccountId
     * @param authenticationResult
     * @param clientId
     * @param authority
     */
    function createRefreshTokenEntity(homeAccountId, environment, refreshToken, clientId, familyId, userAssertionHash, expiresOn) {
        const rtEntity = {
            credentialType: CredentialType.REFRESH_TOKEN,
            homeAccountId: homeAccountId,
            environment: environment,
            clientId: clientId,
            secret: refreshToken,
            lastUpdatedAt: Date.now().toString(),
        };
        if (userAssertionHash) {
            rtEntity.userAssertionHash = userAssertionHash;
        }
        if (familyId) {
            rtEntity.familyId = familyId;
        }
        if (expiresOn) {
            rtEntity.expiresOn = expiresOn.toString();
        }
        return rtEntity;
    }
    function isCredentialEntity(entity) {
        return (entity.hasOwnProperty("homeAccountId") &&
            entity.hasOwnProperty("environment") &&
            entity.hasOwnProperty("credentialType") &&
            entity.hasOwnProperty("clientId") &&
            entity.hasOwnProperty("secret"));
    }
    /**
     * Validates an entity: checks for all expected params
     * @param entity
     */
    function isAccessTokenEntity(entity) {
        if (!entity) {
            return false;
        }
        return (isCredentialEntity(entity) &&
            entity.hasOwnProperty("realm") &&
            entity.hasOwnProperty("target") &&
            (entity["credentialType"] === CredentialType.ACCESS_TOKEN ||
                entity["credentialType"] ===
                    CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME));
    }
    /**
     * Validates an entity: checks for all expected params
     * @param entity
     */
    function isIdTokenEntity(entity) {
        if (!entity) {
            return false;
        }
        return (isCredentialEntity(entity) &&
            entity.hasOwnProperty("realm") &&
            entity["credentialType"] === CredentialType.ID_TOKEN);
    }
    /**
     * Validates an entity: checks for all expected params
     * @param entity
     */
    function isRefreshTokenEntity(entity) {
        if (!entity) {
            return false;
        }
        return (isCredentialEntity(entity) &&
            entity["credentialType"] === CredentialType.REFRESH_TOKEN);
    }
    /**
     * validates if a given cache entry is "Telemetry", parses <key,value>
     * @param key
     * @param entity
     */
    function isServerTelemetryEntity(key, entity) {
        const validateKey = key.indexOf(SERVER_TELEM_CACHE_KEY) === 0;
        let validateEntity = true;
        if (entity) {
            validateEntity =
                entity.hasOwnProperty("failedRequests") &&
                    entity.hasOwnProperty("errors") &&
                    entity.hasOwnProperty("cacheHits");
        }
        return validateKey && validateEntity;
    }
    /**
     * validates if a given cache entry is "Throttling", parses <key,value>
     * @param key
     * @param entity
     */
    function isThrottlingEntity(key, entity) {
        let validateKey = false;
        if (key) {
            validateKey = key.indexOf(THROTTLING_PREFIX) === 0;
        }
        let validateEntity = true;
        if (entity) {
            validateEntity = entity.hasOwnProperty("throttleTime");
        }
        return validateKey && validateEntity;
    }
    /**
     * Generate AppMetadata Cache Key as per the schema: appmetadata-<environment>-<client_id>
     */
    function generateAppMetadataKey({ environment, clientId, }) {
        const appMetaDataKeyArray = [
            APP_METADATA,
            environment,
            clientId,
        ];
        return appMetaDataKeyArray
            .join(CACHE_KEY_SEPARATOR$1)
            .toLowerCase();
    }
    /*
     * Validates an entity: checks for all expected params
     * @param entity
     */
    function isAppMetadataEntity(key, entity) {
        if (!entity) {
            return false;
        }
        return (key.indexOf(APP_METADATA) === 0 &&
            entity.hasOwnProperty("clientId") &&
            entity.hasOwnProperty("environment"));
    }
    /**
     * Validates an entity: checks for all expected params
     * @param entity
     */
    function isAuthorityMetadataEntity(key, entity) {
        if (!entity) {
            return false;
        }
        return (key.indexOf(AUTHORITY_METADATA_CACHE_KEY) === 0 &&
            entity.hasOwnProperty("aliases") &&
            entity.hasOwnProperty("preferred_cache") &&
            entity.hasOwnProperty("preferred_network") &&
            entity.hasOwnProperty("canonical_authority") &&
            entity.hasOwnProperty("authorization_endpoint") &&
            entity.hasOwnProperty("token_endpoint") &&
            entity.hasOwnProperty("issuer") &&
            entity.hasOwnProperty("aliasesFromNetwork") &&
            entity.hasOwnProperty("endpointsFromNetwork") &&
            entity.hasOwnProperty("expiresAt") &&
            entity.hasOwnProperty("jwks_uri"));
    }
    /**
     * Reset the exiresAt value
     */
    function generateAuthorityMetadataExpiresAt() {
        return (nowSeconds() +
            AUTHORITY_METADATA_REFRESH_TIME_SECONDS);
    }
    function updateAuthorityEndpointMetadata(authorityMetadata, updatedValues, fromNetwork) {
        authorityMetadata.authorization_endpoint =
            updatedValues.authorization_endpoint;
        authorityMetadata.token_endpoint = updatedValues.token_endpoint;
        authorityMetadata.end_session_endpoint = updatedValues.end_session_endpoint;
        authorityMetadata.issuer = updatedValues.issuer;
        authorityMetadata.endpointsFromNetwork = fromNetwork;
        authorityMetadata.jwks_uri = updatedValues.jwks_uri;
    }
    function updateCloudDiscoveryMetadata(authorityMetadata, updatedValues, fromNetwork) {
        authorityMetadata.aliases = updatedValues.aliases;
        authorityMetadata.preferred_cache = updatedValues.preferred_cache;
        authorityMetadata.preferred_network = updatedValues.preferred_network;
        authorityMetadata.aliasesFromNetwork = fromNetwork;
    }
    /**
     * Returns whether or not the data needs to be refreshed
     */
    function isAuthorityMetadataExpired(metadata) {
        return metadata.expiresAt <= nowSeconds();
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Time spent sending/waiting for the response of a request to the token endpoint
     */
    const NetworkClientSendPostRequestAsync = "networkClientSendPostRequestAsync";
    const RefreshTokenClientExecutePostToTokenEndpoint = "refreshTokenClientExecutePostToTokenEndpoint";
    const AuthorizationCodeClientExecutePostToTokenEndpoint = "authorizationCodeClientExecutePostToTokenEndpoint";
    /**
     * Time spent on the network for refresh token acquisition
     */
    const RefreshTokenClientExecuteTokenRequest = "refreshTokenClientExecuteTokenRequest";
    /**
     * Time taken for acquiring refresh token , records RT size
     */
    const RefreshTokenClientAcquireToken = "refreshTokenClientAcquireToken";
    /**
     * Time taken for acquiring cached refresh token
     */
    const RefreshTokenClientAcquireTokenWithCachedRefreshToken = "refreshTokenClientAcquireTokenWithCachedRefreshToken";
    /**
     * Helper function to create token request body in RefreshTokenClient (msal-common).
     */
    const RefreshTokenClientCreateTokenRequestBody = "refreshTokenClientCreateTokenRequestBody";
    const SilentFlowClientGenerateResultFromCacheRecord = "silentFlowClientGenerateResultFromCacheRecord";
    /**
     * getAuthCodeUrl API (msal-browser and msal-node).
     */
    const GetAuthCodeUrl = "getAuthCodeUrl";
    /**
     * Functions from InteractionHandler (msal-browser)
     */
    const HandleCodeResponseFromServer = "handleCodeResponseFromServer";
    /**
     * APIs in Authorization Code Client (msal-common)
     */
    const AuthClientExecuteTokenRequest = "authClientExecuteTokenRequest";
    const AuthClientCreateTokenRequestBody = "authClientCreateTokenRequestBody";
    const UpdateTokenEndpointAuthority = "updateTokenEndpointAuthority";
    /**
     * Generate functions in PopTokenGenerator (msal-common)
     */
    const PopTokenGenerateCnf = "popTokenGenerateCnf";
    /**
     * handleServerTokenResponse API in ResponseHandler (msal-common)
     */
    const HandleServerTokenResponse = "handleServerTokenResponse";
    /**
     * Authority functions
     */
    const AuthorityResolveEndpointsAsync = "authorityResolveEndpointsAsync";
    const AuthorityGetCloudDiscoveryMetadataFromNetwork = "authorityGetCloudDiscoveryMetadataFromNetwork";
    const AuthorityUpdateCloudDiscoveryMetadata = "authorityUpdateCloudDiscoveryMetadata";
    const AuthorityGetEndpointMetadataFromNetwork = "authorityGetEndpointMetadataFromNetwork";
    const AuthorityUpdateEndpointMetadata = "authorityUpdateEndpointMetadata";
    const AuthorityUpdateMetadataWithRegionalInformation = "authorityUpdateMetadataWithRegionalInformation";
    /**
     * Region Discovery functions
     */
    const RegionDiscoveryDetectRegion = "regionDiscoveryDetectRegion";
    const RegionDiscoveryGetRegionFromIMDS = "regionDiscoveryGetRegionFromIMDS";
    const RegionDiscoveryGetCurrentVersion = "regionDiscoveryGetCurrentVersion";
    /**
     * Cache operations
     */
    const CacheManagerGetRefreshToken = "cacheManagerGetRefreshToken";
    const SetUserData = "setUserData";
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Wraps a function with a performance measurement.
     * Usage: invoke(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction)
     * @param callback
     * @param eventName
     * @param logger
     * @param telemetryClient
     * @param correlationId
     * @returns
     * @internal
     */
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const invoke = (callback, eventName, logger, telemetryClient, correlationId) => {
        return (...args) => {
            logger.trace("1plfzx", correlationId);
            const inProgressEvent = telemetryClient.startMeasurement(eventName, correlationId);
            if (correlationId) {
                // Track number of times this API is called in a single request
                telemetryClient.incrementFields({ [`ext.${eventName}CallCount`]: 1 }, correlationId);
            }
            try {
                const result = callback(...args);
                inProgressEvent.end({
                    success: true,
                });
                logger.trace("1g8n6a", correlationId);
                return result;
            }
            catch (e) {
                logger.trace("0cfd8i", correlationId);
                try {
                    logger.trace(JSON.stringify(e), correlationId);
                }
                catch (e) {
                    logger.trace("00dty7", correlationId);
                }
                inProgressEvent.end({
                    success: false,
                }, e);
                throw e;
            }
        };
    };
    /**
     * Wraps an async function with a performance measurement.
     * Usage: invokeAsync(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction)
     * @param callback
     * @param eventName
     * @param logger
     * @param telemetryClient
     * @param correlationId
     * @returns
     * @internal
     *
     */
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const invokeAsync = (callback, eventName, logger, telemetryClient, correlationId) => {
        return (...args) => {
            logger.trace("1plfzx", correlationId);
            const inProgressEvent = telemetryClient.startMeasurement(eventName, correlationId);
            if (correlationId) {
                // Track number of times this API is called in a single request
                telemetryClient.incrementFields({ [`ext.${eventName}CallCount`]: 1 }, correlationId);
            }
            return callback(...args)
                .then((response) => {
                logger.trace("1g8n6a", correlationId);
                inProgressEvent.end({
                    success: true,
                });
                return response;
            })
                .catch((e) => {
                logger.trace("0cfd8i", correlationId);
                try {
                    logger.trace(JSON.stringify(e), correlationId);
                }
                catch (e) {
                    logger.trace("00dty7", correlationId);
                }
                inProgressEvent.end({
                    success: false,
                }, e);
                throw e;
            });
        };
    };
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const KeyLocation = {
        SW: "sw"};
    /** @internal */
    class PopTokenGenerator {
        constructor(cryptoUtils, performanceClient) {
            this.cryptoUtils = cryptoUtils;
            this.performanceClient = performanceClient;
        }
        /**
         * Generates the req_cnf validated at the RP in the POP protocol for SHR parameters
         * and returns an object containing the keyid, the full req_cnf string and the req_cnf string hash
         * @param request
         * @returns
         */
        async generateCnf(request, logger) {
            const reqCnf = await invokeAsync(this.generateKid.bind(this), PopTokenGenerateCnf, logger, this.performanceClient, request.correlationId)(request);
            const reqCnfString = this.cryptoUtils.base64UrlEncode(JSON.stringify(reqCnf));
            return {
                kid: reqCnf.kid,
                reqCnfString,
            };
        }
        /**
         * Generates key_id for a SHR token request
         * @param request
         * @returns
         */
        async generateKid(request) {
            const kidThumbprint = await this.cryptoUtils.getPublicKeyThumbprint(request);
            return {
                kid: kidThumbprint,
                xms_ksl: KeyLocation.SW,
            };
        }
        /**
         * Signs the POP access_token with the local generated key-pair
         * @param accessToken
         * @param request
         * @returns
         */
        async signPopToken(accessToken, keyId, request) {
            return this.signPayload(accessToken, keyId, request);
        }
        /**
         * Utility function to generate the signed JWT for an access_token
         * @param payload
         * @param kid
         * @param request
         * @param claims
         * @returns
         */
        async signPayload(payload, keyId, request, claims) {
            // Deconstruct request to extract SHR parameters
            const { resourceRequestMethod, resourceRequestUri, shrClaims, shrNonce, shrOptions, } = request;
            const resourceUrlString = resourceRequestUri
                ? new UrlString(resourceRequestUri)
                : undefined;
            const resourceUrlComponents = resourceUrlString?.getUrlComponents();
            return this.cryptoUtils.signJwt({
                at: payload,
                ts: nowSeconds(),
                m: resourceRequestMethod?.toUpperCase(),
                u: resourceUrlComponents?.HostNameAndPort,
                nonce: shrNonce || this.cryptoUtils.createNewGuid(),
                p: resourceUrlComponents?.AbsolutePath,
                q: resourceUrlComponents?.QueryString
                    ? [[], resourceUrlComponents.QueryString]
                    : undefined,
                client_claims: shrClaims || undefined,
                ...claims,
            }, keyId, shrOptions, request.correlationId);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * MSAL-defined interaction required error code indicating no tokens are found in cache.
     * @public
     */
    const noTokensFound = "no_tokens_found";
    /**
     * MSAL-defined error code indicating a native account is unavailable on the platform.
     * @public
     */
    const nativeAccountUnavailable = "native_account_unavailable";
    /**
     * MSAL-defined error code indicating the refresh token has expired and user interaction is needed.
     * @public
     */
    const refreshTokenExpired = "refresh_token_expired";
    /**
     * MSAL-defined error code indicating UI/UX is not allowed (e.g., blocked by policy), requiring alternate interaction.
     * @public
     */
    const uxNotAllowed = "ux_not_allowed";
    /**
     * Server-originated error code indicating interaction is required to complete the request.
     * @public
     */
    const interactionRequired = "interaction_required";
    /**
     * Server-originated error code indicating user consent is required.
     * @public
     */
    const consentRequired = "consent_required";
    /**
     * Server-originated error code indicating user login is required.
     * @public
     */
    const loginRequired = "login_required";
    /**
     * Server-originated error code indicating the token is invalid or corrupted.
     * @public
     */
    const badToken = "bad_token";
    /**
     * Server-originated error code indicating the user is in an interrupted state and interaction is required.
     * @public
     */
    const interruptedUser = "interrupted_user";
 
    var InteractionRequiredAuthErrorCodes = /*#__PURE__*/Object.freeze({
        __proto__: null,
        badToken: badToken,
        consentRequired: consentRequired,
        interactionRequired: interactionRequired,
        interruptedUser: interruptedUser,
        loginRequired: loginRequired,
        nativeAccountUnavailable: nativeAccountUnavailable,
        noTokensFound: noTokensFound,
        refreshTokenExpired: refreshTokenExpired,
        uxNotAllowed: uxNotAllowed
    });
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * InteractionRequiredServerErrorMessage contains string constants used by error codes and messages returned by the server indicating interaction is required
     */
    const InteractionRequiredServerErrorMessage = [
        interactionRequired,
        consentRequired,
        loginRequired,
        badToken,
        uxNotAllowed,
        interruptedUser,
    ];
    const InteractionRequiredAuthSubErrorMessage = [
        "message_only",
        "additional_action",
        "basic_action",
        "user_password_expired",
        "consent_required",
        "bad_token",
        "ux_not_allowed",
        "interrupted_user",
    ];
    /**
     * Error thrown when user interaction is required.
     */
    class InteractionRequiredAuthError extends AuthError {
        constructor(errorCode, errorMessage, subError, timestamp, traceId, correlationId, claims, errorNo) {
            super(errorCode, errorMessage, subError);
            Object.setPrototypeOf(this, InteractionRequiredAuthError.prototype);
            this.timestamp = timestamp || "";
            this.traceId = traceId || "";
            this.correlationId = correlationId || "";
            this.claims = claims || "";
            this.name = "InteractionRequiredAuthError";
            this.errorNo = errorNo;
        }
    }
    /**
     * Helper function used to determine if an error thrown by the server requires interaction to resolve
     * @param errorCode
     * @param errorString
     * @param subError
     */
    function isInteractionRequiredError(errorCode, errorString, subError) {
        const isInteractionRequiredErrorCode = !!errorCode &&
            InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1;
        const isInteractionRequiredSubError = !!subError &&
            InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;
        const isInteractionRequiredErrorDesc = !!errorString &&
            InteractionRequiredServerErrorMessage.some((irErrorCode) => {
                return errorString.indexOf(irErrorCode) > -1;
            });
        return (isInteractionRequiredErrorCode ||
            isInteractionRequiredErrorDesc ||
            isInteractionRequiredSubError);
    }
    /**
     * Creates an InteractionRequiredAuthError
     */
    function createInteractionRequiredAuthError(errorCode, errorMessage) {
        return new InteractionRequiredAuthError(errorCode, errorMessage);
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Error thrown when there is an error with the server code, for example, unavailability.
     */
    class ServerError extends AuthError {
        constructor(errorCode, errorMessage, subError, errorNo, status) {
            super(errorCode, errorMessage, subError);
            this.name = "ServerError";
            this.errorNo = errorNo;
            this.status = status;
            Object.setPrototypeOf(this, ServerError.prototype);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Appends user state with random guid, or returns random guid.
     * @param cryptoObj
     * @param userState
     * @param meta
     */
    function setRequestState(cryptoObj, userState, meta) {
        const libraryState = generateLibraryState(cryptoObj, meta);
        return userState
            ? `${libraryState}${RESOURCE_DELIM}${userState}`
            : libraryState;
    }
    /**
     * Generates the state value used by the common library.
     * @param cryptoObj
     * @param meta
     */
    function generateLibraryState(cryptoObj, meta) {
        if (!cryptoObj) {
            throw createClientAuthError(noCryptoObject);
        }
        // Create a state object containing a unique id and the timestamp of the request creation
        const stateObj = {
            id: cryptoObj.createNewGuid(),
        };
        if (meta) {
            stateObj.meta = meta;
        }
        const stateString = JSON.stringify(stateObj);
        return cryptoObj.base64Encode(stateString);
    }
    /**
     * Parses the state into the RequestStateObject, which contains the LibraryState info and the state passed by the user.
     * @param base64Decode
     * @param state
     */
    function parseRequestState(base64Decode, state) {
        if (!base64Decode) {
            throw createClientAuthError(noCryptoObject);
        }
        if (!state) {
            throw createClientAuthError(invalidState);
        }
        try {
            // Split the state between library state and user passed state and decode them separately
            const splitState = state.split(RESOURCE_DELIM);
            const libraryState = splitState[0];
            const userState = splitState.length > 1
                ? splitState.slice(1).join(RESOURCE_DELIM)
                : "";
            const libraryStateString = base64Decode(libraryState);
            const libraryStateObj = JSON.parse(libraryStateString);
            return {
                userRequestState: userState || "",
                libraryState: libraryStateObj,
            };
        }
        catch (e) {
            throw createClientAuthError(invalidState);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Class that handles response parsing.
     * @internal
     */
    class ResponseHandler {
        constructor(clientId, cacheStorage, cryptoObj, logger, performanceClient, serializableCache, persistencePlugin) {
            this.clientId = clientId;
            this.cacheStorage = cacheStorage;
            this.cryptoObj = cryptoObj;
            this.logger = logger;
            this.performanceClient = performanceClient;
            this.serializableCache = serializableCache;
            this.persistencePlugin = persistencePlugin;
        }
        /**
         * Function which validates server authorization token response.
         * @param serverResponse
         * @param correlationId
         * @param refreshAccessToken
         */
        validateTokenResponse(serverResponse, correlationId, refreshAccessToken) {
            // Check for error
            if (serverResponse.error ||
                serverResponse.error_description ||
                serverResponse.suberror) {
                const errString = `Error(s): ${serverResponse.error_codes || NOT_AVAILABLE} - Timestamp: ${serverResponse.timestamp || NOT_AVAILABLE} - Description: ${serverResponse.error_description || NOT_AVAILABLE} - Correlation ID: ${serverResponse.correlation_id || NOT_AVAILABLE} - Trace ID: ${serverResponse.trace_id || NOT_AVAILABLE}`;
                const serverErrorNo = serverResponse.error_codes?.length
                    ? serverResponse.error_codes[0]
                    : undefined;
                const serverError = new ServerError(serverResponse.error, errString, serverResponse.suberror, serverErrorNo, serverResponse.status);
                // check if 500 error
                if (refreshAccessToken &&
                    serverResponse.status &&
                    serverResponse.status >=
                        HTTP_SERVER_ERROR_RANGE_START &&
                    serverResponse.status <= HTTP_SERVER_ERROR_RANGE_END) {
                    this.logger.warning("16ks7j", correlationId);
                    // don't throw an exception, but alert the user via a log that the token was unable to be refreshed
                    return;
                    // check if 400 error
                }
                else if (refreshAccessToken &&
                    serverResponse.status &&
                    serverResponse.status >=
                        HTTP_CLIENT_ERROR_RANGE_START &&
                    serverResponse.status <= HTTP_CLIENT_ERROR_RANGE_END) {
                    this.logger.warning("0g61x3", correlationId);
                    // don't throw an exception, but alert the user via a log that the token was unable to be refreshed
                    return;
                }
                if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {
                    throw new InteractionRequiredAuthError(serverResponse.error, serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.correlation_id || "", serverResponse.claims || "", serverErrorNo);
                }
                throw serverError;
            }
        }
        /**
         * Returns a constructed token response based on given string. Also manages the cache updates and cleanups.
         * @param serverTokenResponse
         * @param authority
         */
        async handleServerTokenResponse(serverTokenResponse, authority, reqTimestamp, request, apiId, authCodePayload, userAssertionHash, handlingRefreshTokenResponse, forceCacheRefreshTokenResponse, serverRequestId) {
            // create an idToken object (not entity)
            let idTokenClaims;
            if (serverTokenResponse.id_token) {
                idTokenClaims = extractTokenClaims(serverTokenResponse.id_token || "", this.cryptoObj.base64Decode);
                // token nonce check (TODO: Add a warning if no nonce is given?)
                if (authCodePayload && authCodePayload.nonce) {
                    if (idTokenClaims.nonce !== authCodePayload.nonce) {
                        throw createClientAuthError(nonceMismatch);
                    }
                }
                // token max_age check
                if (request.maxAge || request.maxAge === 0) {
                    const authTime = idTokenClaims.auth_time;
                    if (!authTime) {
                        throw createClientAuthError(authTimeNotFound);
                    }
                    checkMaxAge(authTime, request.maxAge);
                }
            }
            // generate homeAccountId
            this.homeAccountIdentifier = generateHomeAccountId(serverTokenResponse.client_info || "", authority.authorityType, this.logger, this.cryptoObj, request.correlationId, idTokenClaims);
            // save the response tokens
            let requestStateObj;
            if (!!authCodePayload && !!authCodePayload.state) {
                requestStateObj = parseRequestState(this.cryptoObj.base64Decode, authCodePayload.state);
            }
            // Add keyId from request to serverTokenResponse if defined
            serverTokenResponse.key_id =
                serverTokenResponse.key_id || request.sshKid || undefined;
            const cacheRecord = this.generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload);
            let cacheContext;
            try {
                if (this.persistencePlugin && this.serializableCache) {
                    this.logger.verbose("0jbz5k", request.correlationId);
                    cacheContext = new TokenCacheContext(this.serializableCache, true);
                    await this.persistencePlugin.beforeCacheAccess(cacheContext);
                }
                /*
                 * When saving a refreshed tokens to the cache, it is expected that the account that was used is present in the cache.
                 * If not present, we should return null, as it's the case that another application called removeAccount in between
                 * the calls to getAllAccounts and acquireTokenSilent. We should not overwrite that removal, unless explicitly flagged by
                 * the developer, as in the case of refresh token flow used in ADAL Node to MSAL Node migration.
                 */
                if (handlingRefreshTokenResponse &&
                    !forceCacheRefreshTokenResponse &&
                    cacheRecord.account) {
                    const cachedAccounts = this.cacheStorage.getAllAccounts({
                        homeAccountId: cacheRecord.account.homeAccountId,
                        environment: cacheRecord.account.environment,
                    }, request.correlationId);
                    if (cachedAccounts.length < 1) {
                        this.logger.warning("1gmt66", request.correlationId);
                        this.performanceClient?.addFields({
                            acntLoggedOut: true,
                        }, request.correlationId);
                        return await ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, this.performanceClient, idTokenClaims, requestStateObj, undefined, serverRequestId);
                    }
                }
                await this.cacheStorage.saveCacheRecord(cacheRecord, request.correlationId, isKmsi(idTokenClaims || {}), apiId, request.storeInCache);
            }
            finally {
                if (this.persistencePlugin &&
                    this.serializableCache &&
                    cacheContext) {
                    this.logger.verbose("1bh17u", request.correlationId);
                    await this.persistencePlugin.afterCacheAccess(cacheContext);
                }
            }
            return ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, this.performanceClient, idTokenClaims, requestStateObj, serverTokenResponse, serverRequestId);
        }
        /**
         * Generates CacheRecord
         * @param serverTokenResponse
         * @param idTokenObj
         * @param authority
         */
        generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload) {
            const env = authority.getPreferredCache();
            if (!env) {
                throw createClientAuthError(invalidCacheEnvironment);
            }
            const claimsTenantId = getTenantIdFromIdTokenClaims(idTokenClaims);
            // IdToken: non AAD scenarios can have empty realm
            let cachedIdToken;
            let cachedAccount;
            if (serverTokenResponse.id_token && !!idTokenClaims) {
                cachedIdToken = createIdTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.id_token, this.clientId, claimsTenantId || "");
                cachedAccount = buildAccountToCache(this.cacheStorage, authority, this.homeAccountIdentifier, this.cryptoObj.base64Decode, request.correlationId, idTokenClaims, serverTokenResponse.client_info, env, claimsTenantId, authCodePayload, undefined, // nativeAccountId
                this.logger, this.performanceClient);
            }
            // AccessToken
            let cachedAccessToken = null;
            if (serverTokenResponse.access_token) {
                // If scopes not returned in server response, use request scopes
                const responseScopes = serverTokenResponse.scope
                    ? ScopeSet.fromString(serverTokenResponse.scope)
                    : new ScopeSet(request.scopes || []);
                /*
                 * Use timestamp calculated before request
                 * Server may return timestamps as strings, parse to numbers if so.
                 */
                const expiresIn = (typeof serverTokenResponse.expires_in === "string"
                    ? parseInt(serverTokenResponse.expires_in, 10)
                    : serverTokenResponse.expires_in) || 0;
                const extExpiresIn = (typeof serverTokenResponse.ext_expires_in === "string"
                    ? parseInt(serverTokenResponse.ext_expires_in, 10)
                    : serverTokenResponse.ext_expires_in) || 0;
                const refreshIn = (typeof serverTokenResponse.refresh_in === "string"
                    ? parseInt(serverTokenResponse.refresh_in, 10)
                    : serverTokenResponse.refresh_in) || undefined;
                const tokenExpirationSeconds = reqTimestamp + expiresIn;
                const extendedTokenExpirationSeconds = tokenExpirationSeconds + extExpiresIn;
                const refreshOnSeconds = refreshIn && refreshIn > 0
                    ? reqTimestamp + refreshIn
                    : undefined;
                // non AAD scenarios can have empty realm
                cachedAccessToken = createAccessTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.access_token, this.clientId, claimsTenantId || authority.tenant || "", responseScopes.printScopes(), tokenExpirationSeconds, extendedTokenExpirationSeconds, this.cryptoObj.base64Decode, refreshOnSeconds, serverTokenResponse.token_type, userAssertionHash, serverTokenResponse.key_id);
                // Set resource (to be used for MCP scenarios)
                const resource = request.resource || null;
                if (resource) {
                    cachedAccessToken.resource = resource;
                }
            }
            // refreshToken
            let cachedRefreshToken = null;
            if (serverTokenResponse.refresh_token) {
                let rtExpiresOn;
                if (serverTokenResponse.refresh_token_expires_in) {
                    const rtExpiresIn = typeof serverTokenResponse.refresh_token_expires_in ===
                        "string"
                        ? parseInt(serverTokenResponse.refresh_token_expires_in, 10)
                        : serverTokenResponse.refresh_token_expires_in;
                    rtExpiresOn = reqTimestamp + rtExpiresIn;
                    this.performanceClient?.addFields({ ntwkRtExpiresOnSeconds: rtExpiresOn }, request.correlationId);
                }
                cachedRefreshToken = createRefreshTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.refresh_token, this.clientId, serverTokenResponse.foci, userAssertionHash, rtExpiresOn);
            }
            // appMetadata
            let cachedAppMetadata = null;
            if (serverTokenResponse.foci) {
                cachedAppMetadata = {
                    clientId: this.clientId,
                    environment: env,
                    familyId: serverTokenResponse.foci,
                };
            }
            return {
                account: cachedAccount,
                idToken: cachedIdToken,
                accessToken: cachedAccessToken,
                refreshToken: cachedRefreshToken,
                appMetadata: cachedAppMetadata,
            };
        }
        /**
         * Creates an @AuthenticationResult from @CacheRecord , @IdToken , and a boolean that states whether or not the result is from cache.
         *
         * Optionally takes a state string that is set as-is in the response.
         *
         * @param cacheRecord
         * @param idTokenObj
         * @param fromTokenCache
         * @param stateString
         */
        static async generateAuthenticationResult(cryptoObj, authority, cacheRecord, fromTokenCache, request, performanceClient, idTokenClaims, requestState, serverTokenResponse, requestId) {
            let accessToken = "";
            let responseScopes = [];
            let expiresOn = null;
            let extExpiresOn;
            let refreshOn;
            let familyId = "";
            if (cacheRecord.accessToken) {
                /*
                 * if the request object has `popKid` property, `signPopToken` will be set to false and
                 * the token will be returned unsigned
                 */
                if (cacheRecord.accessToken.tokenType ===
                    AuthenticationScheme$1.POP &&
                    !request.popKid) {
                    const popTokenGenerator = new PopTokenGenerator(cryptoObj, performanceClient);
                    const { secret, keyId } = cacheRecord.accessToken;
                    if (!keyId) {
                        throw createClientAuthError(keyIdMissing);
                    }
                    accessToken = await popTokenGenerator.signPopToken(secret, keyId, request);
                }
                else {
                    accessToken = cacheRecord.accessToken.secret;
                }
                responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target).asArray();
                // Access token expiresOn cached in seconds, converting to Date for AuthenticationResult
                expiresOn = toDateFromSeconds(cacheRecord.accessToken.expiresOn);
                extExpiresOn = toDateFromSeconds(cacheRecord.accessToken.extendedExpiresOn);
                if (cacheRecord.accessToken.refreshOn) {
                    refreshOn = toDateFromSeconds(cacheRecord.accessToken.refreshOn);
                }
            }
            if (cacheRecord.appMetadata) {
                familyId =
                    cacheRecord.appMetadata.familyId === THE_FAMILY_ID
                        ? THE_FAMILY_ID
                        : "";
            }
            const uid = idTokenClaims?.oid || idTokenClaims?.sub || "";
            const tid = idTokenClaims?.tid || "";
            // for hybrid + native bridge enablement, send back the native account Id
            if (serverTokenResponse?.spa_accountid && !!cacheRecord.account) {
                cacheRecord.account.nativeAccountId =
                    serverTokenResponse?.spa_accountid;
            }
            const accountInfo = cacheRecord.account
                ? updateAccountTenantProfileData(getAccountInfo(cacheRecord.account), undefined, // tenantProfile optional
                idTokenClaims, cacheRecord.idToken?.secret)
                : null;
            return {
                authority: authority.canonicalAuthority,
                uniqueId: uid,
                tenantId: tid,
                scopes: responseScopes,
                account: accountInfo,
                idToken: cacheRecord?.idToken?.secret || "",
                idTokenClaims: idTokenClaims || {},
                accessToken: accessToken,
                fromCache: fromTokenCache,
                expiresOn: expiresOn,
                extExpiresOn: extExpiresOn,
                refreshOn: refreshOn,
                correlationId: request.correlationId,
                requestId: requestId || "",
                familyId: familyId,
                tokenType: cacheRecord.accessToken?.tokenType || "",
                state: requestState ? requestState.userRequestState : "",
                cloudGraphHostName: cacheRecord.account?.cloudGraphHostName || "",
                msGraphHost: cacheRecord.account?.msGraphHost || "",
                code: serverTokenResponse?.spa_code,
                fromPlatformBroker: false,
            };
        }
    }
    function buildAccountToCache(cacheStorage, authority, homeAccountId, base64Decode, correlationId, idTokenClaims, clientInfo, environment, claimsTenantId, authCodePayload, nativeAccountId, logger, performanceClient) {
        logger?.verbose("09jz0t", correlationId);
        /*
         * Check if base account is already cached. Filter by homeAccountId (identifies
         * the user's home identity) and environment (identifies the cloud) — the two
         * tenant-agnostic properties that uniquely locate a base AccountEntity.
         */
        const accountEnvironment = environment || authority.getPreferredCache();
        const matchedAccounts = cacheStorage.getAccountsFilteredBy({ homeAccountId, environment: accountEnvironment }, correlationId);
        performanceClient?.addFields({ cacheMatchedAccounts: matchedAccounts.length }, correlationId);
        if (matchedAccounts.length > 1) {
            /*
             * Base accounts are expected to be unique for a given homeAccountId in normal cache usage.
             * If multiple matches exist, ignore the cache hit rather than arbitrarily choosing one.
             */
            logger?.warning("0x7ad1", correlationId);
        }
        const cachedAccount = matchedAccounts.length === 1 ? matchedAccounts[0] : null;
        const baseAccount = cachedAccount ||
            createAccountEntity({
                homeAccountId,
                idTokenClaims,
                clientInfo,
                environment,
                cloudGraphHostName: authCodePayload?.cloud_graph_host_name,
                msGraphHost: authCodePayload?.msgraph_host,
                nativeAccountId: nativeAccountId,
            }, authority, base64Decode);
        const tenantProfiles = baseAccount.tenantProfiles || [];
        const tenantId = claimsTenantId || baseAccount.realm;
        if (tenantId &&
            !tenantProfiles.find((tenantProfile) => {
                return tenantProfile.tenantId === tenantId;
            })) {
            const newTenantProfile = buildTenantProfile(homeAccountId, baseAccount.localAccountId, tenantId, idTokenClaims);
            tenantProfiles.push(newTenantProfile);
        }
        baseAccount.tenantProfiles = tenantProfiles;
        return baseAccount;
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const CcsCredentialType = {
        HOME_ACCOUNT_ID: "home_account_id",
        UPN: "UPN",
    };
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    async function getClientAssertion(clientAssertion, clientId, tokenEndpoint) {
        if (typeof clientAssertion === "string") {
            return clientAssertion;
        }
        else {
            const config = {
                clientId: clientId,
                tokenEndpoint: tokenEndpoint,
            };
            return clientAssertion(config);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function getRequestThumbprint(clientId, request, homeAccountId) {
        return {
            clientId: clientId,
            authority: request.authority,
            scopes: request.scopes,
            homeAccountIdentifier: homeAccountId,
            claims: request.claims,
            authenticationScheme: request.authenticationScheme,
            resourceRequestMethod: request.resourceRequestMethod,
            resourceRequestUri: request.resourceRequestUri,
            shrClaims: request.shrClaims,
            sshKid: request.sshKid,
            embeddedClientId: request.embeddedClientId || request.extraParameters?.clientId,
        };
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /** @internal */
    class ThrottlingUtils {
        /**
         * Prepares a RequestThumbprint to be stored as a key.
         * @param thumbprint
         */
        static generateThrottlingStorageKey(thumbprint) {
            return `${THROTTLING_PREFIX}.${JSON.stringify(thumbprint)}`;
        }
        /**
         * Performs necessary throttling checks before a network request.
         * @param cacheManager
         * @param thumbprint
         */
        static preProcess(cacheManager, thumbprint, correlationId) {
            const key = ThrottlingUtils.generateThrottlingStorageKey(thumbprint);
            const value = cacheManager.getThrottlingCache(key, correlationId);
            if (value) {
                if (value.throttleTime < Date.now()) {
                    cacheManager.removeItem(key, correlationId);
                    return;
                }
                throw new ServerError(value.errorCodes?.join(" ") || "", value.errorMessage, value.subError);
            }
        }
        /**
         * Performs necessary throttling checks after a network request.
         * @param cacheManager
         * @param thumbprint
         * @param response
         */
        static postProcess(cacheManager, thumbprint, response, correlationId) {
            if (ThrottlingUtils.checkResponseStatus(response) ||
                ThrottlingUtils.checkResponseForRetryAfter(response)) {
                const thumbprintValue = {
                    throttleTime: ThrottlingUtils.calculateThrottleTime(parseInt(response.headers[HeaderNames.RETRY_AFTER])),
                    error: response.body.error,
                    errorCodes: response.body.error_codes,
                    errorMessage: response.body.error_description,
                    subError: response.body.suberror,
                };
                cacheManager.setThrottlingCache(ThrottlingUtils.generateThrottlingStorageKey(thumbprint), thumbprintValue, correlationId);
            }
        }
        /**
         * Checks a NetworkResponse object's status codes against 429 or 5xx
         * @param response
         */
        static checkResponseStatus(response) {
            return (response.status === 429 ||
                (response.status >= 500 && response.status < 600));
        }
        /**
         * Checks a NetworkResponse object's RetryAfter header
         * @param response
         */
        static checkResponseForRetryAfter(response) {
            if (response.headers) {
                return (response.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) &&
                    (response.status < 200 || response.status >= 300));
            }
            return false;
        }
        /**
         * Calculates the Unix-time value for a throttle to expire given throttleTime in seconds.
         * @param throttleTime
         */
        static calculateThrottleTime(throttleTime) {
            const time = throttleTime <= 0 ? 0 : throttleTime;
            const currentSeconds = Date.now() / 1000;
            return Math.floor(Math.min(currentSeconds +
                (time || DEFAULT_THROTTLE_TIME_SECONDS), currentSeconds + DEFAULT_MAX_THROTTLE_TIME_SECONDS) * 1000);
        }
        static removeThrottle(cacheManager, clientId, request, homeAccountIdentifier) {
            const thumbprint = getRequestThumbprint(clientId, request, homeAccountIdentifier);
            const key = this.generateThrottlingStorageKey(thumbprint);
            cacheManager.removeItem(key, request.correlationId);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Represents network related errors
     */
    class NetworkError extends AuthError {
        constructor(error, httpStatus, responseHeaders) {
            super(error.errorCode, error.errorMessage, error.subError);
            Object.setPrototypeOf(this, NetworkError.prototype);
            this.name = "NetworkError";
            this.error = error;
            this.httpStatus = httpStatus;
            this.responseHeaders = responseHeaders;
        }
    }
    /**
     * Creates NetworkError object for a failed network request
     * @param error - Error to be thrown back to the caller
     * @param httpStatus - Status code of the network request
     * @param responseHeaders - Response headers of the network request, when available
     * @returns NetworkError object
     */
    function createNetworkError(error, httpStatus, responseHeaders, additionalError) {
        error.errorMessage = `${error.errorMessage}, additionalErrorInfo: error.name:${additionalError?.name}, error.message:${additionalError?.message}`;
        return new NetworkError(error, httpStatus, responseHeaders);
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Creates default headers for requests to token endpoint
     */
    function createTokenRequestHeaders(logger, preventCorsPreflight, ccsCred) {
        const headers = {};
        headers[HeaderNames.CONTENT_TYPE] = URL_FORM_CONTENT_TYPE;
        if (!preventCorsPreflight && ccsCred) {
            switch (ccsCred.type) {
                case CcsCredentialType.HOME_ACCOUNT_ID:
                    try {
                        const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
                        headers[HeaderNames.CCS_HEADER] = `Oid:${clientInfo.uid}@${clientInfo.utid}`;
                    }
                    catch (e) {
                        logger.verbose("1qhtee", "");
                    }
                    break;
                case CcsCredentialType.UPN:
                    headers[HeaderNames.CCS_HEADER] = `UPN: ${ccsCred.credential}`;
                    break;
            }
        }
        return headers;
    }
    /**
     * Creates query string for the /token request
     * @param request
     */
    function createTokenQueryParameters(request, clientId, redirectUri, performanceClient) {
        const parameters = new Map();
        if (request.embeddedClientId) {
            addBrokerParameters(parameters, clientId, redirectUri);
        }
        if (request.extraQueryParameters) {
            addExtraParameters(parameters, request.extraQueryParameters);
        }
        addCorrelationId(parameters, request.correlationId);
        instrumentBrokerParams(parameters, request.correlationId, performanceClient);
        return mapToQueryString(parameters);
    }
    /**
     * Http post to token endpoint
     * @param tokenEndpoint
     * @param queryString
     * @param headers
     * @param thumbprint
     */
    async function executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, cacheManager, networkClient, logger, performanceClient, serverTelemetryManager) {
        const response = await sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers: headers }, correlationId, cacheManager, networkClient, logger, performanceClient);
        if (serverTelemetryManager &&
            response.status < 500 &&
            response.status !== 429) {
            // Telemetry data successfully logged by server, clear Telemetry cache
            serverTelemetryManager.clearTelemetryCache();
        }
        return response;
    }
    /**
     * Wraps sendPostRequestAsync with necessary preflight and postflight logic
     * @param thumbprint - Request thumbprint for throttling
     * @param tokenEndpoint - Endpoint to make the POST to
     * @param options - Body and Headers to include on the POST request
     * @param correlationId - CorrelationId for telemetry
     * @param cacheManager - Cache manager instance
     * @param networkClient - Network module instance
     * @param logger - Logger instance
     * @param performanceClient - Performance client instance
     */
    async function sendPostRequest(thumbprint, tokenEndpoint, options, correlationId, cacheManager, networkClient, logger, performanceClient) {
        ThrottlingUtils.preProcess(cacheManager, thumbprint, correlationId);
        let response;
        try {
            response = await invokeAsync((networkClient.sendPostRequestAsync.bind(networkClient)), NetworkClientSendPostRequestAsync, logger, performanceClient, correlationId)(tokenEndpoint, options);
            const responseHeaders = response.headers || {};
            performanceClient?.addFields({
                refreshTokenSize: response.body.refresh_token?.length || 0,
                httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",
                requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "",
            }, correlationId);
        }
        catch (e) {
            if (e instanceof NetworkError) {
                const responseHeaders = e.responseHeaders;
                if (responseHeaders) {
                    performanceClient?.addFields({
                        httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] ||
                            "",
                        requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "",
                        contentTypeHeader: responseHeaders[HeaderNames.CONTENT_TYPE] ||
                            undefined,
                        contentLengthHeader: responseHeaders[HeaderNames.CONTENT_LENGTH] ||
                            undefined,
                        httpStatus: e.httpStatus,
                    }, correlationId);
                }
                throw e.error;
            }
            if (e instanceof AuthError) {
                throw e;
            }
            else {
                throw createClientAuthError(networkError);
            }
        }
        ThrottlingUtils.postProcess(cacheManager, thumbprint, response, correlationId);
        return response;
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function isOpenIdConfigResponse(response) {
        return (response.hasOwnProperty("authorization_endpoint") &&
            response.hasOwnProperty("token_endpoint") &&
            response.hasOwnProperty("issuer") &&
            response.hasOwnProperty("jwks_uri"));
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function isCloudInstanceDiscoveryResponse(response) {
        return (response.hasOwnProperty("tenant_discovery_endpoint") &&
            response.hasOwnProperty("metadata"));
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function isCloudInstanceDiscoveryErrorResponse(response) {
        return (response.hasOwnProperty("error") &&
            response.hasOwnProperty("error_description"));
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class RegionDiscovery {
        constructor(networkInterface, logger, performanceClient, correlationId) {
            this.networkInterface = networkInterface;
            this.logger = logger;
            this.performanceClient = performanceClient;
            this.correlationId = correlationId;
        }
        /**
         * Detect the region from the application's environment.
         *
         * @returns Promise<string | null>
         */
        async detectRegion(environmentRegion, regionDiscoveryMetadata) {
            // Initialize auto detected region with the region from the envrionment
            let autodetectedRegionName = environmentRegion;
            // Check if a region was detected from the environment, if not, attempt to get the region from IMDS
            if (!autodetectedRegionName) {
                const options = RegionDiscovery.IMDS_OPTIONS;
                try {
                    const localIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(IMDS_VERSION, options);
                    if (localIMDSVersionResponse.status === HTTP_SUCCESS) {
                        autodetectedRegionName = localIMDSVersionResponse.body;
                        regionDiscoveryMetadata.region_source =
                            RegionDiscoverySources.IMDS;
                    }
                    // If the response using the local IMDS version failed, try to fetch the current version of IMDS and retry.
                    if (localIMDSVersionResponse.status ===
                        HTTP_BAD_REQUEST) {
                        const currentIMDSVersion = await invokeAsync(this.getCurrentVersion.bind(this), RegionDiscoveryGetCurrentVersion, this.logger, this.performanceClient, this.correlationId)(options);
                        if (!currentIMDSVersion) {
                            regionDiscoveryMetadata.region_source =
                                RegionDiscoverySources.FAILED_AUTO_DETECTION;
                            return null;
                        }
                        const currentIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(currentIMDSVersion, options);
                        if (currentIMDSVersionResponse.status ===
                            HTTP_SUCCESS) {
                            autodetectedRegionName =
                                currentIMDSVersionResponse.body;
                            regionDiscoveryMetadata.region_source =
                                RegionDiscoverySources.IMDS;
                        }
                    }
                }
                catch (e) {
                    regionDiscoveryMetadata.region_source =
                        RegionDiscoverySources.FAILED_AUTO_DETECTION;
                    return null;
                }
            }
            else {
                regionDiscoveryMetadata.region_source =
                    RegionDiscoverySources.ENVIRONMENT_VARIABLE;
            }
            // If no region was auto detected from the environment or from the IMDS endpoint, mark the attempt as a FAILED_AUTO_DETECTION
            if (!autodetectedRegionName) {
                regionDiscoveryMetadata.region_source =
                    RegionDiscoverySources.FAILED_AUTO_DETECTION;
            }
            return autodetectedRegionName || null;
        }
        /**
         * Make the call to the IMDS endpoint
         *
         * @param imdsEndpointUrl
         * @returns Promise<NetworkResponse<string>>
         */
        async getRegionFromIMDS(version, options) {
            return this.networkInterface.sendGetRequestAsync(`${IMDS_ENDPOINT}?api-version=${version}&format=text`, options, IMDS_TIMEOUT);
        }
        /**
         * Get the most recent version of the IMDS endpoint available
         *
         * @returns Promise<string | null>
         */
        async getCurrentVersion(options) {
            try {
                const response = await this.networkInterface.sendGetRequestAsync(`${IMDS_ENDPOINT}?format=json`, options);
                // When IMDS endpoint is called without the api version query param, bad request response comes back with latest version.
                if (response.status === HTTP_BAD_REQUEST &&
                    response.body &&
                    response.body["newest-versions"] &&
                    response.body["newest-versions"].length > 0) {
                    return response.body["newest-versions"][0];
                }
                return null;
            }
            catch (e) {
                return null;
            }
        }
    }
    // Options for the IMDS endpoint request
    RegionDiscovery.IMDS_OPTIONS = {
        headers: {
            Metadata: "true",
        },
    };
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * The authority class validates the authority URIs used by the user, and retrieves the OpenID Configuration Data from the
     * endpoint. It will store the pertinent config data in this object for use during token calls.
     * @internal
     */
    class Authority {
        constructor(authority, networkInterface, cacheManager, authorityOptions, logger, correlationId, performanceClient, managedIdentity) {
            this.canonicalAuthority = authority;
            this._canonicalAuthority.validateAsUri();
            this.networkInterface = networkInterface;
            this.cacheManager = cacheManager;
            this.authorityOptions = authorityOptions;
            this.regionDiscoveryMetadata = {
                region_used: undefined,
                region_source: undefined,
                region_outcome: undefined,
            };
            this.logger = logger;
            this.performanceClient = performanceClient;
            this.correlationId = correlationId;
            this.managedIdentity = managedIdentity || false;
            this.regionDiscovery = new RegionDiscovery(networkInterface, this.logger, this.performanceClient, this.correlationId);
        }
        /**
         * Get {@link AuthorityType}
         * @param authorityUri {@link IUri}
         * @private
         */
        getAuthorityType(authorityUri) {
            // CIAM auth url pattern is being standardized as: <tenant>.ciamlogin.com
            if (authorityUri.HostNameAndPort.endsWith(CIAM_AUTH_URL)) {
                return AuthorityType.Ciam;
            }
            const pathSegments = authorityUri.PathSegments;
            if (pathSegments.length) {
                switch (pathSegments[0].toLowerCase()) {
                    case ADFS:
                        return AuthorityType.Adfs;
                    case DSTS:
                        return AuthorityType.Dsts;
                }
            }
            return AuthorityType.Default;
        }
        // See above for AuthorityType
        get authorityType() {
            return this.getAuthorityType(this.canonicalAuthorityUrlComponents);
        }
        /**
         * ProtocolMode enum representing the way endpoints are constructed.
         */
        get protocolMode() {
            return this.authorityOptions.protocolMode;
        }
        /**
         * Returns authorityOptions which can be used to reinstantiate a new authority instance
         */
        get options() {
            return this.authorityOptions;
        }
        /**
         * A URL that is the authority set by the developer
         */
        get canonicalAuthority() {
            return this._canonicalAuthority.urlString;
        }
        /**
         * Sets canonical authority.
         */
        set canonicalAuthority(url) {
            this._canonicalAuthority = new UrlString(url);
            this._canonicalAuthority.validateAsUri();
            this._canonicalAuthorityUrlComponents = null;
        }
        /**
         * Get authority components.
         */
        get canonicalAuthorityUrlComponents() {
            if (!this._canonicalAuthorityUrlComponents) {
                this._canonicalAuthorityUrlComponents =
                    this._canonicalAuthority.getUrlComponents();
            }
            return this._canonicalAuthorityUrlComponents;
        }
        /**
         * Get hostname and port i.e. login.microsoftonline.com
         */
        get hostnameAndPort() {
            return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();
        }
        /**
         * Get tenant for authority.
         */
        get tenant() {
            return this.canonicalAuthorityUrlComponents.PathSegments[0];
        }
        /**
         * OAuth /authorize endpoint for requests
         */
        get authorizationEndpoint() {
            if (this.discoveryComplete()) {
                return this.replacePath(this.metadata.authorization_endpoint);
            }
            else {
                throw createClientAuthError(endpointResolutionError);
            }
        }
        /**
         * OAuth /token endpoint for requests
         */
        get tokenEndpoint() {
            if (this.discoveryComplete()) {
                return this.replacePath(this.metadata.token_endpoint);
            }
            else {
                throw createClientAuthError(endpointResolutionError);
            }
        }
        get deviceCodeEndpoint() {
            if (this.discoveryComplete()) {
                return this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode"));
            }
            else {
                throw createClientAuthError(endpointResolutionError);
            }
        }
        /**
         * OAuth logout endpoint for requests
         */
        get endSessionEndpoint() {
            if (this.discoveryComplete()) {
                // ROPC policies may not have end_session_endpoint set
                if (!this.metadata.end_session_endpoint) {
                    throw createClientAuthError(endSessionEndpointNotSupported);
                }
                return this.replacePath(this.metadata.end_session_endpoint);
            }
            else {
                throw createClientAuthError(endpointResolutionError);
            }
        }
        /**
         * OAuth issuer for requests
         */
        get selfSignedJwtAudience() {
            if (this.discoveryComplete()) {
                return this.replacePath(this.metadata.issuer);
            }
            else {
                throw createClientAuthError(endpointResolutionError);
            }
        }
        /**
         * Jwks_uri for token signing keys
         */
        get jwksUri() {
            if (this.discoveryComplete()) {
                return this.replacePath(this.metadata.jwks_uri);
            }
            else {
                throw createClientAuthError(endpointResolutionError);
            }
        }
        /**
         * Returns a flag indicating that tenant name can be replaced in authority {@link IUri}
         * @param authorityUri {@link IUri}
         * @private
         */
        canReplaceTenant(authorityUri) {
            return (authorityUri.PathSegments.length === 1 &&
                !Authority.reservedTenantDomains.has(authorityUri.PathSegments[0]) &&
                this.getAuthorityType(authorityUri) === AuthorityType.Default &&
                this.protocolMode !== ProtocolMode.OIDC);
        }
        /**
         * Replaces tenant in url path with current tenant. Defaults to common.
         * @param urlString
         */
        replaceTenant(urlString) {
            return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);
        }
        /**
         * Replaces path such as tenant or policy with the current tenant or policy.
         * @param urlString
         */
        replacePath(urlString) {
            let endpoint = urlString;
            const cachedAuthorityUrl = new UrlString(this.metadata.canonical_authority);
            const cachedAuthorityUrlComponents = cachedAuthorityUrl.getUrlComponents();
            const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments;
            const currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments;
            currentAuthorityParts.forEach((currentPart, index) => {
                let cachedPart = cachedAuthorityParts[index];
                if (index === 0 &&
                    this.canReplaceTenant(cachedAuthorityUrlComponents)) {
                    const tenantId = new UrlString(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];
                    /**
                     * Check if AAD canonical authority contains tenant domain name, for example "testdomain.onmicrosoft.com",
                     * by comparing its first path segment to the corresponding authorization endpoint path segment, which is
                     * always resolved with tenant id by OIDC.
                     */
                    if (cachedPart !== tenantId) {
                        this.logger.verbose("1q3g2x", this.correlationId);
                        cachedPart = tenantId;
                    }
                }
                if (currentPart !== cachedPart) {
                    endpoint = endpoint.replace(`/${cachedPart}/`, `/${currentPart}/`);
                }
            });
            return this.replaceTenant(endpoint);
        }
        /**
         * The default open id configuration endpoint for any canonical authority.
         */
        get defaultOpenIdConfigurationEndpoint() {
            const canonicalAuthorityHost = this.hostnameAndPort;
            if (this.canonicalAuthority.endsWith("v2.0/") ||
                this.authorityType === AuthorityType.Adfs ||
                (this.protocolMode === ProtocolMode.OIDC &&
                    !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost))) {
                return `${this.canonicalAuthority}.well-known/openid-configuration`;
            }
            return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;
        }
        /**
         * Boolean that returns whether or not tenant discovery has been completed.
         */
        discoveryComplete() {
            return !!this.metadata;
        }
        /**
         * Perform endpoint discovery to discover aliases, preferred_cache, preferred_network
         * and the /authorize, /token and logout endpoints.
         */
        async resolveEndpointsAsync() {
            const metadataEntity = this.getCurrentMetadataEntity();
            const cloudDiscoverySource = await invokeAsync(this.updateCloudDiscoveryMetadata.bind(this), AuthorityUpdateCloudDiscoveryMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
            this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network);
            const endpointSource = await invokeAsync(this.updateEndpointMetadata.bind(this), AuthorityUpdateEndpointMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
            this.updateCachedMetadata(metadataEntity, cloudDiscoverySource, {
                source: endpointSource,
            });
            this.performanceClient?.addFields({
                cloudDiscoverySource: cloudDiscoverySource,
                authorityEndpointSource: endpointSource,
            }, this.correlationId);
        }
        /**
         * Returns metadata entity from cache if it exists, otherwiser returns a new metadata entity built
         * from the configured canonical authority
         * @returns
         */
        getCurrentMetadataEntity() {
            let metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort, this.correlationId);
            if (!metadataEntity) {
                metadataEntity = {
                    aliases: [],
                    preferred_cache: this.hostnameAndPort,
                    preferred_network: this.hostnameAndPort,
                    canonical_authority: this.canonicalAuthority,
                    authorization_endpoint: "",
                    token_endpoint: "",
                    end_session_endpoint: "",
                    issuer: "",
                    aliasesFromNetwork: false,
                    endpointsFromNetwork: false,
                    expiresAt: generateAuthorityMetadataExpiresAt(),
                    jwks_uri: "",
                };
            }
            return metadataEntity;
        }
        /**
         * Updates cached metadata based on metadata source and sets the instance's metadata
         * property to the same value
         * @param metadataEntity
         * @param cloudDiscoverySource
         * @param endpointMetadataResult
         */
        updateCachedMetadata(metadataEntity, cloudDiscoverySource, endpointMetadataResult) {
            if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE &&
                endpointMetadataResult?.source !==
                    AuthorityMetadataSource.CACHE) {
                // Reset the expiration time unless both values came from a successful cache lookup
                metadataEntity.expiresAt =
                    generateAuthorityMetadataExpiresAt();
                metadataEntity.canonical_authority = this.canonicalAuthority;
            }
            const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache, this.correlationId);
            this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity, this.correlationId);
            this.metadata = metadataEntity;
        }
        /**
         * Update AuthorityMetadataEntity with new endpoints and return where the information came from
         * @param metadataEntity
         */
        async updateEndpointMetadata(metadataEntity) {
            const localMetadata = this.updateEndpointMetadataFromLocalSources(metadataEntity);
            // Further update may be required for hardcoded metadata if regional metadata is preferred
            if (localMetadata) {
                if (localMetadata.source ===
                    AuthorityMetadataSource.HARDCODED_VALUES) {
                    // If the user prefers to use an azure region replace the global endpoints with regional information.
                    if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
                        if (localMetadata.metadata) {
                            const hardcodedMetadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(localMetadata.metadata);
                            updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false);
                            metadataEntity.canonical_authority =
                                this.canonicalAuthority;
                        }
                    }
                }
                return localMetadata.source;
            }
            // Get metadata from network if local sources aren't available
            let metadata = await invokeAsync(this.getEndpointMetadataFromNetwork.bind(this), AuthorityGetEndpointMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
            if (metadata) {
                // If the user prefers to use an azure region replace the global endpoints with regional information.
                if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
                    metadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(metadata);
                }
                updateAuthorityEndpointMetadata(metadataEntity, metadata, true);
                return AuthorityMetadataSource.NETWORK;
            }
            else {
                // Metadata could not be obtained from the config, cache, network or hardcoded values
                throw createClientAuthError(openIdConfigError, this.defaultOpenIdConfigurationEndpoint);
            }
        }
        /**
         * Updates endpoint metadata from local sources and returns where the information was retrieved from and the metadata config
         * response if the source is hardcoded metadata
         * @param metadataEntity
         * @returns
         */
        updateEndpointMetadataFromLocalSources(metadataEntity) {
            this.logger.verbose("1fi0kc", this.correlationId);
            const configMetadata = this.getEndpointMetadataFromConfig();
            if (configMetadata) {
                this.logger.verbose("06t0uj", this.correlationId);
                updateAuthorityEndpointMetadata(metadataEntity, configMetadata, false);
                return {
                    source: AuthorityMetadataSource.CONFIG,
                };
            }
            this.logger.verbose("151k0p", this.correlationId);
            const hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
            if (hardcodedMetadata) {
                updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false);
                return {
                    source: AuthorityMetadataSource.HARDCODED_VALUES,
                    metadata: hardcodedMetadata,
                };
            }
            else {
                this.logger.verbose("1imop5", this.correlationId);
            }
            // Check cached metadata entity expiration status
            const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity);
            if (this.isAuthoritySameType(metadataEntity) &&
                metadataEntity.endpointsFromNetwork &&
                !metadataEntityExpired) {
                // No need to update
                this.logger.verbose("16uq31", "");
                return { source: AuthorityMetadataSource.CACHE };
            }
            else if (metadataEntityExpired) {
                this.logger.verbose("0uoibc", "");
            }
            return null;
        }
        /**
         * Compares the number of url components after the domain to determine if the cached
         * authority metadata can be used for the requested authority. Protects against same domain different
         * authority such as login.microsoftonline.com/tenant and login.microsoftonline.com/tfp/tenant/policy
         * @param metadataEntity
         */
        isAuthoritySameType(metadataEntity) {
            const cachedAuthorityUrl = new UrlString(metadataEntity.canonical_authority);
            const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments;
            return (cachedParts.length ===
                this.canonicalAuthorityUrlComponents.PathSegments.length);
        }
        /**
         * Parse authorityMetadata config option
         */
        getEndpointMetadataFromConfig() {
            if (this.authorityOptions.authorityMetadata) {
                try {
                    return JSON.parse(this.authorityOptions.authorityMetadata);
                }
                catch (e) {
                    throw createClientConfigurationError(invalidAuthorityMetadata);
                }
            }
            return null;
        }
        /**
         * Gets OAuth endpoints from the given OpenID configuration endpoint.
         *
         * @param hasHardcodedMetadata boolean
         */
        async getEndpointMetadataFromNetwork() {
            const options = {};
            /*
             * TODO: Add a timeout if the authority exists in our library's
             * hardcoded list of metadata
             */
            const openIdConfigurationEndpoint = this.defaultOpenIdConfigurationEndpoint;
            this.logger.verbose("1y65x6", this.correlationId);
            try {
                const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options);
                const isValidResponse = isOpenIdConfigResponse(response.body);
                if (isValidResponse) {
                    return response.body;
                }
                else {
                    this.logger.verbose("1koyv8", this.correlationId);
                    return null;
                }
            }
            catch (e) {
                this.logger.verbose("0a9wik", this.correlationId);
                return null;
            }
        }
        /**
         * Get OAuth endpoints for common authorities.
         */
        getEndpointMetadataFromHardcodedValues() {
            if (this.hostnameAndPort in EndpointMetadata) {
                return EndpointMetadata[this.hostnameAndPort];
            }
            return null;
        }
        /**
         * Update the retrieved metadata with regional information.
         * User selected Azure region will be used if configured.
         */
        async updateMetadataWithRegionalInformation(metadata) {
            const userConfiguredAzureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion;
            if (userConfiguredAzureRegion) {
                if (userConfiguredAzureRegion !==
                    AZURE_REGION_AUTO_DISCOVER_FLAG) {
                    this.regionDiscoveryMetadata.region_outcome =
                        RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
                    this.regionDiscoveryMetadata.region_used =
                        userConfiguredAzureRegion;
                    return Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion);
                }
                const autodetectedRegionName = await invokeAsync(this.regionDiscovery.detectRegion.bind(this.regionDiscovery), RegionDiscoveryDetectRegion, this.logger, this.performanceClient, this.correlationId)(this.authorityOptions.azureRegionConfiguration
                    ?.environmentRegion, this.regionDiscoveryMetadata);
                if (autodetectedRegionName) {
                    this.regionDiscoveryMetadata.region_outcome =
                        RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL;
                    this.regionDiscoveryMetadata.region_used =
                        autodetectedRegionName;
                    return Authority.replaceWithRegionalInformation(metadata, autodetectedRegionName);
                }
                this.regionDiscoveryMetadata.region_outcome =
                    RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
            }
            return metadata;
        }
        /**
         * Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache
         * and returns where the information was retrieved from
         * @param metadataEntity
         * @returns AuthorityMetadataSource
         */
        async updateCloudDiscoveryMetadata(metadataEntity) {
            const localMetadataSource = this.updateCloudDiscoveryMetadataFromLocalSources(metadataEntity);
            if (localMetadataSource) {
                return localMetadataSource;
            }
            // Fallback to network as metadata source
            const metadata = await invokeAsync(this.getCloudDiscoveryMetadataFromNetwork.bind(this), AuthorityGetCloudDiscoveryMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
            if (metadata) {
                updateCloudDiscoveryMetadata(metadataEntity, metadata, true);
                return AuthorityMetadataSource.NETWORK;
            }
            // Metadata could not be obtained from the config, cache, network or hardcoded values
            throw createClientConfigurationError(untrustedAuthority);
        }
        updateCloudDiscoveryMetadataFromLocalSources(metadataEntity) {
            this.logger.verbose("0jhlgt", this.correlationId);
            this.logger.verbosePii("1fy7uz", this.correlationId);
            this.logger.verbosePii("08zabj", this.correlationId);
            this.logger.verbosePii("1o1kv3", this.correlationId);
            const metadata = this.getCloudDiscoveryMetadataFromConfig();
            if (metadata) {
                this.logger.verbose("1nakio", this.correlationId);
                updateCloudDiscoveryMetadata(metadataEntity, metadata, false);
                return AuthorityMetadataSource.CONFIG;
            }
            // If the cached metadata came from config but that config was not passed to this instance, we must go to hardcoded values
            this.logger.verbose("1x74aj", this.correlationId);
            const hardcodedMetadata = getCloudDiscoveryMetadataFromHardcodedValues(this.hostnameAndPort);
            if (hardcodedMetadata) {
                this.logger.verbose("0by47c", this.correlationId);
                updateCloudDiscoveryMetadata(metadataEntity, hardcodedMetadata, false);
                return AuthorityMetadataSource.HARDCODED_VALUES;
            }
            this.logger.verbose("0r2fzy", this.correlationId);
            const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity);
            if (this.isAuthoritySameType(metadataEntity) &&
                metadataEntity.aliasesFromNetwork &&
                !metadataEntityExpired) {
                this.logger.verbose("1uffgh", "");
                // No need to update
                return AuthorityMetadataSource.CACHE;
            }
            else if (metadataEntityExpired) {
                this.logger.verbose("0uoibc", "");
            }
            return null;
        }
        /**
         * Parse cloudDiscoveryMetadata config or check knownAuthorities
         */
        getCloudDiscoveryMetadataFromConfig() {
            // CIAM does not support cloud discovery metadata
            if (this.authorityType === AuthorityType.Ciam) {
                this.logger.verbose("04y84h", this.correlationId);
                return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
            }
            // Check if network response was provided in config
            if (this.authorityOptions.cloudDiscoveryMetadata) {
                this.logger.verbose("0gszr3", this.correlationId);
                try {
                    this.logger.verbose("1iifkx", this.correlationId);
                    const parsedResponse = JSON.parse(this.authorityOptions.cloudDiscoveryMetadata);
                    const metadata = getCloudDiscoveryMetadataFromNetworkResponse(parsedResponse.metadata, this.hostnameAndPort);
                    this.logger.verbose("0q67e3", "");
                    if (metadata) {
                        this.logger.verbose("0hzfao", this.correlationId);
                        return metadata;
                    }
                    else {
                        this.logger.verbose("1ajz3u", this.correlationId);
                    }
                }
                catch (e) {
                    this.logger.verbose("1wq5tu", this.correlationId);
                    throw createClientConfigurationError(invalidCloudDiscoveryMetadata);
                }
            }
            // If cloudDiscoveryMetadata is empty or does not contain the host, check knownAuthorities
            if (this.isInKnownAuthorities()) {
                this.logger.verbose("0mt9al", this.correlationId);
                return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
            }
            return null;
        }
        /**
         * Called to get metadata from network if CloudDiscoveryMetadata was not populated by config
         *
         * @param hasHardcodedMetadata boolean
         */
        async getCloudDiscoveryMetadataFromNetwork() {
            const instanceDiscoveryEndpoint = `${AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`;
            const options = {};
            /*
             * TODO: Add a timeout if the authority exists in our library's
             * hardcoded list of metadata
             */
            let match = null;
            try {
                const response = await this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options);
                let typedResponseBody;
                let metadata;
                if (isCloudInstanceDiscoveryResponse(response.body)) {
                    typedResponseBody =
                        response.body;
                    metadata = typedResponseBody.metadata;
                    this.logger.verbosePii("1vglyt", this.correlationId);
                }
                else if (isCloudInstanceDiscoveryErrorResponse(response.body)) {
                    this.logger.warning("062uto", this.correlationId);
                    typedResponseBody =
                        response.body;
                    if (typedResponseBody.error === INVALID_INSTANCE) {
                        this.logger.error("1x90tm", this.correlationId);
                        return null;
                    }
                    this.logger.warning("0wchdm", this.correlationId);
                    this.logger.warning("1s5mpv", this.correlationId);
                    this.logger.warning("1yhqpw", this.correlationId);
                    metadata = [];
                }
                else {
                    this.logger.error("0768g0", this.correlationId);
                    return null;
                }
                this.logger.verbose("1lrobr", this.correlationId);
                match = getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort);
            }
            catch (error) {
                if (error instanceof AuthError) {
                    this.logger.error("0vwhc7", this.correlationId);
                }
                else {
                    this.logger.error("0s2z41", this.correlationId);
                }
                return null;
            }
            // Custom Domain scenario, host is trusted because Instance Discovery call succeeded
            if (!match) {
                this.logger.warning("0jp28q", this.correlationId);
                this.logger.verbose("130sd8", this.correlationId);
                match = Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
            }
            return match;
        }
        /**
         * Helper function to determine if this host is included in the knownAuthorities config option
         */
        isInKnownAuthorities() {
            const matches = this.authorityOptions.knownAuthorities.filter((authority) => {
                return (authority &&
                    UrlString.getDomainFromUrl(authority).toLowerCase() ===
                        this.hostnameAndPort);
            });
            return matches.length > 0;
        }
        /**
         * helper function to populate the authority based on azureCloudOptions
         * @param authorityString
         * @param azureCloudOptions
         */
        static generateAuthority(authorityString, azureCloudOptions) {
            let authorityAzureCloudInstance;
            if (azureCloudOptions &&
                azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) {
                const tenant = azureCloudOptions.tenant
                    ? azureCloudOptions.tenant
                    : DEFAULT_COMMON_TENANT;
                authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`;
            }
            return authorityAzureCloudInstance
                ? authorityAzureCloudInstance
                : authorityString;
        }
        /**
         * Creates cloud discovery metadata object from a given host
         * @param host
         */
        static createCloudDiscoveryMetadataFromHost(host) {
            return {
                preferred_network: host,
                preferred_cache: host,
                aliases: [host],
            };
        }
        /**
         * helper function to generate environment from authority object
         */
        getPreferredCache() {
            if (this.managedIdentity) {
                return DEFAULT_AUTHORITY_HOST;
            }
            else if (this.discoveryComplete()) {
                return this.metadata.preferred_cache;
            }
            else {
                throw createClientAuthError(endpointResolutionError);
            }
        }
        /**
         * Returns whether or not the provided host is an alias of this authority instance
         * @param host
         */
        isAlias(host) {
            return this.metadata.aliases.indexOf(host) > -1;
        }
        /**
         * Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery
         * @param host
         */
        isAliasOfKnownMicrosoftAuthority(host) {
            return InstanceDiscoveryMetadataAliases.has(host);
        }
        /**
         * Checks whether the provided host is that of a public cloud authority
         *
         * @param authority string
         * @returns bool
         */
        static isPublicCloudAuthority(host) {
            return KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0;
        }
        /**
         * Rebuild the authority string with the region
         *
         * @param host string
         * @param region string
         */
        static buildRegionalAuthorityString(host, region, queryString) {
            // Create and validate a Url string object with the initial authority string
            const authorityUrlInstance = new UrlString(host);
            authorityUrlInstance.validateAsUri();
            const authorityUrlParts = authorityUrlInstance.getUrlComponents();
            let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`;
            if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) {
                hostNameAndPort = `${region}.${REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`;
            }
            // Include the query string portion of the url
            const url = UrlString.constructAuthorityUriFromObject({
                ...authorityUrlInstance.getUrlComponents(),
                HostNameAndPort: hostNameAndPort,
            }).urlString;
            // Add the query string if a query string was provided
            if (queryString)
                return `${url}?${queryString}`;
            return url;
        }
        /**
         * Replace the endpoints in the metadata object with their regional equivalents.
         *
         * @param metadata OpenIdConfigResponse
         * @param azureRegion string
         */
        static replaceWithRegionalInformation(metadata, azureRegion) {
            const regionalMetadata = { ...metadata };
            regionalMetadata.authorization_endpoint =
                Authority.buildRegionalAuthorityString(regionalMetadata.authorization_endpoint, azureRegion);
            regionalMetadata.token_endpoint =
                Authority.buildRegionalAuthorityString(regionalMetadata.token_endpoint, azureRegion);
            if (regionalMetadata.end_session_endpoint) {
                regionalMetadata.end_session_endpoint =
                    Authority.buildRegionalAuthorityString(regionalMetadata.end_session_endpoint, azureRegion);
            }
            return regionalMetadata;
        }
        /**
         * Transform CIAM_AUTHORIY as per the below rules:
         * If no path segments found and it is a CIAM authority (hostname ends with .ciamlogin.com), then transform it
         *
         * NOTE: The transformation path should go away once STS supports CIAM with the format: `tenantIdorDomain.ciamlogin.com`
         * `ciamlogin.com` can also change in the future and we should accommodate the same
         *
         * @param authority
         */
        static transformCIAMAuthority(authority) {
            let ciamAuthority = authority;
            const authorityUrl = new UrlString(authority);
            const authorityUrlComponents = authorityUrl.getUrlComponents();
            // check if transformation is needed
            if (authorityUrlComponents.PathSegments.length === 0 &&
                authorityUrlComponents.HostNameAndPort.endsWith(CIAM_AUTH_URL)) {
                const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0];
                ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${AAD_TENANT_DOMAIN_SUFFIX}`;
            }
            return ciamAuthority;
        }
    }
    // Reserved tenant domain names that will not be replaced with tenant id
    Authority.reservedTenantDomains = new Set([
        "{tenant}",
        "{tenantid}",
        AADAuthority.COMMON,
        AADAuthority.CONSUMERS,
        AADAuthority.ORGANIZATIONS,
    ]);
    /**
     * Extract tenantId from authority
     */
    function getTenantFromAuthorityString(authority) {
        const authorityUrl = new UrlString(authority);
        const authorityUrlComponents = authorityUrl.getUrlComponents();
        /**
         * For credential matching purposes, tenantId is the last path segment of the authority URL:
         *  AAD Authority - domain/tenantId -> Credentials are cached with realm = tenantId
         *  B2C Authority - domain/{tenantId}?/.../policy -> Credentials are cached with realm = policy
         *  tenantId is downcased because B2C policies can have mixed case but tfp claim is downcased
         *
         * Note that we may not have any path segments in certain OIDC scenarios.
         */
        const tenantId = authorityUrlComponents.PathSegments.slice(-1)[0]?.toLowerCase();
        switch (tenantId) {
            case AADAuthority.COMMON:
            case AADAuthority.ORGANIZATIONS:
            case AADAuthority.CONSUMERS:
                return undefined;
            default:
                return tenantId;
        }
    }
    function formatAuthorityUri(authorityUri) {
        return authorityUri.endsWith(FORWARD_SLASH)
            ? authorityUri
            : `${authorityUri}${FORWARD_SLASH}`;
    }
    function buildStaticAuthorityOptions(authOptions) {
        const rawCloudDiscoveryMetadata = authOptions.cloudDiscoveryMetadata;
        let cloudDiscoveryMetadata = undefined;
        if (rawCloudDiscoveryMetadata) {
            try {
                cloudDiscoveryMetadata = JSON.parse(rawCloudDiscoveryMetadata);
            }
            catch (e) {
                throw createClientConfigurationError(invalidCloudDiscoveryMetadata);
            }
        }
        return {
            canonicalAuthority: authOptions.authority
                ? formatAuthorityUri(authOptions.authority)
                : undefined,
            knownAuthorities: authOptions.knownAuthorities,
            cloudDiscoveryMetadata: cloudDiscoveryMetadata,
        };
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Create an authority object of the correct type based on the url
     * Performs basic authority validation - checks to see if the authority is of a valid type (i.e. aad, b2c, adfs)
     *
     * Also performs endpoint discovery.
     *
     * @param authorityUri
     * @param networkClient
     * @param cacheManager
     * @param authorityOptions
     * @param logger
     * @param correlationId
     * @param performanceClient
     * @internal
     */
    async function createDiscoveredInstance(authorityUri, networkClient, cacheManager, authorityOptions, logger, correlationId, performanceClient) {
        const authorityUriFinal = Authority.transformCIAMAuthority(formatAuthorityUri(authorityUri));
        // Initialize authority and perform discovery endpoint check.
        const acquireTokenAuthority = new Authority(authorityUriFinal, networkClient, cacheManager, authorityOptions, logger, correlationId, performanceClient);
        try {
            await invokeAsync(acquireTokenAuthority.resolveEndpointsAsync.bind(acquireTokenAuthority), AuthorityResolveEndpointsAsync, logger, performanceClient, correlationId)();
            return acquireTokenAuthority;
        }
        catch (e) {
            throw createClientAuthError(endpointResolutionError);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Oauth2.0 Authorization Code client
     * @internal
     */
    class AuthorizationCodeClient {
        constructor(configuration, performanceClient) {
            // Flag to indicate if client is for hybrid spa auth code redemption
            this.includeRedirectUri = true;
            // Set the configuration
            this.config = buildClientConfiguration(configuration);
            // Initialize the logger
            this.logger = new Logger(this.config.loggerOptions, name$1, version$1);
            // Initialize crypto
            this.cryptoUtils = this.config.cryptoInterface;
            // Initialize storage interface
            this.cacheManager = this.config.storageInterface;
            // Set the network interface
            this.networkClient = this.config.networkInterface;
            // Set TelemetryManager
            this.serverTelemetryManager = this.config.serverTelemetryManager;
            // set Authority
            this.authority = this.config.authOptions.authority;
            // set performance telemetry client
            this.performanceClient = performanceClient;
            this.oidcDefaultScopes =
                this.config.authOptions.authority.options.OIDCOptions?.defaultScopes;
        }
        /**
         * API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the
         * authorization_code_grant
         * @param request
         */
        async acquireToken(request, apiId, authCodePayload) {
            if (!request.code) {
                throw createClientAuthError(requestCannotBeMade);
            }
            // Check for new cloud instance
            if (authCodePayload && authCodePayload.cloud_instance_host_name) {
                await invokeAsync(this.updateTokenEndpointAuthority.bind(this), UpdateTokenEndpointAuthority, this.logger, this.performanceClient, request.correlationId)(authCodePayload.cloud_instance_host_name, request.correlationId);
            }
            const reqTimestamp = nowSeconds();
            const response = await invokeAsync(this.executeTokenRequest.bind(this), AuthClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(this.authority, request, this.serverTelemetryManager);
            // Retrieve requestId from response headers
            const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
            const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
            // Validate response. This function throws a server error if an error is returned by the server.
            responseHandler.validateTokenResponse(response.body, request.correlationId);
            return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, apiId, authCodePayload, undefined, undefined, undefined, requestId);
        }
        /**
         * Used to log out the current user, and redirect the user to the postLogoutRedirectUri.
         * Default behaviour is to redirect the user to `window.location.href`.
         * @param authorityUri
         */
        getLogoutUri(logoutRequest) {
            // Throw error if logoutRequest is null/undefined
            if (!logoutRequest) {
                throw createClientConfigurationError(logoutRequestEmpty);
            }
            const queryString = this.createLogoutUrlQueryString(logoutRequest);
            // Construct logout URI
            return UrlString.appendQueryString(this.authority.endSessionEndpoint, queryString);
        }
        /**
         * Executes POST request to token endpoint
         * @param authority
         * @param request
         */
        async executeTokenRequest(authority, request, serverTelemetryManager) {
            const queryParametersString = createTokenQueryParameters(request, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);
            const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
            const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), AuthClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);
            let ccsCredential = undefined;
            if (request.clientInfo) {
                try {
                    const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode);
                    ccsCredential = {
                        credential: `${clientInfo.uid}${CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
                        type: CcsCredentialType.HOME_ACCOUNT_ID,
                    };
                }
                catch (e) {
                    this.logger.verbose("0wznt3", request.correlationId);
                }
            }
            const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, ccsCredential || request.ccsCredential);
            const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request);
            return invokeAsync(executePostToTokenEndpoint, AuthorizationCodeClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, serverTelemetryManager);
        }
        /**
         * Generates a map for all the params to be sent to the service
         * @param request
         */
        async createTokenRequestBody(request) {
            const parameters = new Map();
            addClientId(parameters, request.embeddedClientId ||
                request.extraParameters?.[CLIENT_ID] ||
                this.config.authOptions.clientId);
            /*
             * For hybrid spa flow, there will be a code but no verifier
             * In this scenario, don't include redirect uri as auth code will not be bound to redirect URI
             */
            if (!this.includeRedirectUri) {
                // Just validate
                if (!request.redirectUri) {
                    throw createClientConfigurationError(redirectUriEmpty);
                }
            }
            else {
                // Validate and include redirect uri
                addRedirectUri(parameters, request.redirectUri);
            }
            // Add scope array, parameter builder will add default scopes and dedupe
            addScopes(parameters, request.scopes, true, this.oidcDefaultScopes);
            addResource(parameters, request.resource);
            // add code: user set, not validated
            addAuthorizationCode(parameters, request.code);
            // Add library metadata
            addLibraryInfo(parameters, this.config.libraryInfo);
            addApplicationTelemetry(parameters, this.config.telemetry.application);
            addThrottling(parameters);
            if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {
                addServerTelemetry(parameters, this.serverTelemetryManager);
            }
            // add code_verifier if passed
            if (request.codeVerifier) {
                addCodeVerifier(parameters, request.codeVerifier);
            }
            if (this.config.clientCredentials.clientSecret) {
                addClientSecret(parameters, this.config.clientCredentials.clientSecret);
            }
            if (this.config.clientCredentials.clientAssertion) {
                const clientAssertion = this.config.clientCredentials.clientAssertion;
                addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
                addClientAssertionType(parameters, clientAssertion.assertionType);
            }
            addGrantType(parameters, GrantType.AUTHORIZATION_CODE_GRANT);
            addClientInfo(parameters);
            if (request.authenticationScheme === AuthenticationScheme$1.POP) {
                const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
                let reqCnfData;
                if (!request.popKid) {
                    const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);
                    reqCnfData = generatedReqCnfData.reqCnfString;
                }
                else {
                    reqCnfData = this.cryptoUtils.encodeKid(request.popKid);
                }
                // SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
                addPopToken(parameters, reqCnfData);
            }
            else if (request.authenticationScheme === AuthenticationScheme$1.SSH) {
                if (request.sshJwk) {
                    addSshJwk(parameters, request.sshJwk);
                }
                else {
                    throw createClientConfigurationError(missingSshJwk);
                }
            }
            let ccsCred = undefined;
            if (request.clientInfo) {
                try {
                    const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode);
                    ccsCred = {
                        credential: `${clientInfo.uid}${CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
                        type: CcsCredentialType.HOME_ACCOUNT_ID,
                    };
                }
                catch (e) {
                    this.logger.verbose("0wznt3", request.correlationId);
                }
            }
            else {
                ccsCred = request.ccsCredential;
            }
            // Adds these as parameters in the request instead of headers to prevent CORS preflight request
            if (this.config.systemOptions.preventCorsPreflight && ccsCred) {
                switch (ccsCred.type) {
                    case CcsCredentialType.HOME_ACCOUNT_ID:
                        try {
                            const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
                            addCcsOid(parameters, clientInfo);
                        }
                        catch (e) {
                            this.logger.verbose("1qhtee", request.correlationId);
                        }
                        break;
                    case CcsCredentialType.UPN:
                        addCcsUpn(parameters, ccsCred.credential);
                        break;
                }
            }
            if (request.embeddedClientId) {
                addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri);
            }
            if (request.extraParameters) {
                addExtraParameters(parameters, request.extraParameters);
            }
            // Add hybrid spa parameters if not already provided
            if (request.enableSpaAuthorizationCode &&
                (!request.extraParameters ||
                    !request.extraParameters[RETURN_SPA_CODE])) {
                addExtraParameters(parameters, {
                    [RETURN_SPA_CODE]: "1",
                });
            }
            instrumentBrokerParams(parameters, request.correlationId, this.performanceClient);
            addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities, request.skipBrokerClaims);
            return mapToQueryString(parameters);
        }
        /**
         * This API validates the `EndSessionRequest` and creates a URL
         * @param request
         */
        createLogoutUrlQueryString(request) {
            const parameters = new Map();
            if (request.postLogoutRedirectUri) {
                addPostLogoutRedirectUri(parameters, request.postLogoutRedirectUri);
            }
            if (request.correlationId) {
                addCorrelationId(parameters, request.correlationId);
            }
            if (request.idTokenHint) {
                addIdTokenHint(parameters, request.idTokenHint);
            }
            if (request.state) {
                addState(parameters, request.state);
            }
            if (request.logoutHint) {
                addLogoutHint(parameters, request.logoutHint);
            }
            if (request.extraQueryParameters) {
                addExtraParameters(parameters, request.extraQueryParameters);
            }
            if (this.config.authOptions.instanceAware) {
                addInstanceAware(parameters);
            }
            return mapToQueryString(parameters);
        }
        /**
         * Updates the authority to the cloud instance provided in the authorization response
         * @param cloudInstanceHostName - cloud instance host name from authorization code payload
         * @param correlationId - request correlation id
         */
        async updateTokenEndpointAuthority(cloudInstanceHostName, correlationId) {
            const cloudInstanceAuthorityUri = `https://${cloudInstanceHostName}/${this.authority.tenant}/`;
            const cloudInstanceAuthority = await createDiscoveredInstance(cloudInstanceAuthorityUri, this.networkClient, this.cacheManager, this.authority.options, this.logger, correlationId, this.performanceClient);
            this.authority = cloudInstanceAuthority;
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS = 300; // 5 Minutes
    /**
     * OAuth2.0 refresh token client
     * @internal
     */
    class RefreshTokenClient {
        constructor(configuration, performanceClient) {
            // Set the configuration
            this.config = buildClientConfiguration(configuration);
            // Initialize the logger
            this.logger = new Logger(this.config.loggerOptions, name$1, version$1);
            // Initialize crypto
            this.cryptoUtils = this.config.cryptoInterface;
            // Initialize storage interface
            this.cacheManager = this.config.storageInterface;
            // Set the network interface
            this.networkClient = this.config.networkInterface;
            // Set TelemetryManager
            this.serverTelemetryManager = this.config.serverTelemetryManager;
            // set Authority
            this.authority = this.config.authOptions.authority;
            // set performance telemetry client
            this.performanceClient = performanceClient;
        }
        async acquireToken(request, apiId) {
            const reqTimestamp = nowSeconds();
            const response = await invokeAsync(this.executeTokenRequest.bind(this), RefreshTokenClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(request, this.authority);
            // Retrieve requestId from response headers
            const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
            const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
            responseHandler.validateTokenResponse(response.body, request.correlationId);
            return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, apiId, undefined, undefined, true, request.forceCache, requestId);
        }
        /**
         * Gets cached refresh token and attaches to request, then calls acquireToken API
         * @param request
         */
        async acquireTokenByRefreshToken(request, apiId) {
            // Cannot renew token if no request object is given.
            if (!request) {
                throw createClientConfigurationError(tokenRequestEmpty);
            }
            // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
            if (!request.account) {
                throw createClientAuthError(noAccountInSilentRequest);
            }
            // try checking if FOCI is enabled for the given application
            const isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment, request.correlationId);
            // if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest
            if (isFOCI) {
                try {
                    return await invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, true, apiId);
                }
                catch (e) {
                    const noFamilyRTInCache = e instanceof InteractionRequiredAuthError &&
                        e.errorCode ===
                            noTokensFound;
                    const clientMismatchErrorWithFamilyRT = e instanceof ServerError &&
                        e.errorCode === INVALID_GRANT_ERROR &&
                        e.subError === CLIENT_MISMATCH_ERROR;
                    // if family Refresh Token (FRT) cache acquisition fails or if client_mismatch error is seen with FRT, reattempt with application Refresh Token (ART)
                    if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) {
                        return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false, apiId);
                        // throw in all other cases
                    }
                    else {
                        throw e;
                    }
                }
            }
            // fall back to application refresh token acquisition
            return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false, apiId);
        }
        /**
         * makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached
         * @param request
         */
        async acquireTokenWithCachedRefreshToken(request, foci, apiId) {
            // fetches family RT or application RT based on FOCI value
            const refreshToken = invoke(this.cacheManager.getRefreshToken.bind(this.cacheManager), CacheManagerGetRefreshToken, this.logger, this.performanceClient, request.correlationId)(request.account, foci, request.correlationId, undefined);
            if (!refreshToken) {
                throw createInteractionRequiredAuthError(noTokensFound);
            }
            if (refreshToken.expiresOn) {
                const offset = request.refreshTokenExpirationOffsetSeconds ||
                    DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS;
                this.performanceClient?.addFields({
                    cacheRtExpiresOnSeconds: Number(refreshToken.expiresOn),
                    rtOffsetSeconds: offset,
                }, request.correlationId);
                if (isTokenExpired(refreshToken.expiresOn, offset)) {
                    throw createInteractionRequiredAuthError(refreshTokenExpired);
                }
            }
            // attach cached RT size to the current measurement
            const refreshTokenRequest = {
                ...request,
                refreshToken: refreshToken.secret,
                authenticationScheme: request.authenticationScheme ||
                    AuthenticationScheme$1.BEARER,
                ccsCredential: {
                    credential: request.account.homeAccountId,
                    type: CcsCredentialType.HOME_ACCOUNT_ID,
                },
            };
            try {
                return await invokeAsync(this.acquireToken.bind(this), RefreshTokenClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(refreshTokenRequest, apiId);
            }
            catch (e) {
                if (e instanceof InteractionRequiredAuthError) {
                    if (e.subError === badToken) {
                        // Remove bad refresh token from cache
                        this.logger.verbose("1pg3ap", request.correlationId);
                        const badRefreshTokenKey = this.cacheManager.generateCredentialKey(refreshToken);
                        this.cacheManager.removeRefreshToken(badRefreshTokenKey, request.correlationId);
                    }
                }
                throw e;
            }
        }
        /**
         * Constructs the network message and makes a NW call to the underlying secure token service
         * @param request
         * @param authority
         */
        async executeTokenRequest(request, authority) {
            const queryParametersString = createTokenQueryParameters(request, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);
            const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
            const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), RefreshTokenClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);
            const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, request.ccsCredential);
            const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request);
            return invokeAsync(executePostToTokenEndpoint, RefreshTokenClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, this.serverTelemetryManager);
        }
        /**
         * Helper function to create the token request body
         * @param request
         */
        async createTokenRequestBody(request) {
            const parameters = new Map();
            addClientId(parameters, request.embeddedClientId ||
                request.extraParameters?.[CLIENT_ID] ||
                this.config.authOptions.clientId);
            if (request.redirectUri) {
                addRedirectUri(parameters, request.redirectUri);
            }
            addScopes(parameters, request.scopes, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes);
            addGrantType(parameters, GrantType.REFRESH_TOKEN_GRANT);
            addClientInfo(parameters);
            addLibraryInfo(parameters, this.config.libraryInfo);
            addApplicationTelemetry(parameters, this.config.telemetry.application);
            addThrottling(parameters);
            if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {
                addServerTelemetry(parameters, this.serverTelemetryManager);
            }
            addRefreshToken(parameters, request.refreshToken);
            if (this.config.clientCredentials.clientSecret) {
                addClientSecret(parameters, this.config.clientCredentials.clientSecret);
            }
            if (this.config.clientCredentials.clientAssertion) {
                const clientAssertion = this.config.clientCredentials.clientAssertion;
                addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
                addClientAssertionType(parameters, clientAssertion.assertionType);
            }
            if (request.authenticationScheme === AuthenticationScheme$1.POP) {
                const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
                let reqCnfData;
                if (!request.popKid) {
                    const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);
                    reqCnfData = generatedReqCnfData.reqCnfString;
                }
                else {
                    reqCnfData = this.cryptoUtils.encodeKid(request.popKid);
                }
                // SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
                addPopToken(parameters, reqCnfData);
            }
            else if (request.authenticationScheme === AuthenticationScheme$1.SSH) {
                if (request.sshJwk) {
                    addSshJwk(parameters, request.sshJwk);
                }
                else {
                    throw createClientConfigurationError(missingSshJwk);
                }
            }
            if (this.config.systemOptions.preventCorsPreflight &&
                request.ccsCredential) {
                switch (request.ccsCredential.type) {
                    case CcsCredentialType.HOME_ACCOUNT_ID:
                        try {
                            const clientInfo = buildClientInfoFromHomeAccountId(request.ccsCredential.credential);
                            addCcsOid(parameters, clientInfo);
                        }
                        catch (e) {
                            this.logger.verbose("1qhtee", request.correlationId);
                        }
                        break;
                    case CcsCredentialType.UPN:
                        addCcsUpn(parameters, request.ccsCredential.credential);
                        break;
                }
            }
            if (request.embeddedClientId) {
                addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri);
            }
            if (request.extraParameters) {
                addExtraParameters(parameters, {
                    ...request.extraParameters,
                });
            }
            instrumentBrokerParams(parameters, request.correlationId, this.performanceClient);
            addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities, request.skipBrokerClaims);
            return mapToQueryString(parameters);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /** @internal */
    class SilentFlowClient {
        constructor(configuration, performanceClient) {
            // Set the configuration
            this.config = buildClientConfiguration(configuration);
            // Initialize the logger
            this.logger = new Logger(this.config.loggerOptions, name$1, version$1);
            // Initialize crypto
            this.cryptoUtils = this.config.cryptoInterface;
            // Initialize storage interface
            this.cacheManager = this.config.storageInterface;
            // Set the network interface
            this.networkClient = this.config.networkInterface;
            // Set TelemetryManager
            this.serverTelemetryManager = this.config.serverTelemetryManager;
            // set Authority
            this.authority = this.config.authOptions.authority;
            // set performance telemetry client
            this.performanceClient = performanceClient;
        }
        /**
         * Retrieves token from cache or throws an error if it must be refreshed.
         * @param request
         */
        async acquireCachedToken(request) {
            let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE;
            if (request.forceRefresh || !StringUtils.isEmptyObj(request.claims)) {
                // Must refresh due to present force_refresh flag.
                this.setCacheOutcome(CacheOutcome.FORCE_REFRESH_OR_CLAIMS, request.correlationId);
                throw createClientAuthError(tokenRefreshRequired);
            }
            // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
            if (!request.account) {
                throw createClientAuthError(noAccountInSilentRequest);
            }
            const requestTenantId = request.account.tenantId ||
                getTenantFromAuthorityString(request.authority);
            const tokenKeys = this.cacheManager.getTokenKeys();
            const cachedAccessToken = this.cacheManager.getAccessToken(request.account, request, tokenKeys, requestTenantId);
            if (!cachedAccessToken) {
                // must refresh due to non-existent access_token
                this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId);
                throw createClientAuthError(tokenRefreshRequired);
            }
            else if (wasClockTurnedBack(cachedAccessToken.cachedAt) ||
                isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
                // must refresh due to the expires_in value
                this.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED, request.correlationId);
                throw createClientAuthError(tokenRefreshRequired);
            }
            else if (request.resource) {
                // cached access token must have a resource that matches the request resource for MCP scenarios
                if (cachedAccessToken.resource !== request.resource) {
                    this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId);
                    throw createClientAuthError(tokenRefreshRequired);
                }
            }
            else if (cachedAccessToken.refreshOn &&
                isTokenExpired(cachedAccessToken.refreshOn, 0)) {
                // must refresh (in the background) due to the refresh_in value
                lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;
                // don't throw ClientAuthError.createRefreshRequiredError(), return cached token instead
            }
            const environment = request.authority || this.authority.getPreferredCache();
            const cacheRecord = {
                account: this.cacheManager.getAccount(this.cacheManager.generateAccountKey(request.account), request.correlationId),
                accessToken: cachedAccessToken,
                idToken: this.cacheManager.getIdToken(request.account, request.correlationId, tokenKeys, requestTenantId),
                refreshToken: null,
                appMetadata: this.cacheManager.readAppMetadataFromCache(environment, request.correlationId),
            };
            this.setCacheOutcome(lastCacheOutcome, request.correlationId);
            if (this.config.serverTelemetryManager) {
                this.config.serverTelemetryManager.incrementCacheHits();
            }
            return [
                await invokeAsync(this.generateResultFromCacheRecord.bind(this), SilentFlowClientGenerateResultFromCacheRecord, this.logger, this.performanceClient, request.correlationId)(cacheRecord, request),
                lastCacheOutcome,
            ];
        }
        setCacheOutcome(cacheOutcome, correlationId) {
            this.serverTelemetryManager?.setCacheOutcome(cacheOutcome);
            this.performanceClient?.addFields({
                cacheOutcome: cacheOutcome,
            }, correlationId);
            if (cacheOutcome !== CacheOutcome.NOT_APPLICABLE) {
                this.logger.info("09ingz", correlationId);
            }
        }
        /**
         * Helper function to build response object from the CacheRecord
         * @param cacheRecord
         */
        async generateResultFromCacheRecord(cacheRecord, request) {
            let idTokenClaims;
            if (cacheRecord.idToken) {
                idTokenClaims = extractTokenClaims(cacheRecord.idToken.secret, this.config.cryptoInterface.base64Decode);
            }
            // token max_age check
            if (request.maxAge || request.maxAge === 0) {
                const authTime = idTokenClaims?.auth_time;
                if (!authTime) {
                    throw createClientAuthError(authTimeNotFound);
                }
                checkMaxAge(authTime, request.maxAge);
            }
            return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, this.performanceClient, idTokenClaims);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const StubbedNetworkModule = {
        sendGetRequestAsync: () => {
            return Promise.reject(createClientAuthError(methodNotImplemented));
        },
        sendPostRequestAsync: () => {
            return Promise.reject(createClientAuthError(methodNotImplemented));
        },
    };
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Returns map of parameters that are applicable to all calls to /authorize whether using PKCE or EAR
     * @param config
     * @param request
     * @param logger
     * @param performanceClient
     * @returns
     */
    function getStandardAuthorizeRequestParameters(authOptions, request, logger, performanceClient) {
        // generate the correlationId if not set by the user and add
        const correlationId = request.correlationId;
        const parameters = new Map();
        addClientId(parameters, request.embeddedClientId ||
            request.extraQueryParameters?.[CLIENT_ID] ||
            authOptions.clientId);
        const requestScopes = [
            ...(request.scopes || []),
            ...(request.extraScopesToConsent || []),
        ];
        addScopes(parameters, requestScopes, true, authOptions.authority.options.OIDCOptions?.defaultScopes);
        addResource(parameters, request.resource);
        addRedirectUri(parameters, request.redirectUri);
        addCorrelationId(parameters, correlationId);
        // add response_mode. If not passed in it defaults to query.
        addResponseMode(parameters, request.responseMode);
        // add client_info=1
        addClientInfo(parameters);
        // add clidata=1
        addCliData(parameters);
        if (request.prompt) {
            addPrompt(parameters, request.prompt);
            performanceClient?.addFields({ prompt: request.prompt }, correlationId);
        }
        if (request.domainHint) {
            addDomainHint(parameters, request.domainHint);
            performanceClient?.addFields({ domainHintFromRequest: true }, correlationId);
        }
        // Add sid or loginHint with preference for login_hint claim (in request) -> sid -> loginHint (upn/email) -> username of AccountInfo object
        if (request.prompt !== PromptValue$1.SELECT_ACCOUNT) {
            // AAD will throw if prompt=select_account is passed with an account hint
            if (request.sid && request.prompt === PromptValue$1.NONE) {
                // SessionID is only used in silent calls
                logger.verbose("1tvqyx", request.correlationId);
                addSid(parameters, request.sid);
                performanceClient?.addFields({ sidFromRequest: true }, correlationId);
            }
            else if (request.account) {
                const accountSid = extractAccountSid(request.account);
                let accountLoginHintClaim = extractLoginHint(request.account);
                if (accountLoginHintClaim && request.domainHint) {
                    logger.warning("0wkg3v", request.correlationId);
                    accountLoginHintClaim = null;
                }
                // If login_hint claim is present, use it over sid/username
                if (accountLoginHintClaim) {
                    logger.verbose("1eyfsw", request.correlationId);
                    addLoginHint(parameters, accountLoginHintClaim);
                    performanceClient?.addFields({ loginHintFromClaim: true }, correlationId);
                    try {
                        const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
                        addCcsOid(parameters, clientInfo);
                    }
                    catch (e) {
                        logger.verbose("12ugck", request.correlationId);
                    }
                }
                else if (accountSid && request.prompt === PromptValue$1.NONE) {
                    /*
                     * If account and loginHint are provided, we will check account first for sid before adding loginHint
                     * SessionId is only used in silent calls
                     */
                    logger.verbose("1rmd8s", request.correlationId);
                    addSid(parameters, accountSid);
                    performanceClient?.addFields({ sidFromClaim: true }, correlationId);
                    try {
                        const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
                        addCcsOid(parameters, clientInfo);
                    }
                    catch (e) {
                        logger.verbose("12ugck", request.correlationId);
                    }
                }
                else if (request.loginHint) {
                    logger.verbose("0y3007", request.correlationId);
                    addLoginHint(parameters, request.loginHint);
                    addCcsUpn(parameters, request.loginHint);
                    performanceClient?.addFields({ loginHintFromRequest: true }, correlationId);
                }
                else if (request.account.username) {
                    // Fallback to account username if provided
                    logger.verbose("02f507", request.correlationId);
                    addLoginHint(parameters, request.account.username);
                    performanceClient?.addFields({ loginHintFromUpn: true }, correlationId);
                    try {
                        const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
                        addCcsOid(parameters, clientInfo);
                    }
                    catch (e) {
                        logger.verbose("12ugck", request.correlationId);
                    }
                }
            }
            else if (request.loginHint) {
                logger.verbose("0g01ey", request.correlationId);
                addLoginHint(parameters, request.loginHint);
                addCcsUpn(parameters, request.loginHint);
                performanceClient?.addFields({ loginHintFromRequest: true }, correlationId);
            }
        }
        else {
            logger.verbose("169k9v", request.correlationId);
        }
        if (request.nonce) {
            addNonce(parameters, request.nonce);
        }
        if (request.state) {
            addState(parameters, request.state);
        }
        if (request.embeddedClientId) {
            addBrokerParameters(parameters, authOptions.clientId, authOptions.redirectUri);
        }
        addClaims(parameters, request.claims, authOptions.clientCapabilities, request.skipBrokerClaims);
        // If extraQueryParameters includes instance_aware its value will be added when extraQueryParameters are added
        if (authOptions.instanceAware &&
            (!request.extraQueryParameters ||
                !Object.keys(request.extraQueryParameters).includes(INSTANCE_AWARE))) {
            addInstanceAware(parameters);
        }
        return parameters;
    }
    /**
     * Returns authorize endpoint with given request parameters in the query string
     * @param authority
     * @param requestParameters
     * @returns
     */
    function getAuthorizeUrl(authority, requestParameters) {
        const queryString = mapToQueryString(requestParameters);
        return UrlString.appendQueryString(authority.authorizationEndpoint, queryString);
    }
    /**
     * Handles the hash fragment response from public client code request. Returns a code response used by
     * the client to exchange for a token in acquireToken.
     * @param serverParams
     * @param cachedState
     */
    function getAuthorizationCodePayload(serverParams, cachedState) {
        // Get code response
        validateAuthorizationResponse(serverParams, cachedState);
        // throw when there is no auth code in the response
        if (!serverParams.code) {
            throw createClientAuthError(authorizationCodeMissingFromServerResponse);
        }
        return serverParams;
    }
    /**
     * Function which validates server authorization code response.
     * @param serverResponseHash
     * @param requestState
     */
    function validateAuthorizationResponse(serverResponse, requestState) {
        if (!serverResponse.state || !requestState) {
            throw serverResponse.state
                ? createClientAuthError(stateNotFound, "Cached State")
                : createClientAuthError(stateNotFound, "Server State");
        }
        let decodedServerResponseState;
        let decodedRequestState;
        try {
            decodedServerResponseState = decodeURIComponent(serverResponse.state);
        }
        catch (e) {
            throw createClientAuthError(invalidState, serverResponse.state);
        }
        try {
            decodedRequestState = decodeURIComponent(requestState);
        }
        catch (e) {
            throw createClientAuthError(invalidState, serverResponse.state);
        }
        if (decodedServerResponseState !== decodedRequestState) {
            throw createClientAuthError(stateMismatch);
        }
        // Check for error
        if (serverResponse.error ||
            serverResponse.error_description ||
            serverResponse.suberror) {
            const serverErrorNo = parseServerErrorNo(serverResponse);
            if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {
                throw new InteractionRequiredAuthError(serverResponse.error || "", serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.correlation_id || "", serverResponse.claims || "", serverErrorNo);
            }
            throw new ServerError(serverResponse.error || "", serverResponse.error_description, serverResponse.suberror, serverErrorNo);
        }
    }
    /**
     * Get server error No from the error_uri
     * @param serverResponse
     * @returns
     */
    function parseServerErrorNo(serverResponse) {
        const errorCodePrefix = "code=";
        const errorCodePrefixIndex = serverResponse.error_uri?.lastIndexOf(errorCodePrefix);
        return errorCodePrefixIndex && errorCodePrefixIndex >= 0
            ? serverResponse.error_uri?.substring(errorCodePrefixIndex + errorCodePrefix.length)
            : undefined;
    }
    /**
     * Helper to get sid from account. Returns null if idTokenClaims are not present or sid is not present.
     * @param account
     */
    function extractAccountSid(account) {
        return account.idTokenClaims?.sid || null;
    }
    function extractLoginHint(account) {
        return account.loginHint || account.idTokenClaims?.login_hint || null;
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Helper to enforce resource parameter presence in token requests when isMcp is set in the configuration.
     * If resource parameter is set in both the request and in extraQueryParameters or extraParameters, an error will be thrown.
     * This is used for MCP flows.
     * @param isMcp - Flag indicating if application is an MCP app, from configuration
     * @param request - Auth request
     */
    function enforceResourceParameter(isMcp, request) {
        if (!isMcp) {
            return;
        }
        if (request.resource &&
            (containsResourceParam(request.extraParameters) ||
                containsResourceParam(request.extraQueryParameters))) {
            throw createClientAuthError(misplacedResourceParam);
        }
        if (!request.resource) {
            throw createClientAuthError(resourceParameterRequired);
        }
    }
    function containsResourceParam(params) {
        if (!params) {
            return false;
        }
        return Object.prototype.hasOwnProperty.call(params, "resource");
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This is a helper class that parses supported HTTP response authentication headers to extract and return
     * header challenge values that can be used outside the basic authorization flows.
     */
    class AuthenticationHeaderParser {
        constructor(headers) {
            this.headers = headers;
        }
        /**
         * This method parses the SHR nonce value out of either the Authentication-Info or WWW-Authenticate authentication headers.
         * @returns
         */
        getShrNonce() {
            // Attempt to parse nonce from Authentiacation-Info
            const authenticationInfo = this.headers[HeaderNames.AuthenticationInfo];
            if (authenticationInfo) {
                const authenticationInfoChallenges = this.parseChallenges(authenticationInfo);
                if (authenticationInfoChallenges.nextnonce) {
                    return authenticationInfoChallenges.nextnonce;
                }
                throw createClientConfigurationError(invalidAuthenticationHeader);
            }
            // Attempt to parse nonce from WWW-Authenticate
            const wwwAuthenticate = this.headers[HeaderNames.WWWAuthenticate];
            if (wwwAuthenticate) {
                const wwwAuthenticateChallenges = this.parseChallenges(wwwAuthenticate);
                if (wwwAuthenticateChallenges.nonce) {
                    return wwwAuthenticateChallenges.nonce;
                }
                throw createClientConfigurationError(invalidAuthenticationHeader);
            }
            // If neither header is present, throw missing headers error
            throw createClientConfigurationError(missingNonceAuthenticationHeader);
        }
        /**
         * Parses an HTTP header's challenge set into a key/value map.
         * @param header
         * @returns
         */
        parseChallenges(header) {
            const schemeSeparator = header.indexOf(" ");
            const challenges = header.substr(schemeSeparator + 1).split(",");
            const challengeMap = {};
            challenges.forEach((challenge) => {
                const [key, value] = challenge.split("=");
                // Remove escaped quotation marks (', ") from challenge string to keep only the challenge value
                challengeMap[key] = unescape(value.replace(/['"]+/g, ""));
            });
            return challengeMap;
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * AuthErrorMessage class containing string constants used by error codes and messages.
     */
    const unexpectedError = "unexpected_error";
    const postRequestFailed$1 = "post_request_failed";
 
    var AuthErrorCodes = /*#__PURE__*/Object.freeze({
        __proto__: null,
        postRequestFailed: postRequestFailed$1,
        unexpectedError: unexpectedError
    });
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const skuGroupSeparator = ",";
    const skuValueSeparator = "|";
    function makeExtraSkuString(params) {
        const { skus, libraryName, libraryVersion, extensionName, extensionVersion, } = params;
        const skuMap = new Map([
            [0, [libraryName, libraryVersion]],
            [2, [extensionName, extensionVersion]],
        ]);
        let skuArr = [];
        if (skus?.length) {
            skuArr = skus.split(skuGroupSeparator);
            // Ignore invalid input sku param
            if (skuArr.length < 4) {
                return skus;
            }
        }
        else {
            skuArr = Array.from({ length: 4 }, () => skuValueSeparator);
        }
        skuMap.forEach((value, key) => {
            if (value.length === 2 && value[0]?.length && value[1]?.length) {
                setSku({
                    skuArr,
                    index: key,
                    skuName: value[0],
                    skuVersion: value[1],
                });
            }
        });
        return skuArr.join(skuGroupSeparator);
    }
    function setSku(params) {
        const { skuArr, index, skuName, skuVersion } = params;
        if (index >= skuArr.length) {
            return;
        }
        skuArr[index] = [skuName, skuVersion].join(skuValueSeparator);
    }
    /** @internal */
    class ServerTelemetryManager {
        constructor(telemetryRequest, cacheManager) {
            this.cacheOutcome = CacheOutcome.NOT_APPLICABLE;
            this.cacheManager = cacheManager;
            this.apiId = telemetryRequest.apiId;
            this.correlationId = telemetryRequest.correlationId;
            this.wrapperSKU = telemetryRequest.wrapperSKU || "";
            this.wrapperVer = telemetryRequest.wrapperVer || "";
            this.telemetryCacheKey =
                SERVER_TELEM_CACHE_KEY +
                    CACHE_KEY_SEPARATOR$1 +
                    telemetryRequest.clientId;
        }
        /**
         * API to add MSER Telemetry to request
         */
        generateCurrentRequestHeaderValue() {
            const request = `${this.apiId}${SERVER_TELEM_VALUE_SEPARATOR}${this.cacheOutcome}`;
            const platformFieldsArr = [this.wrapperSKU, this.wrapperVer];
            const nativeBrokerErrorCode = this.getNativeBrokerErrorCode();
            if (nativeBrokerErrorCode?.length) {
                platformFieldsArr.push(`broker_error=${nativeBrokerErrorCode}`);
            }
            const platformFields = platformFieldsArr.join(SERVER_TELEM_VALUE_SEPARATOR);
            const regionDiscoveryFields = this.getRegionDiscoveryFields();
            const requestWithRegionDiscoveryFields = [
                request,
                regionDiscoveryFields,
            ].join(SERVER_TELEM_VALUE_SEPARATOR);
            return [
                SERVER_TELEM_SCHEMA_VERSION,
                requestWithRegionDiscoveryFields,
                platformFields,
            ].join(SERVER_TELEM_CATEGORY_SEPARATOR);
        }
        /**
         * API to add MSER Telemetry for the last failed request
         */
        generateLastRequestHeaderValue() {
            const lastRequests = this.getLastRequests();
            const maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests);
            const failedRequests = lastRequests.failedRequests
                .slice(0, 2 * maxErrors)
                .join(SERVER_TELEM_VALUE_SEPARATOR);
            const errors = lastRequests.errors
                .slice(0, maxErrors)
                .join(SERVER_TELEM_VALUE_SEPARATOR);
            const errorCount = lastRequests.errors.length;
            // Indicate whether this header contains all data or partial data
            const overflow = maxErrors < errorCount
                ? SERVER_TELEM_OVERFLOW_TRUE
                : SERVER_TELEM_OVERFLOW_FALSE;
            const platformFields = [errorCount, overflow].join(SERVER_TELEM_VALUE_SEPARATOR);
            return [
                SERVER_TELEM_SCHEMA_VERSION,
                lastRequests.cacheHits,
                failedRequests,
                errors,
                platformFields,
            ].join(SERVER_TELEM_CATEGORY_SEPARATOR);
        }
        /**
         * API to cache token failures for MSER data capture
         * @param error
         */
        cacheFailedRequest(error) {
            const lastRequests = this.getLastRequests();
            if (lastRequests.errors.length >=
                SERVER_TELEM_MAX_CACHED_ERRORS) {
                // Remove a cached error to make room, first in first out
                lastRequests.failedRequests.shift(); // apiId
                lastRequests.failedRequests.shift(); // correlationId
                lastRequests.errors.shift();
            }
            lastRequests.failedRequests.push(this.apiId, this.correlationId);
            if (error instanceof Error && !!error && error.toString()) {
                if (error instanceof AuthError) {
                    if (error.subError) {
                        lastRequests.errors.push(error.subError);
                    }
                    else if (error.errorCode) {
                        lastRequests.errors.push(error.errorCode);
                    }
                    else {
                        lastRequests.errors.push(error.toString());
                    }
                }
                else {
                    lastRequests.errors.push(error.toString());
                }
            }
            else {
                lastRequests.errors.push(SERVER_TELEM_UNKNOWN_ERROR);
            }
            this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
            return;
        }
        /**
         * Update server telemetry cache entry by incrementing cache hit counter
         */
        incrementCacheHits() {
            const lastRequests = this.getLastRequests();
            lastRequests.cacheHits += 1;
            this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
            return lastRequests.cacheHits;
        }
        /**
         * Get the server telemetry entity from cache or initialize a new one
         */
        getLastRequests() {
            const initialValue = {
                failedRequests: [],
                errors: [],
                cacheHits: 0,
            };
            const lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey, this.correlationId);
            return lastRequests || initialValue;
        }
        /**
         * Remove server telemetry cache entry
         */
        clearTelemetryCache() {
            const lastRequests = this.getLastRequests();
            const numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests);
            const errorCount = lastRequests.errors.length;
            if (numErrorsFlushed === errorCount) {
                // All errors were sent on last request, clear Telemetry cache
                this.cacheManager.removeItem(this.telemetryCacheKey, this.correlationId);
            }
            else {
                // Partial data was flushed to server, construct a new telemetry cache item with errors that were not flushed
                const serverTelemEntity = {
                    failedRequests: lastRequests.failedRequests.slice(numErrorsFlushed * 2),
                    errors: lastRequests.errors.slice(numErrorsFlushed),
                    cacheHits: 0,
                };
                this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity, this.correlationId);
            }
        }
        /**
         * Returns the maximum number of errors that can be flushed to the server in the next network request
         * @param serverTelemetryEntity
         */
        static maxErrorsToSend(serverTelemetryEntity) {
            let i;
            let maxErrors = 0;
            let dataSize = 0;
            const errorCount = serverTelemetryEntity.errors.length;
            for (i = 0; i < errorCount; i++) {
                // failedRequests parameter contains pairs of apiId and correlationId, multiply index by 2 to preserve pairs
                const apiId = serverTelemetryEntity.failedRequests[2 * i] || "";
                const correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] || "";
                const errorCode = serverTelemetryEntity.errors[i] || "";
                // Count number of characters that would be added to header, each character is 1 byte. Add 3 at the end to account for separators
                dataSize +=
                    apiId.toString().length +
                        correlationId.toString().length +
                        errorCode.length +
                        3;
                if (dataSize < SERVER_TELEM_MAX_LAST_HEADER_BYTES) {
                    // Adding this entry to the header would still keep header size below the limit
                    maxErrors += 1;
                }
                else {
                    break;
                }
            }
            return maxErrors;
        }
        /**
         * Get the region discovery fields
         *
         * @returns string
         */
        getRegionDiscoveryFields() {
            const regionDiscoveryFields = [];
            regionDiscoveryFields.push(this.regionUsed || "");
            regionDiscoveryFields.push(this.regionSource || "");
            regionDiscoveryFields.push(this.regionOutcome || "");
            return regionDiscoveryFields.join(",");
        }
        /**
         * Update the region discovery metadata
         *
         * @param regionDiscoveryMetadata
         * @returns void
         */
        updateRegionDiscoveryMetadata(regionDiscoveryMetadata) {
            this.regionUsed = regionDiscoveryMetadata.region_used;
            this.regionSource = regionDiscoveryMetadata.region_source;
            this.regionOutcome = regionDiscoveryMetadata.region_outcome;
        }
        /**
         * Set cache outcome
         */
        setCacheOutcome(cacheOutcome) {
            this.cacheOutcome = cacheOutcome;
        }
        setNativeBrokerErrorCode(errorCode) {
            const lastRequests = this.getLastRequests();
            lastRequests.nativeBrokerErrorCode = errorCode;
            this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
        }
        getNativeBrokerErrorCode() {
            return this.getLastRequests().nativeBrokerErrorCode;
        }
        clearNativeBrokerErrorCode() {
            const lastRequests = this.getLastRequests();
            delete lastRequests.nativeBrokerErrorCode;
            this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
        }
        static makeExtraSkuString(params) {
            return makeExtraSkuString(params);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Error thrown when there is an error in the client code running on the browser.
     */
    class JoseHeaderError extends AuthError {
        constructor(errorCode, errorMessage) {
            super(errorCode, errorMessage);
            this.name = "JoseHeaderError";
            Object.setPrototypeOf(this, JoseHeaderError.prototype);
        }
    }
    /** Returns JoseHeaderError object */
    function createJoseHeaderError(code) {
        return new JoseHeaderError(code);
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const missingKidError = "missing_kid_error";
    const missingAlgError = "missing_alg_error";
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /** @internal */
    class JoseHeader {
        constructor(options) {
            this.typ = options.typ;
            this.alg = options.alg;
            this.kid = options.kid;
        }
        /**
         * Builds SignedHttpRequest formatted JOSE Header from the
         * JOSE Header options provided or previously set on the object and returns
         * the stringified header object.
         * Throws if keyId or algorithm aren't provided since they are required for Access Token Binding.
         * @param shrHeaderOptions
         * @returns
         */
        static getShrHeaderString(shrHeaderOptions) {
            // KeyID is required on the SHR header
            if (!shrHeaderOptions.kid) {
                throw createJoseHeaderError(missingKidError);
            }
            // Alg is required on the SHR header
            if (!shrHeaderOptions.alg) {
                throw createJoseHeaderError(missingAlgError);
            }
            const shrHeader = new JoseHeader({
                // Access Token PoP headers must have type pop, but the type header can be overriden for special cases
                typ: shrHeaderOptions.typ || JsonWebTokenTypes$1.Pop,
                kid: shrHeaderOptions.kid,
                alg: shrHeaderOptions.alg,
            });
            return JSON.stringify(shrHeader);
        }
    }
 
    /*! @azure/msal-common v16.5.0 2026-04-16 */
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Starts context by adding payload to the stack
     * @param event {PerformanceEvent}
     * @param stack {?PerformanceEventStackedContext[]} stack
     */
    function startContext(event, stack) {
        if (!stack) {
            return;
        }
        stack.push({
            name: event.name,
        });
    }
    /**
     * Ends context by removing payload from the stack and returning parent or self, if stack is empty, payload
     *
     * @param event {PerformanceEvent}
     * @param stack {?PerformanceEventStackedContext[]} stack
     * @param error {?unknown} error
     */
    function endContext(event, stack, error) {
        if (!stack?.length) {
            return;
        }
        const peek = (stack) => {
            return stack.length ? stack[stack.length - 1] : undefined;
        };
        const abbrEventName = event.name;
        const top = peek(stack);
        if (top?.name !== abbrEventName) {
            return;
        }
        const current = stack?.pop();
        if (!current) {
            return;
        }
        const errorCode = error instanceof AuthError
            ? error.errorCode
            : error instanceof Error
                ? error.name
                : undefined;
        const subErr = error instanceof AuthError ? error.subError : undefined;
        if (errorCode && current.childErr !== errorCode) {
            current.err = errorCode;
            if (subErr) {
                current.subErr = subErr;
            }
        }
        delete current.name;
        delete current.childErr;
        const context = {
            ...current,
            dur: event.durationMs,
        };
        if (!event.success) {
            context.fail = 1;
        }
        const parent = peek(stack);
        if (!parent) {
            return { [abbrEventName]: context };
        }
        if (errorCode) {
            parent.childErr = errorCode;
        }
        let childName;
        if (!parent[abbrEventName]) {
            childName = abbrEventName;
        }
        else {
            const siblings = Object.keys(parent).filter((key) => key.startsWith(abbrEventName)).length;
            childName = `${abbrEventName}_${siblings + 1}`;
        }
        parent[childName] = context;
        return parent;
    }
    /**
     * Adds error name and stack trace to the telemetry event
     * @param error {Error}
     * @param logger {Logger}
     * @param event {PerformanceEvent}
     * @param stackMaxSize {number} max error stack size to capture
     */
    function addError(error, logger, event, stackMaxSize = 5) {
        if (!(error instanceof Error)) {
            logger.trace("0gcyox", event.correlationId);
            return;
        }
        else if (error instanceof AuthError) {
            event.errorCode = error.errorCode;
            event.subErrorCode = error.subError;
            if (!event.serverErrorNo &&
                (error instanceof ServerError ||
                    error instanceof InteractionRequiredAuthError) &&
                error.errorNo) {
                event.serverErrorNo = error.errorNo;
            }
            return;
        }
        else if (error instanceof CacheError) {
            event.errorCode = error.errorCode;
            return;
        }
        else if (event.errorStack?.length) {
            logger.trace("0lmqrh", event.correlationId);
            return;
        }
        else if (!error.stack?.length) {
            logger.trace("1cnpwa", event.correlationId);
            return;
        }
        if (error.stack) {
            event.errorStack = compactStack(error.stack, stackMaxSize);
        }
        event.errorName = error.name;
    }
    /**
     * Compacts error stack into array by fetching N first entries
     * @param stack {string} error stack
     * @param stackMaxSize {number} max error stack size to capture
     * @returns {string[]}
     */
    function compactStack(stack, stackMaxSize) {
        if (stackMaxSize < 0) {
            return [];
        }
        const stackArr = stack.split("\n") || [];
        const res = [];
        // Check for a handful of known, common runtime errors and log them (with redaction where applicable).
        const firstLine = stackArr[0];
        if (firstLine.startsWith("TypeError: Cannot read property") ||
            firstLine.startsWith("TypeError: Cannot read properties of") ||
            firstLine.startsWith("TypeError: Cannot set property") ||
            firstLine.startsWith("TypeError: Cannot set properties of") ||
            firstLine.endsWith("is not a function")) {
            // These types of errors are not at risk of leaking PII. They will indicate unavailable APIs
            res.push(compactStackLine(firstLine));
        }
        else if (firstLine.startsWith("SyntaxError") ||
            firstLine.startsWith("TypeError")) {
            // Prevent unintentional leaking of arbitrary info by redacting contents between both single and double quotes
            res.push(compactStackLine(
            // Example: SyntaxError: Unexpected token 'e', "test" is not valid JSON -> SyntaxError: Unexpected token <redacted>, <redacted> is not valid JSON
            firstLine.replace(/['].*[']|["].*["]/g, "<redacted>")));
        }
        // Get top N stack lines
        for (let ix = 1; ix < stackArr.length; ix++) {
            if (res.length >= stackMaxSize) {
                break;
            }
            const line = stackArr[ix];
            res.push(compactStackLine(line));
        }
        return res;
    }
    /**
     * Compacts error stack line by shortening file path
     * Example: https://localhost/msal-common/src/authority/Authority.js:100:1 -> Authority.js:100:1
     * @param line {string} stack line
     * @returns {string}
     */
    function compactStackLine(line) {
        const filePathIx = line.lastIndexOf(" ") + 1;
        if (filePathIx < 1) {
            return line;
        }
        const filePath = line.substring(filePathIx);
        let fileNameIx = filePath.lastIndexOf("/");
        fileNameIx = fileNameIx < 0 ? filePath.lastIndexOf("\\") : fileNameIx;
        if (fileNameIx >= 0) {
            return (line.substring(0, filePathIx) +
                "(" +
                filePath.substring(fileNameIx + 1) +
                (filePath.charAt(filePath.length - 1) === ")" ? "" : ")")).trimStart();
        }
        return line.trimStart();
    }
    function getAccountType(account) {
        const idTokenClaims = account?.idTokenClaims;
        if (idTokenClaims?.tfp || idTokenClaims?.acr) {
            return "B2C";
        }
        if (!idTokenClaims?.tid) {
            return undefined;
        }
        else if (idTokenClaims?.tid === "9188040d-6c67-4c5b-b112-36a304b66dad") {
            return "MSA";
        }
        return "AAD";
    }
    class PerformanceClient {
        /**
         * Creates an instance of PerformanceClient,
         * an abstract class containing core performance telemetry logic.
         *
         * @constructor
         * @param {string} clientId Client ID of the application
         * @param {string} authority Authority used by the application
         * @param {Logger} logger Logger used by the application
         * @param {string} libraryName Name of the library
         * @param {string} libraryVersion Version of the library
         * @param {ApplicationTelemetry} applicationTelemetry application name and version
         * @param {Set<String>} intFields integer fields to be truncated
         */
        constructor(clientId, authority, logger, libraryName, libraryVersion, applicationTelemetry, intFields) {
            this.authority = authority;
            this.libraryName = libraryName;
            this.libraryVersion = libraryVersion;
            this.applicationTelemetry = applicationTelemetry;
            this.clientId = clientId;
            this.logger = logger;
            this.callbacks = new Map();
            this.eventsByCorrelationId = new Map();
            this.eventStack = new Map();
            this.intFields = intFields || new Set();
            for (const item of IntFields) {
                this.intFields.add(item);
            }
        }
        /**
         * Starts measuring performance for a given operation. Returns a function that should be used to end the measurement.
         *
         * @param {PerformanceEvents} measureName
         * @param {?string} [correlationId]
         * @returns {InProgressPerformanceEvent}
         */
        startMeasurement(measureName, correlationId) {
            // Generate a placeholder correlation if the request does not provide one
            const eventCorrelationId = correlationId || this.generateId();
            const inProgressEvent = {
                eventId: this.generateId(),
                status: PerformanceEventStatus.InProgress,
                authority: this.authority,
                libraryName: this.libraryName,
                libraryVersion: this.libraryVersion,
                clientId: this.clientId,
                name: measureName,
                startTimeMs: Date.now(),
                correlationId: eventCorrelationId,
                appName: this.applicationTelemetry?.appName,
                appVersion: this.applicationTelemetry?.appVersion,
            };
            // Store in progress events so they can be discarded if not ended properly
            this.cacheEventByCorrelationId(inProgressEvent);
            startContext(inProgressEvent, this.eventStack.get(eventCorrelationId));
            // Return the event and functions the caller can use to properly end/flush the measurement
            return {
                end: (event, error, account) => {
                    return this.endMeasurement({
                        // Initial set of event properties
                        ...inProgressEvent,
                        // Properties set when event ends
                        ...event,
                    }, error, account);
                },
                discard: () => {
                    return this.discardMeasurements(inProgressEvent.correlationId);
                },
                add: (fields) => {
                    return this.addFields(fields, inProgressEvent.correlationId);
                },
                increment: (fields) => {
                    return this.incrementFields(fields, inProgressEvent.correlationId);
                },
                event: inProgressEvent,
            };
        }
        /**
         * Stops measuring the performance for an operation. Should only be called directly by PerformanceClient classes,
         * as consumers should instead use the function returned by startMeasurement.
         * Adds a new field named as "[event name]DurationMs" for sub-measurements, completes and emits an event
         * otherwise.
         *
         * @param {PerformanceEvent} event
         * @param {unknown} error
         * @param {AccountInfo?} account
         * @returns {(PerformanceEvent | null)}
         */
        endMeasurement(event, error, account) {
            const rootEvent = this.eventsByCorrelationId.get(event.correlationId);
            if (!rootEvent) {
                this.logger.trace("0k9ti8", event.correlationId);
                return null;
            }
            const isRoot = event.eventId === rootEvent.eventId;
            event.durationMs = Math.round(event.durationMs || this.getDurationMs(event.startTimeMs));
            const context = JSON.stringify(endContext(event, this.eventStack.get(rootEvent.correlationId), error));
            if (isRoot) {
                this.discardMeasurements(rootEvent.correlationId);
            }
            else {
                rootEvent.incompleteSubMeasurements?.delete(event.eventId);
            }
            if (error) {
                addError(error, this.logger, rootEvent);
            }
            // Add sub-measurement attribute to root event's ext field.
            if (!isRoot) {
                rootEvent.ext = {
                    ...rootEvent.ext,
                    ...event.ext,
                };
                rootEvent.ext[event.name + "DurationMs"] = Math.floor(event.durationMs);
                return { ...rootEvent };
            }
            if (isRoot &&
                !error &&
                (rootEvent.errorCode || rootEvent.subErrorCode)) {
                this.logger.trace("1fm1tm", event.correlationId);
                rootEvent.errorCode = undefined;
                rootEvent.subErrorCode = undefined;
            }
            let finalEvent = { ...rootEvent, ...event };
            let incompleteSubsCount = 0;
            // Incomplete sub-measurements are discarded. They are likely an instrumentation bug that should be fixed.
            finalEvent.incompleteSubMeasurements?.forEach((subMeasurement) => {
                this.logger.trace("0nxk52", finalEvent.correlationId);
                incompleteSubsCount++;
            });
            finalEvent.incompleteSubMeasurements = undefined;
            const logs = getAndFlushLogsFromCache(event.correlationId);
            // Format logs: [millis1,hash1;millis2,hash2;...]
            const formattedLogs = logs
                .map((logMessage) => `${logMessage.milliseconds},${logMessage.hash}`)
                .join(";");
            finalEvent = {
                ...finalEvent,
                status: PerformanceEventStatus.Completed,
                incompleteSubsCount,
                context,
                logs: formattedLogs,
            };
            if (account) {
                finalEvent.accountType = getAccountType(account);
                finalEvent.dataBoundary = account.dataBoundary;
            }
            this.truncateIntegralFields(finalEvent);
            this.emitEvents([finalEvent], event.correlationId);
            return finalEvent;
        }
        /**
         * Saves extra information to be emitted when the measurements are flushed
         * @param fields
         * @param correlationId
         */
        addFields(fields, correlationId) {
            const event = this.eventsByCorrelationId.get(correlationId);
            if (event) {
                const staticFields = {};
                const dynamicFields = {};
                for (const key in fields) {
                    if (key.startsWith(EXT_FIELD_PREFIX)) {
                        const dynamicKey = key.slice(EXT_FIELD_PREFIX.length);
                        const value = fields[key];
                        if (typeof value === "string" ||
                            typeof value === "number") {
                            dynamicFields[dynamicKey] = value;
                        }
                    }
                    else {
                        staticFields[key] = fields[key];
                    }
                }
                const updatedEvent = {
                    ...event,
                    ...staticFields,
                };
                if (Object.keys(dynamicFields).length) {
                    updatedEvent.ext = {
                        ...updatedEvent.ext,
                        ...dynamicFields,
                    };
                }
                this.eventsByCorrelationId.set(correlationId, updatedEvent);
            }
            else {
                this.logger.trace("0thl6s", correlationId);
            }
        }
        /**
         * Increment counters to be emitted when the measurements are flushed
         * @param fields {string[]}
         * @param correlationId {string} correlation identifier
         */
        incrementFields(fields, correlationId) {
            const event = this.eventsByCorrelationId.get(correlationId);
            if (event) {
                for (const counter in fields) {
                    if (counter.startsWith(EXT_FIELD_PREFIX)) {
                        event.ext = event.ext || {};
                        // Route to ext sub-object
                        const dynamicKey = counter.slice(EXT_FIELD_PREFIX.length);
                        const currentValue = event.ext[dynamicKey];
                        if (currentValue === undefined) {
                            event.ext[dynamicKey] = 0;
                        }
                        else if (isNaN(Number(currentValue))) {
                            return;
                        }
                        event.ext[dynamicKey] =
                            (Number(event.ext[dynamicKey]) || 0) +
                                (fields[counter] ?? 0);
                    }
                    else {
                        /* eslint-disable custom-msal/no-dynamic-telemetry-fields -- internal dispatching of static fields by name */
                        if (!event.hasOwnProperty(counter)) {
                            event[counter] = 0;
                        }
                        else if (isNaN(Number(event[counter]))) {
                            return;
                        }
                        event[counter] += fields[counter];
                        /* eslint-enable custom-msal/no-dynamic-telemetry-fields */
                    }
                }
            }
            else {
                this.logger.trace("0thl6s", correlationId);
            }
        }
        /**
         * Upserts event into event cache.
         * First key is the correlation id, second key is the event id.
         * Allows for events to be grouped by correlation id,
         * and to easily allow for properties on them to be updated.
         *
         * @private
         * @param {PerformanceEvent} event
         */
        cacheEventByCorrelationId(event) {
            const rootEvent = this.eventsByCorrelationId.get(event.correlationId);
            if (rootEvent) {
                rootEvent.incompleteSubMeasurements =
                    rootEvent.incompleteSubMeasurements || new Map();
                rootEvent.incompleteSubMeasurements.set(event.eventId, {
                    name: event.name,
                    startTimeMs: event.startTimeMs,
                });
            }
            else {
                this.eventsByCorrelationId.set(event.correlationId, { ...event });
                this.eventStack.set(event.correlationId, []);
            }
        }
        /**
         * Removes measurements and aux data for a given correlation id.
         *
         * @param {string} correlationId
         */
        discardMeasurements(correlationId) {
            this.eventsByCorrelationId.delete(correlationId);
            this.eventStack.delete(correlationId);
        }
        /**
         * Registers a callback function to receive performance events.
         *
         * @param {PerformanceCallbackFunction} callback
         * @returns {string}
         */
        addPerformanceCallback(callback) {
            for (const [id, cb] of this.callbacks) {
                if (cb.toString() === callback.toString()) {
                    this.logger.warning("1eap5p", "");
                    return id;
                }
            }
            const callbackId = this.generateId();
            this.callbacks.set(callbackId, callback);
            this.logger.verbose("0c9ujz", "");
            return callbackId;
        }
        /**
         * Removes a callback registered with addPerformanceCallback.
         *
         * @param {string} callbackId
         * @returns {boolean}
         */
        removePerformanceCallback(callbackId) {
            const result = this.callbacks.delete(callbackId);
            if (result) {
                this.logger.verbose("0253if", "");
            }
            else {
                this.logger.verbose("0iqk07", "");
            }
            return result;
        }
        /**
         * Emits events to all registered callbacks.
         *
         * @param {PerformanceEvent[]} events
         * @param {?string} [correlationId]
         */
        emitEvents(events, correlationId) {
            this.logger.verbose("11jb1y", correlationId);
            this.callbacks.forEach((callback, callbackId) => {
                this.logger.trace("0p2pjl", correlationId);
                callback.apply(null, [events]);
            });
        }
        /**
         * Enforce truncation of integral fields in performance event.
         * @param {PerformanceEvent} event performance event to update.
         */
        truncateIntegralFields(event) {
            this.intFields.forEach((key) => {
                /* eslint-disable custom-msal/no-dynamic-telemetry-fields -- internal truncation of known integer fields */
                if (key in event && typeof event[key] === "number") {
                    event[key] = Math.floor(event[key]);
                }
                /* eslint-enable custom-msal/no-dynamic-telemetry-fields */
            });
        }
        /**
         * Returns event duration in milliseconds
         * @param startTimeMs {number}
         * @returns {number}
         */
        getDurationMs(startTimeMs) {
            const durationMs = Date.now() - startTimeMs;
            // Handle clock skew
            return durationMs < 0 ? durationMs : 0;
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * acquireTokenFromCache (msal-browser).
     * Internal API for acquiring token from cache
     */
    const AcquireTokenFromCache = "acquireTokenFromCache";
    /**
     * acquireTokenByRefreshToken API (msal-browser and msal-node).
     * Used to renew an access token using a refresh token against the token endpoint.
     */
    const AcquireTokenByRefreshToken = "acquireTokenByRefreshToken";
    /**
     * acquireTokenSilentAsync (msal-browser).
     * Internal API for acquireTokenSilent.
     */
    const AcquireTokenSilentAsync = "acquireTokenSilentAsync";
    /**
     * getPublicKeyThumbprint API in CryptoOpts class (msal-browser).
     * Used to generate a public/private keypair and generate a public key thumbprint for pop requests.
     */
    const CryptoOptsGetPublicKeyThumbprint = "cryptoOptsGetPublicKeyThumbprint";
    /**
     * signJwt API in CryptoOpts class (msal-browser).
     * Used to signed a pop token.
     */
    const CryptoOptsSignJwt = "cryptoOptsSignJwt";
    /**
     * acquireToken API in the SilentCacheClient class (msal-browser).
     * Used to read access tokens from the cache.
     */
    const SilentCacheClientAcquireToken = "silentCacheClientAcquireToken";
    /**
     * acquireToken API in the SilentIframeClient class (msal-browser).
     * Used to acquire a new set of tokens from the authorize endpoint in a hidden iframe.
     */
    const SilentIframeClientAcquireToken = "silentIframeClientAcquireToken";
    const AwaitConcurrentIframe = "awaitConcurrentIframe"; // Time spent waiting for a concurrent iframe to complete
    /**
     * acquireToken API in SilentRereshClient (msal-browser).
     * Used to acquire a new set of tokens from the token endpoint using a refresh token.
     */
    const SilentRefreshClientAcquireToken = "silentRefreshClientAcquireToken";
    /**
     * getDiscoveredAuthority API in StandardInteractionClient class (msal-browser).
     * Used to load authority metadata for a request.
     */
    const StandardInteractionClientGetDiscoveredAuthority = "standardInteractionClientGetDiscoveredAuthority";
    /**
     * acquireToken API in NativeInteractionClient class (msal-browser).
     * Used to acquire a token from Native component when native brokering is enabled.
     */
    const NativeInteractionClientAcquireToken = "nativeInteractionClientAcquireToken";
    const NativeInteractionClientAcquireTokenRedirect = "nativeInteractionClientAcquireToken";
    /**
     * acquireTokenByRefreshToken API in RefreshTokenClient (msal-common).
     */
    const RefreshTokenClientAcquireTokenByRefreshToken = "refreshTokenClientAcquireTokenByRefreshToken";
    /**
     * acquireTokenBySilentIframe (msal-browser).
     * Internal API for acquiring token by silent Iframe
     */
    const AcquireTokenBySilentIframe = "acquireTokenBySilentIframe";
    /**
     * Internal API for initializing base request in BaseInteractionClient (msal-browser)
     */
    const InitializeBaseRequest = "initializeBaseRequest";
    /**
     * Internal API for initializing silent request in SilentCacheClient (msal-browser)
     */
    const InitializeSilentRequest = "initializeSilentRequest";
    const InitializeCache = "initializeCache";
    /**
     * Helper function in SilentIframeClient class (msal-browser).
     */
    const SilentIframeClientTokenHelper = "silentIframeClientTokenHelper";
    /**
     * SilentHandler
     */
    const SilentHandlerInitiateAuthRequest = "silentHandlerInitiateAuthRequest";
    const SilentHandlerMonitorIframeForHash = "silentHandlerMonitorIframeForHash";
    const SilentHandlerLoadFrameSync = "silentHandlerLoadFrameSync";
    /**
     * Helper functions in StandardInteractionClient class (msal-browser)
     */
    const StandardInteractionClientCreateAuthCodeClient = "standardInteractionClientCreateAuthCodeClient";
    const StandardInteractionClientGetClientConfiguration = "standardInteractionClientGetClientConfiguration";
    const StandardInteractionClientInitializeAuthorizationRequest = "standardInteractionClientInitializeAuthorizationRequest";
    const SilentFlowClientAcquireCachedToken = "silentFlowClientAcquireCachedToken";
    const GetStandardParams = "getStandardParams";
    const HandleCodeResponse = "handleCodeResponse";
    const HandleResponseEar = "handleResponseEar";
    const HandleResponsePlatformBroker = "handleResponsePlatformBroker";
    const HandleResponseCode = "handleResponseCode";
    const AuthClientAcquireToken = "authClientAcquireToken";
    const DeserializeResponse = "deserializeResponse";
    const AuthorityFactoryCreateDiscoveredInstance = "authorityFactoryCreateDiscoveredInstance";
    const AcquireTokenByCodeAsync = "acquireTokenByCodeAsync";
    const HandleRedirectPromiseMeasurement = "handleRedirectPromise";
    const HandleNativeRedirectPromiseMeasurement = "handleNativeRedirectPromise";
    const NativeMessageHandlerHandshake = "nativeMessageHandlerHandshake";
    const RemoveHiddenIframe = "removeHiddenIframe";
    const ImportExistingCache = "importExistingCache";
    /**
     * Crypto Operations
     */
    const GeneratePkceCodes = "generatePkceCodes";
    const GenerateCodeVerifier = "generateCodeVerifier";
    const GenerateCodeChallengeFromVerifier = "generateCodeChallengeFromVerifier";
    const Sha256Digest = "sha256Digest";
    const GetRandomValues = "getRandomValues";
    const GenerateHKDF = "generateHKDF";
    const GenerateBaseKey = "generateBaseKey";
    const Base64Decode = "base64Decode";
    const UrlEncodeArr = "urlEncodeArr";
    const Encrypt = "encrypt";
    const Decrypt = "decrypt";
    const GenerateEarKey = "generateEarKey";
    const DecryptEarResponse = "decryptEarResponse";
    const LoadAccount = "loadAccount";
    const LoadIdToken = "loadIdToken";
    const LoadAccessToken = "loadAccessToken";
    const LoadRefreshToken = "loadRefreshToken";
    /**
     * Background telemetry measurement that tracks whether a late bridge response
     * arrives after the iframe timeout has already fired.
     */
    const WaitForBridgeLateResponse$1 = "waitForBridgeLateResponse";
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const pkceNotCreated = "pkce_not_created";
    const earJwkEmpty = "ear_jwk_empty";
    const earJweEmpty = "ear_jwe_empty";
    const cryptoNonExistent = "crypto_nonexistent";
    const emptyNavigateUri = "empty_navigate_uri";
    const hashEmptyError = "hash_empty_error";
    const noStateInHash = "no_state_in_hash";
    const hashDoesNotContainKnownProperties = "hash_does_not_contain_known_properties";
    const unableToParseState = "unable_to_parse_state";
    const stateInteractionTypeMismatch = "state_interaction_type_mismatch";
    const interactionInProgress = "interaction_in_progress";
    const interactionInProgressCancelled = "interaction_in_progress_cancelled";
    const popupWindowError = "popup_window_error";
    const emptyWindowError = "empty_window_error";
    const userCancelled = "user_cancelled";
    const redirectBridgeEmptyResponse = "redirect_bridge_empty_response";
    const redirectInIframe = "redirect_in_iframe";
    const blockIframeReload = "block_iframe_reload";
    const blockNestedPopups = "block_nested_popups";
    const iframeClosedPrematurely = "iframe_closed_prematurely";
    const silentLogoutUnsupported = "silent_logout_unsupported";
    const noAccountError = "no_account_error";
    const silentPromptValueError = "silent_prompt_value_error";
    const noTokenRequestCacheError = "no_token_request_cache_error";
    const unableToParseTokenRequestCacheError = "unable_to_parse_token_request_cache_error";
    const authRequestNotSetError = "auth_request_not_set_error";
    const invalidCacheType = "invalid_cache_type";
    const nonBrowserEnvironment = "non_browser_environment";
    const databaseNotOpen = "database_not_open";
    const noNetworkConnectivity = "no_network_connectivity";
    const postRequestFailed = "post_request_failed";
    const getRequestFailed = "get_request_failed";
    const failedToParseResponse = "failed_to_parse_response";
    const unableToLoadToken = "unable_to_load_token";
    const cryptoKeyNotFound = "crypto_key_not_found";
    const authCodeRequired = "auth_code_required";
    const authCodeOrNativeAccountIdRequired = "auth_code_or_nativeAccountId_required";
    const spaCodeAndNativeAccountIdPresent = "spa_code_and_nativeAccountId_present";
    const databaseUnavailable = "database_unavailable";
    const unableToAcquireTokenFromNativePlatform = "unable_to_acquire_token_from_native_platform";
    const nativeHandshakeTimeout = "native_handshake_timeout";
    const nativeExtensionNotInstalled = "native_extension_not_installed";
    const nativeConnectionNotEstablished = "native_connection_not_established";
    const uninitializedPublicClientApplication = "uninitialized_public_client_application";
    const nativePromptNotSupported = "native_prompt_not_supported";
    const invalidBase64String = "invalid_base64_string";
    const invalidPopTokenRequest = "invalid_pop_token_request";
    const failedToBuildHeaders = "failed_to_build_headers";
    const failedToParseHeaders = "failed_to_parse_headers";
    const failedToDecryptEarResponse = "failed_to_decrypt_ear_response";
    const timedOut = "timed_out";
    const emptyResponse = "empty_response";
 
    var BrowserAuthErrorCodes = /*#__PURE__*/Object.freeze({
        __proto__: null,
        authCodeOrNativeAccountIdRequired: authCodeOrNativeAccountIdRequired,
        authCodeRequired: authCodeRequired,
        authRequestNotSetError: authRequestNotSetError,
        blockIframeReload: blockIframeReload,
        blockNestedPopups: blockNestedPopups,
        cryptoKeyNotFound: cryptoKeyNotFound,
        cryptoNonExistent: cryptoNonExistent,
        databaseNotOpen: databaseNotOpen,
        databaseUnavailable: databaseUnavailable,
        earJweEmpty: earJweEmpty,
        earJwkEmpty: earJwkEmpty,
        emptyNavigateUri: emptyNavigateUri,
        emptyResponse: emptyResponse,
        emptyWindowError: emptyWindowError,
        failedToBuildHeaders: failedToBuildHeaders,
        failedToDecryptEarResponse: failedToDecryptEarResponse,
        failedToParseHeaders: failedToParseHeaders,
        failedToParseResponse: failedToParseResponse,
        getRequestFailed: getRequestFailed,
        hashDoesNotContainKnownProperties: hashDoesNotContainKnownProperties,
        hashEmptyError: hashEmptyError,
        iframeClosedPrematurely: iframeClosedPrematurely,
        interactionInProgress: interactionInProgress,
        interactionInProgressCancelled: interactionInProgressCancelled,
        invalidBase64String: invalidBase64String,
        invalidCacheType: invalidCacheType,
        invalidPopTokenRequest: invalidPopTokenRequest,
        nativeConnectionNotEstablished: nativeConnectionNotEstablished,
        nativeExtensionNotInstalled: nativeExtensionNotInstalled,
        nativeHandshakeTimeout: nativeHandshakeTimeout,
        nativePromptNotSupported: nativePromptNotSupported,
        noAccountError: noAccountError,
        noNetworkConnectivity: noNetworkConnectivity,
        noStateInHash: noStateInHash,
        noTokenRequestCacheError: noTokenRequestCacheError,
        nonBrowserEnvironment: nonBrowserEnvironment,
        pkceNotCreated: pkceNotCreated,
        popupWindowError: popupWindowError,
        postRequestFailed: postRequestFailed,
        redirectBridgeEmptyResponse: redirectBridgeEmptyResponse,
        redirectInIframe: redirectInIframe,
        silentLogoutUnsupported: silentLogoutUnsupported,
        silentPromptValueError: silentPromptValueError,
        spaCodeAndNativeAccountIdPresent: spaCodeAndNativeAccountIdPresent,
        stateInteractionTypeMismatch: stateInteractionTypeMismatch,
        timedOut: timedOut,
        unableToAcquireTokenFromNativePlatform: unableToAcquireTokenFromNativePlatform,
        unableToLoadToken: unableToLoadToken,
        unableToParseState: unableToParseState,
        unableToParseTokenRequestCacheError: unableToParseTokenRequestCacheError,
        uninitializedPublicClientApplication: uninitializedPublicClientApplication,
        userCancelled: userCancelled
    });
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function getDefaultErrorMessage(code) {
        return `See https://aka.ms/msal.js.errors#${code} for details`;
    }
    /**
     * Browser library error class thrown by the MSAL.js library for SPAs
     */
    class BrowserAuthError extends AuthError {
        constructor(errorCode, subError) {
            super(errorCode, getDefaultErrorMessage(errorCode), subError);
            Object.setPrototypeOf(this, BrowserAuthError.prototype);
            this.name = "BrowserAuthError";
        }
    }
    function createBrowserAuthError(errorCode, subError) {
        return new BrowserAuthError(errorCode, subError);
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Constants
     */
    const BrowserConstants = {
        /**
         * Invalid grant error code
         */
        INVALID_GRANT_ERROR: "invalid_grant",
        /**
         * Default popup window width
         */
        POPUP_WIDTH: 483,
        /**
         * Default popup window height
         */
        POPUP_HEIGHT: 600,
        /**
         * Name of the popup window starts with
         */
        POPUP_NAME_PREFIX: "msal",
        /**
         * Msal-browser SKU
         */
        MSAL_SKU: "msal.js.browser",
    };
    const PlatformAuthConstants = {
        CHANNEL_ID: "53ee284d-920a-4b59-9d30-a60315b26836",
        PREFERRED_EXTENSION_ID: "ppnbnpeolgkicgegkbkbjmhlideopiji",
        MATS_TELEMETRY: "MATS",
        MICROSOFT_ENTRA_BROKERID: "MicrosoftEntra",
        DOM_API_NAME: "DOM API",
        PLATFORM_DOM_APIS: "get-token-and-sign-out",
        PLATFORM_DOM_PROVIDER: "PlatformAuthDOMHandler",
        PLATFORM_EXTENSION_PROVIDER: "PlatformAuthExtensionHandler",
    };
    const NativeExtensionMethod = {
        HandshakeRequest: "Handshake",
        HandshakeResponse: "HandshakeResponse",
        GetToken: "GetToken",
        Response: "Response",
    };
    const BrowserCacheLocation = {
        LocalStorage: "localStorage",
        SessionStorage: "sessionStorage",
        MemoryStorage: "memoryStorage",
    };
    /**
     * HTTP Request types supported by MSAL.
     */
    const HTTP_REQUEST_TYPE = {
        GET: "GET",
        POST: "POST",
    };
    const INTERACTION_TYPE = {
        SIGNIN: "signin",
        SIGNOUT: "signout",
    };
    /**
     * Temporary cache keys for MSAL, deleted after any request.
     */
    const TemporaryCacheKeys = {
        ORIGIN_URI: "request.origin",
        URL_HASH: "urlHash",
        REQUEST_PARAMS: "request.params",
        VERIFIER: "code.verifier",
        INTERACTION_STATUS_KEY: "interaction.status",
        NATIVE_REQUEST: "request.native",
    };
    /**
     * Cache keys stored in-memory
     */
    const InMemoryCacheKeys = {
        WRAPPER_SKU: "wrapper.sku",
        WRAPPER_VER: "wrapper.version",
    };
    /**
     * API Codes for Telemetry purposes.
     * Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs
     * 0-99 Silent Flow
     * 800-899 Auth Code Flow
     * 900-999 Misc
     */
    const ApiId = {
        acquireTokenRedirect: 861,
        acquireTokenPopup: 862,
        ssoSilent: 863,
        acquireTokenSilent_authCode: 864,
        handleRedirectPromise: 865,
        acquireTokenByCode: 866,
        acquireTokenSilent_silentFlow: 61,
        logout: 961,
        logoutPopup: 962,
        hydrateCache: 963,
        loadExternalTokens: 964,
    };
    /**
     * API Names for Telemetry purposes.
     */
    const ApiName = {
        861: "acquireTokenRedirect",
        862: "acquireTokenPopup",
        863: "ssoSilent",
        864: "acquireTokenSilent_authCode",
        865: "handleRedirectPromise",
        866: "acquireTokenByCode",
        61: "acquireTokenSilent_silentFlow",
        961: "logout",
        962: "logoutPopup",
        963: "hydrateCache",
        964: "loadExternalTokens",
    };
    const apiIdToName = (id) => {
        if (typeof id === "number" && id in ApiName) {
            return ApiName[id];
        }
        return "unknown";
    };
    /*
     * Interaction type of the API - used for state and telemetry
     */
    exports.InteractionType = void 0;
    (function (InteractionType) {
        InteractionType["Redirect"] = "redirect";
        InteractionType["Popup"] = "popup";
        InteractionType["Silent"] = "silent";
        InteractionType["None"] = "none";
    })(exports.InteractionType || (exports.InteractionType = {}));
    /**
     * Types of interaction currently in progress.
     * Used in events in wrapper libraries to invoke functions when certain interaction is in progress or all interactions are complete.
     */
    const InteractionStatus = {
        /**
         * Initial status before interaction occurs
         */
        Startup: "startup",
        /**
         * Status set when logout call occuring
         */
        Logout: "logout",
        /**
         * Status set for acquireToken calls
         */
        AcquireToken: "acquireToken",
        /**
         * Status set when handleRedirect in progress
         */
        HandleRedirect: "handleRedirect",
        /**
         * Status set when interaction is complete
         */
        None: "none",
    };
    const DEFAULT_REQUEST = {
        scopes: OIDC_DEFAULT_SCOPES$1,
    };
    /**
     * JWK Key Format string (Type MUST be defined for window crypto APIs)
     */
    const KEY_FORMAT_JWK = "jwk";
    // Supported wrapper SKUs
    const WrapperSKU = {
        React: "@azure/msal-react",
        Angular: "@azure/msal-angular",
    };
    // DatabaseStorage Constants
    const DB_NAME = "msal.db";
    const DB_VERSION = 1;
    const DB_TABLE_NAME = `${DB_NAME}.keys`;
    const CacheLookupPolicy = {
        /*
         * acquireTokenSilent will attempt to retrieve an access token from the cache. If the access token is expired
         * or cannot be found the refresh token will be used to acquire a new one. Finally, if the refresh token
         * is expired acquireTokenSilent will attempt to acquire new access and refresh tokens.
         */
        Default: 0,
        /*
         * acquireTokenSilent will only look for access tokens in the cache. It will not attempt to renew access or
         * refresh tokens.
         */
        AccessToken: 1,
        /*
         * acquireTokenSilent will attempt to retrieve an access token from the cache. If the access token is expired or
         * cannot be found, the refresh token will be used to acquire a new one. If the refresh token is expired, it
         * will not be renewed and acquireTokenSilent will fail.
         */
        AccessTokenAndRefreshToken: 2,
        /*
         * acquireTokenSilent will not attempt to retrieve access tokens from the cache and will instead attempt to
         * exchange the cached refresh token for a new access token. If the refresh token is expired, it will not be
         * renewed and acquireTokenSilent will fail.
         */
        RefreshToken: 3,
        /*
         * acquireTokenSilent will not look in the cache for the access token. It will go directly to network with the
         * cached refresh token. If the refresh token is expired an attempt will be made to renew it. This is equivalent to
         * setting "forceRefresh: true".
         */
        RefreshTokenAndNetwork: 4,
        /*
         * acquireTokenSilent will attempt to renew both access and refresh tokens. It will not look in the cache. This will
         * always fail if 3rd party cookies are blocked by the browser.
         */
        Skip: 5,
    };
    const iFrameRenewalPolicies = [
        CacheLookupPolicy.Default,
        CacheLookupPolicy.Skip,
        CacheLookupPolicy.RefreshTokenAndNetwork,
    ];
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Class which exposes APIs to encode plaintext to base64 encoded string. See here for implementation details:
     * https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_2_%E2%80%93_JavaScript's_UTF-16_%3E_UTF-8_%3E_base64
     */
    /**
     * Returns URL Safe b64 encoded string from a plaintext string.
     * @param input
     */
    function urlEncode(input) {
        return encodeURIComponent(base64Encode(input)
            .replace(/=/g, "")
            .replace(/\+/g, "-")
            .replace(/\//g, "_"));
    }
    /**
     * Returns URL Safe b64 encoded string from an int8Array.
     * @param inputArr
     */
    function urlEncodeArr(inputArr) {
        return base64EncArr(inputArr)
            .replace(/=/g, "")
            .replace(/\+/g, "-")
            .replace(/\//g, "_");
    }
    /**
     * Returns b64 encoded string from plaintext string.
     * @param input
     */
    function base64Encode(input) {
        return base64EncArr(new TextEncoder().encode(input));
    }
    /**
     * Base64 encode byte array
     * @param aBytes
     */
    function base64EncArr(aBytes) {
        const binString = Array.from(aBytes, (x) => String.fromCodePoint(x)).join("");
        return btoa(binString);
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Class which exposes APIs to decode base64 strings to plaintext. See here for implementation details:
     * https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
     */
    /**
     * Returns a URL-safe plaintext decoded string from b64 encoded input.
     * @param input
     */
    function base64Decode(input) {
        return new TextDecoder().decode(base64DecToArr(input));
    }
    /**
     * Decodes base64 into Uint8Array
     * @param base64String
     */
    function base64DecToArr(base64String) {
        let encodedString = base64String.replace(/-/g, "+").replace(/_/g, "/");
        switch (encodedString.length % 4) {
            case 0:
                break;
            case 2:
                encodedString += "==";
                break;
            case 3:
                encodedString += "=";
                break;
            default:
                throw createBrowserAuthError(invalidBase64String);
        }
        const binString = atob(encodedString);
        return Uint8Array.from(binString, (m) => m.codePointAt(0) || 0);
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This file defines functions used by the browser library to perform cryptography operations such as
     * hashing and encoding. It also has helper functions to validate the availability of specific APIs.
     */
    /**
     * See here for more info on RsaHashedKeyGenParams: https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams
     */
    // Algorithms
    const PKCS1_V15_KEYGEN_ALG = "RSASSA-PKCS1-v1_5";
    const AES_GCM = "AES-GCM";
    const HKDF = "HKDF";
    // SHA-256 hashing algorithm
    const S256_HASH_ALG = "SHA-256";
    // MOD length for PoP tokens
    const MODULUS_LENGTH = 2048;
    // Public Exponent
    const PUBLIC_EXPONENT = new Uint8Array([0x01, 0x00, 0x01]);
    // UUID hex digits
    const UUID_CHARS = "0123456789abcdef";
    // Array to store UINT32 random value
    const UINT32_ARR = new Uint32Array(1);
    // Key Format
    const RAW = "raw";
    // Key Usages
    const ENCRYPT = "encrypt";
    const DECRYPT = "decrypt";
    const DERIVE_KEY = "deriveKey";
    // Suberror
    const SUBTLE_SUBERROR = "crypto_subtle_undefined";
    const keygenAlgorithmOptions = {
        name: PKCS1_V15_KEYGEN_ALG,
        hash: S256_HASH_ALG,
        modulusLength: MODULUS_LENGTH,
        publicExponent: PUBLIC_EXPONENT,
    };
    /**
     * Check whether browser crypto is available.
     */
    function validateCryptoAvailable(skipValidateSubtleCrypto) {
        if (!window) {
            throw createBrowserAuthError(nonBrowserEnvironment);
        }
        if (!window.crypto) {
            throw createBrowserAuthError(cryptoNonExistent);
        }
        if (!skipValidateSubtleCrypto && !window.crypto.subtle) {
            throw createBrowserAuthError(cryptoNonExistent, SUBTLE_SUBERROR);
        }
    }
    /**
     * Returns a sha-256 hash of the given dataString as an ArrayBuffer.
     * @param dataString {string} data string
     * @param performanceClient {?IPerformanceClient}
     * @param correlationId {?string} correlation id
     */
    async function sha256Digest(dataString) {
        const encoder = new TextEncoder();
        const data = encoder.encode(dataString);
        return window.crypto.subtle.digest(S256_HASH_ALG, data);
    }
    /**
     * Populates buffer with cryptographically random values.
     * @param dataBuffer
     */
    function getRandomValues(dataBuffer) {
        return window.crypto.getRandomValues(dataBuffer);
    }
    /**
     * Returns random Uint32 value.
     * @returns {number}
     */
    function getRandomUint32() {
        window.crypto.getRandomValues(UINT32_ARR);
        return UINT32_ARR[0];
    }
    /**
     * Creates a UUID v7 from the current timestamp.
     * Implementation relies on the system clock to guarantee increasing order of generated identifiers.
     * @returns {number}
     */
    function createNewGuid() {
        const currentTimestamp = Date.now();
        const baseRand = getRandomUint32() * 0x400 + (getRandomUint32() & 0x3ff);
        // Result byte array
        const bytes = new Uint8Array(16);
        // A 12-bit `rand_a` field value
        const randA = Math.trunc(baseRand / 2 ** 30);
        // The higher 30 bits of 62-bit `rand_b` field value
        const randBHi = baseRand & (2 ** 30 - 1);
        // The lower 32 bits of 62-bit `rand_b` field value
        const randBLo = getRandomUint32();
        bytes[0] = currentTimestamp / 2 ** 40;
        bytes[1] = currentTimestamp / 2 ** 32;
        bytes[2] = currentTimestamp / 2 ** 24;
        bytes[3] = currentTimestamp / 2 ** 16;
        bytes[4] = currentTimestamp / 2 ** 8;
        bytes[5] = currentTimestamp;
        bytes[6] = 0x70 | (randA >>> 8);
        bytes[7] = randA;
        bytes[8] = 0x80 | (randBHi >>> 24);
        bytes[9] = randBHi >>> 16;
        bytes[10] = randBHi >>> 8;
        bytes[11] = randBHi;
        bytes[12] = randBLo >>> 24;
        bytes[13] = randBLo >>> 16;
        bytes[14] = randBLo >>> 8;
        bytes[15] = randBLo;
        let text = "";
        for (let i = 0; i < bytes.length; i++) {
            text += UUID_CHARS.charAt(bytes[i] >>> 4);
            text += UUID_CHARS.charAt(bytes[i] & 0xf);
            if (i === 3 || i === 5 || i === 7 || i === 9) {
                text += "-";
            }
        }
        return text;
    }
    /**
     * Generates a keypair based on current keygen algorithm config.
     * @param extractable
     * @param usages
     */
    async function generateKeyPair(extractable, usages) {
        return window.crypto.subtle.generateKey(keygenAlgorithmOptions, extractable, usages);
    }
    /**
     * Export key as Json Web Key (JWK)
     * @param key
     */
    async function exportJwk(key) {
        return window.crypto.subtle.exportKey(KEY_FORMAT_JWK, key);
    }
    /**
     * Imports key as Json Web Key (JWK), can set extractable and usages.
     * @param key
     * @param extractable
     * @param usages
     */
    async function importJwk(key, extractable, usages) {
        return window.crypto.subtle.importKey(KEY_FORMAT_JWK, key, keygenAlgorithmOptions, extractable, usages);
    }
    /**
     * Signs given data with given key
     * @param key
     * @param data
     */
    async function sign(key, data) {
        return window.crypto.subtle.sign(keygenAlgorithmOptions, key, data);
    }
    /**
     * Generates Base64 encoded jwk used in the Encrypted Authorize Response (EAR) flow
     */
    async function generateEarKey() {
        const key = await generateBaseKey();
        const keyStr = urlEncodeArr(new Uint8Array(key));
        const jwk = {
            alg: "dir",
            kty: "oct",
            k: keyStr,
        };
        return base64Encode(JSON.stringify(jwk));
    }
    /**
     * Parses earJwk for encryption key and returns CryptoKey object
     * @param earJwk
     * @returns
     */
    async function importEarKey(earJwk) {
        const b64DecodedJwk = base64Decode(earJwk);
        const jwkJson = JSON.parse(b64DecodedJwk);
        const rawKey = jwkJson.k;
        const keyBuffer = base64DecToArr(rawKey);
        return window.crypto.subtle.importKey(RAW, keyBuffer, AES_GCM, false, [
            DECRYPT,
        ]);
    }
    /**
     * Decrypt ear_jwe response returned in the Encrypted Authorize Response (EAR) flow
     * @param earJwk
     * @param earJwe
     * @returns
     */
    async function decryptEarResponse(earJwk, earJwe) {
        const earJweParts = earJwe.split(".");
        if (earJweParts.length !== 5) {
            throw createBrowserAuthError(failedToDecryptEarResponse, "jwe_length");
        }
        const key = await importEarKey(earJwk).catch(() => {
            throw createBrowserAuthError(failedToDecryptEarResponse, "import_key");
        });
        try {
            const header = new TextEncoder().encode(earJweParts[0]);
            const iv = base64DecToArr(earJweParts[2]);
            const ciphertext = base64DecToArr(earJweParts[3]);
            const tag = base64DecToArr(earJweParts[4]);
            const tagLengthBits = tag.byteLength * 8;
            // Concat ciphertext and tag
            const encryptedData = new Uint8Array(ciphertext.length + tag.length);
            encryptedData.set(ciphertext);
            encryptedData.set(tag, ciphertext.length);
            const decryptedData = await window.crypto.subtle.decrypt({
                name: AES_GCM,
                iv: iv,
                tagLength: tagLengthBits,
                additionalData: header,
            }, key, encryptedData);
            return new TextDecoder().decode(decryptedData);
        }
        catch (e) {
            throw createBrowserAuthError(failedToDecryptEarResponse, "decrypt");
        }
    }
    /**
     * Generates symmetric base encryption key. This may be stored as all encryption/decryption keys will be derived from this one.
     */
    async function generateBaseKey() {
        const key = await window.crypto.subtle.generateKey({
            name: AES_GCM,
            length: 256,
        }, true, [ENCRYPT, DECRYPT]);
        return window.crypto.subtle.exportKey(RAW, key);
    }
    /**
     * Returns the raw key to be passed into the key derivation function
     * @param baseKey
     * @returns
     */
    async function generateHKDF(baseKey) {
        return window.crypto.subtle.importKey(RAW, baseKey, HKDF, false, [
            DERIVE_KEY,
        ]);
    }
    /**
     * Given a base key and a nonce generates a derived key to be used in encryption and decryption.
     * Note: every time we encrypt a new key is derived
     * @param baseKey
     * @param nonce
     * @returns
     */
    async function deriveKey(baseKey, nonce, context) {
        return window.crypto.subtle.deriveKey({
            name: HKDF,
            salt: nonce,
            hash: S256_HASH_ALG,
            info: new TextEncoder().encode(context),
        }, baseKey, { name: AES_GCM, length: 256 }, false, [ENCRYPT, DECRYPT]);
    }
    /**
     * Encrypt the given data given a base key. Returns encrypted data and a nonce that must be provided during decryption
     * @param key
     * @param rawData
     */
    async function encrypt(baseKey, rawData, context) {
        const encodedData = new TextEncoder().encode(rawData);
        // The nonce must never be reused with a given key.
        const nonce = window.crypto.getRandomValues(new Uint8Array(16));
        const derivedKey = await deriveKey(baseKey, nonce, context);
        const encryptedData = await window.crypto.subtle.encrypt({
            name: AES_GCM,
            iv: new Uint8Array(12), // New key is derived for every encrypt so we don't need a new nonce
        }, derivedKey, encodedData);
        return {
            data: urlEncodeArr(new Uint8Array(encryptedData)),
            nonce: urlEncodeArr(nonce),
        };
    }
    /**
     * Decrypt data with the given key and nonce
     * @param key
     * @param nonce
     * @param encryptedData
     * @returns
     */
    async function decrypt(baseKey, nonce, context, encryptedData) {
        const encodedData = base64DecToArr(encryptedData);
        const derivedKey = await deriveKey(baseKey, base64DecToArr(nonce), context);
        const decryptedData = await window.crypto.subtle.decrypt({
            name: AES_GCM,
            iv: new Uint8Array(12), // New key is derived for every encrypt so we don't need a new nonce
        }, derivedKey, encodedData);
        return new TextDecoder().decode(decryptedData);
    }
    /**
     * Returns the SHA-256 hash of an input string
     * @param plainText
     */
    async function hashString(plainText) {
        const hashBuffer = await sha256Digest(plainText);
        const hashBytes = new Uint8Array(hashBuffer);
        return urlEncodeArr(hashBytes);
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const storageNotSupported = "storage_not_supported";
    const stubbedPublicClientApplicationCalled = "stubbed_public_client_application_called";
    const inMemRedirectUnavailable = "in_mem_redirect_unavailable";
 
    var BrowserConfigurationAuthErrorCodes = /*#__PURE__*/Object.freeze({
        __proto__: null,
        inMemRedirectUnavailable: inMemRedirectUnavailable,
        storageNotSupported: storageNotSupported,
        stubbedPublicClientApplicationCalled: stubbedPublicClientApplicationCalled
    });
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Browser library error class thrown by the MSAL.js library for SPAs
     */
    class BrowserConfigurationAuthError extends AuthError {
        constructor(errorCode, errorMessage) {
            super(errorCode, errorMessage);
            this.name = "BrowserConfigurationAuthError";
            Object.setPrototypeOf(this, BrowserConfigurationAuthError.prototype);
        }
    }
    function createBrowserConfigurationAuthError(errorCode) {
        return new BrowserConfigurationAuthError(errorCode, getDefaultErrorMessage(errorCode));
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Extracts and parses the authentication response from URL (hash and/or query string).
     * This is a shared utility used across multiple components in msal-browser.
     *
     * @returns {Object} An object containing the parsed state information and URL parameters.
     * @returns {URLSearchParams} params - The parsed URL parameters from the payload.
     * @returns {string} payload - The combined query string and hash content.
     * @returns {string} urlHash - The original URL hash.
     * @returns {string} urlQuery - The original URL query string.
     * @returns {LibraryStateObject} libraryState - The decoded library state from the state parameter.
     *
     * @throws {AuthError} If no authentication payload is found in the URL.
     * @throws {AuthError} If the state parameter is missing.
     * @throws {AuthError} If the state is missing required 'id' or 'meta' attributes.
     */
    function parseAuthResponseFromUrl() {
        // Extract both hash and query string to support hybrid response format
        const urlHash = window.location.hash;
        const urlQuery = window.location.search;
        // Determine which part contains the auth response by checking for 'state' parameter
        let hasResponseInHash = false;
        let hasResponseInQuery = false;
        let payload = "";
        let params = undefined;
        if (urlHash && urlHash.length > 1) {
            const hashContent = urlHash.charAt(0) === "#" ? urlHash.substring(1) : urlHash;
            const hashParams = new URLSearchParams(hashContent);
            if (hashParams.has("state")) {
                hasResponseInHash = true;
                payload = hashContent;
                params = hashParams;
            }
        }
        if (urlQuery && urlQuery.length > 1) {
            const queryContent = urlQuery.charAt(0) === "?" ? urlQuery.substring(1) : urlQuery;
            const queryParams = new URLSearchParams(queryContent);
            if (queryParams.has("state")) {
                hasResponseInQuery = true;
                payload = queryContent;
                params = queryParams;
            }
        }
        // If response is in both, combine them (hybrid format)
        if (hasResponseInHash && hasResponseInQuery) {
            const queryContent = urlQuery.charAt(0) === "?" ? urlQuery.substring(1) : urlQuery;
            const hashContent = urlHash.charAt(0) === "#" ? urlHash.substring(1) : urlHash;
            payload = `${queryContent}${hashContent}`;
            params = new URLSearchParams(payload);
        }
        if (!payload || !params) {
            throw createBrowserAuthError(emptyResponse);
        }
        const state = params.get("state");
        if (!state) {
            throw createBrowserAuthError(noStateInHash);
        }
        const { libraryState } = parseRequestState(base64Decode, state);
        const { id, meta } = libraryState;
        if (!id || !meta) {
            throw createBrowserAuthError(unableToParseState, "missing_library_state");
        }
        return {
            params,
            payload,
            urlHash,
            urlQuery,
            hasResponseInHash,
            hasResponseInQuery,
            libraryState: {
                id,
                meta,
            },
        };
    }
    /**
     * Clears hash from window url.
     */
    function clearHash(contentWindow) {
        // Office.js sets history.replaceState to null
        contentWindow.location.hash = "";
        if (typeof contentWindow.history.replaceState === "function") {
            // Full removes "#" from url
            contentWindow.history.replaceState(null, "", `${contentWindow.location.origin}${contentWindow.location.pathname}${contentWindow.location.search}`);
        }
    }
    /**
     * Replaces current hash with hash from provided url
     */
    function replaceHash(url) {
        const urlParts = url.split("#");
        urlParts.shift(); // Remove part before the hash
        window.location.hash = urlParts.length > 0 ? urlParts.join("#") : "";
    }
    /**
     * Returns boolean of whether the current window is in an iframe or not.
     */
    function isInIframe() {
        return window.parent !== window;
    }
    /**
     * Returns boolean of whether or not the current window is a popup opened by msal
     */
    function isInPopup() {
        if (isInIframe()) {
            return false;
        }
        try {
            const { libraryState } = parseAuthResponseFromUrl();
            const { meta } = libraryState;
            return meta["interactionType"] === exports.InteractionType.Popup;
        }
        catch (e) {
            // If parsing fails (no state, invalid URL, etc.), we're not in a popup
            return false;
        }
    }
    /**
     * Await a response from a redirect bridge using BroadcastChannel.
     * This unified function works for both popup and iframe scenarios by listening on a
     * BroadcastChannel for the server payload.
     *
     * @param timeoutMs - Timeout in milliseconds.
     * @param logger - Logger instance for logging monitoring events.
     * @param browserCrypto - Browser crypto instance for decoding state.
     * @param request - The authorization or end session request.
     * @returns Promise<string> - Resolves with the response string (query or hash) from the window.
     */
    // Track the active bridge monitor to allow cancellation when overriding interactions
    let activeBridgeMonitor = null;
    /**
     * Cancels the pending bridge response monitor if one exists.
     * This is called when overrideInteractionInProgress is used to cancel
     * any pending popup interaction before starting a new one.
     */
    function cancelPendingBridgeResponse(logger, correlationId) {
        if (activeBridgeMonitor) {
            logger.verbose("18y01k", correlationId);
            clearTimeout(activeBridgeMonitor.timeoutId);
            activeBridgeMonitor.channel.close();
            activeBridgeMonitor.reject(createBrowserAuthError(interactionInProgressCancelled));
            activeBridgeMonitor = null;
        }
    }
    async function waitForBridgeResponse(timeoutMs, logger, browserCrypto, request, performanceClient, experimentalConfig) {
        return new Promise((resolve, reject) => {
            logger.verbose("1rf6em", request.correlationId);
            const correlationId = request.correlationId;
            performanceClient.addFields({
                redirectBridgeTimeoutMs: timeoutMs,
                lateResponseExperimentEnabled: experimentalConfig?.iframeTimeoutTelemetry || false,
            }, correlationId);
            const { libraryState } = parseRequestState(browserCrypto.base64Decode, request.state || "");
            const channel = new BroadcastChannel(libraryState.id);
            let responseString = undefined;
            let timedOut$1 = false;
            let lateTimeoutId;
            let lateMeasurement;
            const timeoutId = window.setTimeout(() => {
                // Clear the active monitor
                activeBridgeMonitor = null;
                if (experimentalConfig?.iframeTimeoutTelemetry) {
                    lateMeasurement = performanceClient.startMeasurement(WaitForBridgeLateResponse$1, correlationId);
                    timedOut$1 = true;
                    lateTimeoutId = window.setTimeout(() => {
                        lateMeasurement?.end({ success: false });
                        clearTimeout(lateTimeoutId);
                        channel.close();
                    }, 60000); // 60s late response timeout to allow for telemetry of late responses
                }
                else {
                    channel.close();
                }
                reject(createBrowserAuthError(timedOut, "redirect_bridge_timeout"));
            }, timeoutMs);
            // Track this monitor so it can be cancelled if needed
            activeBridgeMonitor = {
                timeoutId,
                channel,
                reject,
            };
            channel.onmessage = (event) => {
                responseString = event.data.payload;
                const messageVersion = event?.data && typeof event.data.v === "number"
                    ? event.data.v
                    : undefined;
                if (timedOut$1) {
                    lateMeasurement?.end({
                        success: responseString ? true : false,
                    });
                    clearTimeout(lateTimeoutId);
                    channel.close();
                    return;
                }
                performanceClient.addFields({
                    redirectBridgeMessageVersion: messageVersion,
                }, correlationId);
                // Clear the active monitor
                activeBridgeMonitor = null;
                clearTimeout(timeoutId);
                channel.close();
                if (responseString) {
                    resolve(responseString);
                }
                else {
                    reject(createBrowserAuthError(redirectBridgeEmptyResponse));
                }
            };
        });
    }
    // #endregion
    /**
     * Returns current window URL as redirect uri
     */
    function getCurrentUri() {
        return typeof window !== "undefined" && window.location
            ? window.location.href.split("?")[0].split("#")[0]
            : "";
    }
    /**
     * Gets the homepage url for the current window location.
     */
    function getHomepage() {
        const currentUrl = new UrlString(window.location.href);
        const urlComponents = currentUrl.getUrlComponents();
        return `${urlComponents.Protocol}//${urlComponents.HostNameAndPort}/`;
    }
    /**
     * Throws error if we have completed an auth and are
     * attempting another auth request inside an iframe.
     */
    function blockReloadInHiddenIframes() {
        const isResponseHash = getDeserializedResponse(window.location.hash);
        // return an error if called from the hidden iframe created by the msal js silent calls
        if (isResponseHash && isInIframe()) {
            throw createBrowserAuthError(blockIframeReload);
        }
    }
    /**
     * Block redirect operations in iframes unless explicitly allowed
     * @param interactionType Interaction type for the request
     * @param allowRedirectInIframe Config value to allow redirects when app is inside an iframe
     */
    function blockRedirectInIframe(allowRedirectInIframe) {
        if (isInIframe() && !allowRedirectInIframe) {
            // If we are not in top frame, we shouldn't redirect. This is also handled by the service.
            throw createBrowserAuthError(redirectInIframe);
        }
    }
    /**
     * Block redirectUri loaded in popup from calling AcquireToken APIs
     */
    function blockAcquireTokenInPopups() {
        // Popups opened by msal popup APIs are given a name that starts with "msal."
        if (isInPopup()) {
            throw createBrowserAuthError(blockNestedPopups);
        }
    }
    /**
     * Throws error if token requests are made in non-browser environment
     * @param isBrowserEnvironment Flag indicating if environment is a browser.
     */
    function blockNonBrowserEnvironment() {
        if (typeof window === "undefined") {
            throw createBrowserAuthError(nonBrowserEnvironment);
        }
    }
    /**
     * Throws error if initialize hasn't been called
     * @param initialized
     */
    function blockAPICallsBeforeInitialize(initialized) {
        if (!initialized) {
            throw createBrowserAuthError(uninitializedPublicClientApplication);
        }
    }
    /**
     * Helper to validate app environment before making an auth request
     * @param initialized
     */
    function preflightCheck$1(initialized) {
        // Block request if not in browser environment
        blockNonBrowserEnvironment();
        // Block auth requests inside a hidden iframe
        blockReloadInHiddenIframes();
        // Block redirectUri opened in a popup from calling MSAL APIs
        blockAcquireTokenInPopups();
        // Block token acquisition before initialize has been called
        blockAPICallsBeforeInitialize(initialized);
    }
    /**
     * Helper to validate app enviornment before making redirect request
     * @param initialized
     * @param config
     */
    function redirectPreflightCheck(initialized, config) {
        preflightCheck$1(initialized);
        blockRedirectInIframe(config.system.allowRedirectInIframe);
        // Block redirects if memory storage is enabled
        if (config.cache.cacheLocation === BrowserCacheLocation.MemoryStorage) {
            throw createBrowserConfigurationAuthError(inMemRedirectUnavailable);
        }
    }
    /**
     * Adds a preconnect link element to the header which begins DNS resolution and SSL connection in anticipation of the /token request
     * @param loginDomain Authority domain, including https protocol e.g. https://login.microsoftonline.com
     * @returns
     */
    function preconnect(authority) {
        const link = document.createElement("link");
        link.rel = "preconnect";
        link.href = new URL(authority).origin;
        link.crossOrigin = "anonymous";
        document.head.appendChild(link);
        // The browser will close connection if not used within a few seconds, remove element from the header after 10s
        window.setTimeout(() => {
            try {
                document.head.removeChild(link);
            }
            catch { }
        }, 10000); // 10s Timeout
    }
    /**
     * Wrapper function that creates a UUID v7 from the current timestamp.
     * @returns {string}
     */
    function createGuid() {
        return createNewGuid();
    }
    const addClientCapabilitiesToClaims = addClientCapabilitiesToClaims$1;
 
    var BrowserUtils = /*#__PURE__*/Object.freeze({
        __proto__: null,
        addClientCapabilitiesToClaims: addClientCapabilitiesToClaims,
        blockAPICallsBeforeInitialize: blockAPICallsBeforeInitialize,
        blockAcquireTokenInPopups: blockAcquireTokenInPopups,
        blockNonBrowserEnvironment: blockNonBrowserEnvironment,
        blockRedirectInIframe: blockRedirectInIframe,
        blockReloadInHiddenIframes: blockReloadInHiddenIframes,
        cancelPendingBridgeResponse: cancelPendingBridgeResponse,
        clearHash: clearHash,
        createGuid: createGuid,
        getCurrentUri: getCurrentUri,
        getHomepage: getHomepage,
        invoke: invoke,
        invokeAsync: invokeAsync,
        isInIframe: isInIframe,
        isInPopup: isInPopup,
        parseAuthResponseFromUrl: parseAuthResponseFromUrl,
        preconnect: preconnect,
        preflightCheck: preflightCheck$1,
        redirectPreflightCheck: redirectPreflightCheck,
        replaceHash: replaceHash,
        waitForBridgeResponse: waitForBridgeResponse
    });
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Storage wrapper for IndexedDB storage in browsers: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
     */
    class DatabaseStorage {
        constructor() {
            this.dbName = DB_NAME;
            this.version = DB_VERSION;
            this.tableName = DB_TABLE_NAME;
            this.dbOpen = false;
        }
        /**
         * Opens IndexedDB instance.
         */
        async open() {
            return new Promise((resolve, reject) => {
                const openDB = window.indexedDB.open(this.dbName, this.version);
                openDB.addEventListener("upgradeneeded", (e) => {
                    const event = e;
                    event.target.result.createObjectStore(this.tableName);
                });
                openDB.addEventListener("success", (e) => {
                    const event = e;
                    this.db = event.target.result;
                    this.dbOpen = true;
                    resolve();
                });
                openDB.addEventListener("error", () => reject(createBrowserAuthError(databaseUnavailable)));
            });
        }
        /**
         * Closes the connection to IndexedDB database when all pending transactions
         * complete.
         */
        closeConnection() {
            const db = this.db;
            if (db && this.dbOpen) {
                db.close();
                this.dbOpen = false;
            }
        }
        /**
         * Opens database if it's not already open
         */
        async validateDbIsOpen() {
            if (!this.dbOpen) {
                return this.open();
            }
        }
        /**
         * Retrieves item from IndexedDB instance.
         * @param key
         */
        async getItem(key) {
            await this.validateDbIsOpen();
            return new Promise((resolve, reject) => {
                // TODO: Add timeouts?
                if (!this.db) {
                    return reject(createBrowserAuthError(databaseNotOpen));
                }
                const transaction = this.db.transaction([this.tableName], "readonly");
                const objectStore = transaction.objectStore(this.tableName);
                const dbGet = objectStore.get(key);
                dbGet.addEventListener("success", (e) => {
                    const event = e;
                    this.closeConnection();
                    resolve(event.target.result);
                });
                dbGet.addEventListener("error", (e) => {
                    this.closeConnection();
                    reject(e);
                });
            });
        }
        /**
         * Adds item to IndexedDB under given key
         * @param key
         * @param payload
         */
        async setItem(key, payload) {
            await this.validateDbIsOpen();
            return new Promise((resolve, reject) => {
                // TODO: Add timeouts?
                if (!this.db) {
                    return reject(createBrowserAuthError(databaseNotOpen));
                }
                const transaction = this.db.transaction([this.tableName], "readwrite");
                const objectStore = transaction.objectStore(this.tableName);
                const dbPut = objectStore.put(payload, key);
                dbPut.addEventListener("success", () => {
                    this.closeConnection();
                    resolve();
                });
                dbPut.addEventListener("error", (e) => {
                    this.closeConnection();
                    reject(e);
                });
            });
        }
        /**
         * Removes item from IndexedDB under given key
         * @param key
         */
        async removeItem(key) {
            await this.validateDbIsOpen();
            return new Promise((resolve, reject) => {
                if (!this.db) {
                    return reject(createBrowserAuthError(databaseNotOpen));
                }
                const transaction = this.db.transaction([this.tableName], "readwrite");
                const objectStore = transaction.objectStore(this.tableName);
                const dbDelete = objectStore.delete(key);
                dbDelete.addEventListener("success", () => {
                    this.closeConnection();
                    resolve();
                });
                dbDelete.addEventListener("error", (e) => {
                    this.closeConnection();
                    reject(e);
                });
            });
        }
        /**
         * Get all the keys from the storage object as an iterable array of strings.
         */
        async getKeys() {
            await this.validateDbIsOpen();
            return new Promise((resolve, reject) => {
                if (!this.db) {
                    return reject(createBrowserAuthError(databaseNotOpen));
                }
                const transaction = this.db.transaction([this.tableName], "readonly");
                const objectStore = transaction.objectStore(this.tableName);
                const dbGetKeys = objectStore.getAllKeys();
                dbGetKeys.addEventListener("success", (e) => {
                    const event = e;
                    this.closeConnection();
                    resolve(event.target.result);
                });
                dbGetKeys.addEventListener("error", (e) => {
                    this.closeConnection();
                    reject(e);
                });
            });
        }
        /**
         *
         * Checks whether there is an object under the search key in the object store
         */
        async containsKey(key) {
            await this.validateDbIsOpen();
            return new Promise((resolve, reject) => {
                if (!this.db) {
                    return reject(createBrowserAuthError(databaseNotOpen));
                }
                const transaction = this.db.transaction([this.tableName], "readonly");
                const objectStore = transaction.objectStore(this.tableName);
                const dbContainsKey = objectStore.count(key);
                dbContainsKey.addEventListener("success", (e) => {
                    const event = e;
                    this.closeConnection();
                    resolve(event.target.result === 1);
                });
                dbContainsKey.addEventListener("error", (e) => {
                    this.closeConnection();
                    reject(e);
                });
            });
        }
        /**
         * Deletes the MSAL database. The database is deleted rather than cleared to make it possible
         * for client applications to downgrade to a previous MSAL version without worrying about forward compatibility issues
         * with IndexedDB database versions.
         */
        async deleteDatabase() {
            // Check if database being deleted exists
            if (this.db && this.dbOpen) {
                this.closeConnection();
            }
            return new Promise((resolve, reject) => {
                const deleteDbRequest = window.indexedDB.deleteDatabase(DB_NAME);
                const id = setTimeout(() => reject(false), 200); // Reject if events aren't raised within 200ms
                deleteDbRequest.addEventListener("success", () => {
                    clearTimeout(id);
                    return resolve(true);
                });
                deleteDbRequest.addEventListener("blocked", () => {
                    clearTimeout(id);
                    return resolve(true);
                });
                deleteDbRequest.addEventListener("error", () => {
                    clearTimeout(id);
                    return reject(false);
                });
            });
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class MemoryStorage {
        constructor() {
            this.cache = new Map();
        }
        async initialize() {
            // Memory storage does not require initialization
        }
        getItem(key) {
            return this.cache.get(key) || null;
        }
        getUserData(key) {
            return this.getItem(key);
        }
        setItem(key, value) {
            this.cache.set(key, value);
        }
        async setUserData(key, value) {
            this.setItem(key, value);
        }
        removeItem(key) {
            this.cache.delete(key);
        }
        getKeys() {
            const cacheKeys = [];
            this.cache.forEach((value, key) => {
                cacheKeys.push(key);
            });
            return cacheKeys;
        }
        containsKey(key) {
            return this.cache.has(key);
        }
        clear() {
            this.cache.clear();
        }
        decryptData() {
            // Memory storage does not support encryption, so this method is a no-op
            return Promise.resolve(null);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This class allows MSAL to store artifacts asynchronously using the DatabaseStorage IndexedDB wrapper,
     * backed up with the more volatile MemoryStorage object for cases in which IndexedDB may be unavailable.
     */
    class AsyncMemoryStorage {
        constructor(logger) {
            this.inMemoryCache = new MemoryStorage();
            this.indexedDBCache = new DatabaseStorage();
            this.logger = logger;
        }
        handleDatabaseAccessError(error, correlationId) {
            if (error instanceof BrowserAuthError &&
                error.errorCode === databaseUnavailable) {
                this.logger.error("1wx7zz", correlationId);
            }
            else {
                throw error;
            }
        }
        /**
         * Get the item matching the given key. Tries in-memory cache first, then in the asynchronous
         * storage object if item isn't found in-memory.
         * @param key
         * @param correlationId
         */
        async getItem(key, correlationId) {
            const item = this.inMemoryCache.getItem(key);
            if (!item) {
                try {
                    this.logger.verbose("0naxpl", correlationId);
                    return await this.indexedDBCache.getItem(key);
                }
                catch (e) {
                    this.handleDatabaseAccessError(e, correlationId);
                }
            }
            return item;
        }
        /**
         * Sets the item in the in-memory cache and then tries to set it in the asynchronous
         * storage object with the given key.
         * @param key
         * @param value
         * @param correlationId
         */
        async setItem(key, value, correlationId) {
            this.inMemoryCache.setItem(key, value);
            try {
                await this.indexedDBCache.setItem(key, value);
            }
            catch (e) {
                this.handleDatabaseAccessError(e, correlationId);
            }
        }
        /**
         * Removes the item matching the key from the in-memory cache, then tries to remove it from the asynchronous storage object.
         * @param key
         * @param correlationId
         */
        async removeItem(key, correlationId) {
            this.inMemoryCache.removeItem(key);
            try {
                await this.indexedDBCache.removeItem(key);
            }
            catch (e) {
                this.handleDatabaseAccessError(e, correlationId);
            }
        }
        /**
         * Get all the keys from the in-memory cache as an iterable array of strings. If no keys are found, query the keys in the
         * asynchronous storage object.
         * @param correlationId
         */
        async getKeys(correlationId) {
            const cacheKeys = this.inMemoryCache.getKeys();
            if (cacheKeys.length === 0) {
                try {
                    this.logger.verbose("1iqrbq", correlationId);
                    return await this.indexedDBCache.getKeys();
                }
                catch (e) {
                    this.handleDatabaseAccessError(e, correlationId);
                }
            }
            return cacheKeys;
        }
        /**
         * Returns true or false if the given key is present in the cache.
         * @param key
         * @param correlationId
         */
        async containsKey(key, correlationId) {
            const containsKey = this.inMemoryCache.containsKey(key);
            if (!containsKey) {
                try {
                    this.logger.verbose("03zl2j", correlationId);
                    return await this.indexedDBCache.containsKey(key);
                }
                catch (e) {
                    this.handleDatabaseAccessError(e, correlationId);
                }
            }
            return containsKey;
        }
        /**
         * Clears in-memory Map
         * @param correlationId
         */
        clearInMemory(correlationId) {
            // InMemory cache is a Map instance, clear is straightforward
            this.logger.verbose("03r21p", correlationId);
            this.inMemoryCache.clear();
            this.logger.verbose("0uksk1", correlationId);
        }
        /**
         * Tries to delete the IndexedDB database
         * @param correlationId
         * @returns
         */
        async clearPersistent(correlationId) {
            try {
                this.logger.verbose("0rdqut", correlationId);
                const dbDeleted = await this.indexedDBCache.deleteDatabase();
                if (dbDeleted) {
                    this.logger.verbose("149ouc", correlationId);
                }
                return dbDeleted;
            }
            catch (e) {
                this.handleDatabaseAccessError(e, correlationId);
                return false;
            }
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This class implements MSAL's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and
     * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).
     */
    class CryptoOps {
        constructor(logger, performanceClient, skipValidateSubtleCrypto) {
            this.logger = logger;
            // Browser crypto needs to be validated first before any other classes can be set.
            validateCryptoAvailable(skipValidateSubtleCrypto ?? false);
            this.cache = new AsyncMemoryStorage(this.logger);
            this.performanceClient = performanceClient;
        }
        /**
         * Creates a new random GUID - used to populate state and nonce.
         * @returns string (GUID)
         */
        createNewGuid() {
            return createNewGuid();
        }
        /**
         * Encodes input string to base64.
         * @param input
         */
        base64Encode(input) {
            return base64Encode(input);
        }
        /**
         * Decodes input string from base64.
         * @param input
         */
        base64Decode(input) {
            return base64Decode(input);
        }
        /**
         * Encodes input string to base64 URL safe string.
         * @param input
         */
        base64UrlEncode(input) {
            return urlEncode(input);
        }
        /**
         * Stringifies and base64Url encodes input public key
         * @param inputKid
         * @returns Base64Url encoded public key
         */
        encodeKid(inputKid) {
            return this.base64UrlEncode(JSON.stringify({ kid: inputKid }));
        }
        /**
         * Generates a keypair, stores it and returns a thumbprint
         * @param request
         */
        async getPublicKeyThumbprint(request) {
            const publicKeyThumbMeasurement = this.performanceClient?.startMeasurement(CryptoOptsGetPublicKeyThumbprint, request.correlationId);
            // Generate Keypair
            const keyPair = await generateKeyPair(CryptoOps.EXTRACTABLE, CryptoOps.POP_KEY_USAGES);
            // Generate Thumbprint for Public Key
            const publicKeyJwk = await exportJwk(keyPair.publicKey);
            const pubKeyThumprintObj = {
                e: publicKeyJwk.e,
                kty: publicKeyJwk.kty,
                n: publicKeyJwk.n,
            };
            const publicJwkString = getSortedObjectString(pubKeyThumprintObj);
            const publicJwkHash = await this.hashString(publicJwkString);
            // Generate Thumbprint for Private Key
            const privateKeyJwk = await exportJwk(keyPair.privateKey);
            // Re-import private key to make it unextractable
            const unextractablePrivateKey = await importJwk(privateKeyJwk, false, ["sign"]);
            // Store Keypair data in keystore
            await this.cache.setItem(publicJwkHash, {
                privateKey: unextractablePrivateKey,
                publicKey: keyPair.publicKey,
                requestMethod: request.resourceRequestMethod,
                requestUri: request.resourceRequestUri,
            }, request.correlationId);
            if (publicKeyThumbMeasurement) {
                publicKeyThumbMeasurement.end({
                    success: true,
                });
            }
            return publicJwkHash;
        }
        /**
         * Removes cryptographic keypair from key store matching the keyId passed in
         * @param kid
         * @param correlationId
         */
        async removeTokenBindingKey(kid, correlationId) {
            await this.cache.removeItem(kid, correlationId);
            const keyFound = await this.cache.containsKey(kid, correlationId);
            if (keyFound) {
                throw createClientAuthError(bindingKeyNotRemoved);
            }
        }
        /**
         * Removes all cryptographic keys from IndexedDB storage
         * @param correlationId
         */
        async clearKeystore(correlationId) {
            // Delete in-memory keystores
            this.cache.clearInMemory(correlationId);
            /**
             * There is only one database, so calling clearPersistent on asymmetric keystore takes care of
             * every persistent keystore
             */
            try {
                await this.cache.clearPersistent(correlationId);
                return true;
            }
            catch (e) {
                if (e instanceof Error) {
                    this.logger.error("1owpn8", correlationId);
                }
                else {
                    this.logger.error("0yrmwo", correlationId);
                }
                return false;
            }
        }
        /**
         * Signs the given object as a jwt payload with private key retrieved by given kid.
         * @param payload
         * @param kid
         */
        async signJwt(payload, kid, shrOptions, correlationId) {
            const signJwtMeasurement = this.performanceClient?.startMeasurement(CryptoOptsSignJwt, correlationId);
            const cachedKeyPair = await this.cache.getItem(kid, correlationId || "");
            if (!cachedKeyPair) {
                throw createBrowserAuthError(cryptoKeyNotFound);
            }
            // Get public key as JWK
            const publicKeyJwk = await exportJwk(cachedKeyPair.publicKey);
            const publicKeyJwkString = getSortedObjectString(publicKeyJwk);
            // Base64URL encode public key thumbprint with keyId only: BASE64URL({ kid: "FULL_PUBLIC_KEY_HASH" })
            const encodedKeyIdThumbprint = urlEncode(JSON.stringify({ kid: kid }));
            // Generate header
            const shrHeader = JoseHeader.getShrHeaderString({
                ...shrOptions?.header,
                alg: publicKeyJwk.alg,
                kid: encodedKeyIdThumbprint,
            });
            const encodedShrHeader = urlEncode(shrHeader);
            // Generate payload
            payload.cnf = {
                jwk: JSON.parse(publicKeyJwkString),
            };
            const encodedPayload = urlEncode(JSON.stringify(payload));
            // Form token string
            const tokenString = `${encodedShrHeader}.${encodedPayload}`;
            // Sign token
            const encoder = new TextEncoder();
            const tokenBuffer = encoder.encode(tokenString);
            const signatureBuffer = await sign(cachedKeyPair.privateKey, tokenBuffer);
            const encodedSignature = urlEncodeArr(new Uint8Array(signatureBuffer));
            const signedJwt = `${tokenString}.${encodedSignature}`;
            if (signJwtMeasurement) {
                signJwtMeasurement.end({
                    success: true,
                });
            }
            return signedJwt;
        }
        /**
         * Returns the SHA-256 hash of an input string
         * @param plainText
         */
        async hashString(plainText) {
            return hashString(plainText);
        }
    }
    CryptoOps.POP_KEY_USAGES = ["sign", "verify"];
    CryptoOps.EXTRACTABLE = true;
    function getSortedObjectString(obj) {
        return JSON.stringify(obj, Object.keys(obj).sort());
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * acquireTokenSilent API (msal-browser and msal-node).
     * Used to silently acquire a new access token (from the cache or the network).
     */
    const AcquireTokenSilent = "acquireTokenSilent";
    /**
     * acquireTokenByCode API (msal-browser and msal-node).
     * Used to acquire tokens by trading an authorization code against the token endpoint.
     */
    const AcquireTokenByCode = "acquireTokenByCode";
    /**
     * acquireTokenPopup (msal-browser).
     * Used to acquire a new access token interactively through pop ups
     */
    const AcquireTokenPopup = "acquireTokenPopup";
    /**
     * acquireTokenPreRedirect (msal-browser).
     * First part of the redirect flow.
     * Used to acquire a new access token interactively through redirects.
     */
    const AcquireTokenPreRedirect = "acquireTokenPreRedirect";
    /**
     * acquireTokenRedirect (msal-browser).
     * Second part of the redirect flow.
     * Used to acquire a new access token interactively through redirects.
     */
    const AcquireTokenRedirect = "acquireTokenRedirect";
    /**
     * ssoSilent API (msal-browser).
     * Used to silently acquire an authorization code and set of tokens using a hidden iframe.
     */
    const SsoSilent = "ssoSilent";
    // Initialize client application
    const InitializeClientApplication = "initializeClientApplication";
    // Update cache storage
    const LocalStorageUpdated = "localStorageUpdated";
    // Load external tokens
    const LoadExternalTokens = "loadExternalTokens";
    /**
     * SSO capability verification call (msal-browser).
     * Fire-and-forget SSO verification call made after interactive authentication completes.
     */
    const SsoCapable = "ssoCapable";
    // Wait for late response from bridge after timeout has already occurred
    const WaitForBridgeLateResponse = "waitForBridgeLateResponse";
 
    var BrowserRootPerformanceEvents = /*#__PURE__*/Object.freeze({
        __proto__: null,
        AcquireTokenByCode: AcquireTokenByCode,
        AcquireTokenPopup: AcquireTokenPopup,
        AcquireTokenPreRedirect: AcquireTokenPreRedirect,
        AcquireTokenRedirect: AcquireTokenRedirect,
        AcquireTokenSilent: AcquireTokenSilent,
        InitializeClientApplication: InitializeClientApplication,
        LoadExternalTokens: LoadExternalTokens,
        LocalStorageUpdated: LocalStorageUpdated,
        SsoCapable: SsoCapable,
        SsoSilent: SsoSilent,
        WaitForBridgeLateResponse: WaitForBridgeLateResponse
    });
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const PREFIX = "msal";
    const BROWSER_PREFIX = "browser";
    const CACHE_KEY_SEPARATOR = "|";
    const CREDENTIAL_SCHEMA_VERSION = 2;
    const ACCOUNT_SCHEMA_VERSION = 2;
    const LOG_LEVEL_CACHE_KEY = `${PREFIX}.${BROWSER_PREFIX}.log.level`;
    const LOG_PII_CACHE_KEY = `${PREFIX}.${BROWSER_PREFIX}.log.pii`;
    const BROWSER_PERF_ENABLED_KEY = `${PREFIX}.${BROWSER_PREFIX}.performance.enabled`;
    const PLATFORM_AUTH_DOM_SUPPORT = `${PREFIX}.${BROWSER_PREFIX}.platform.auth.dom`;
    const VERSION_CACHE_KEY = `${PREFIX}.version`;
    const ACCOUNT_KEYS = "account.keys";
    const TOKEN_KEYS = "token.keys";
    const SSO_CAPABLE = `${PREFIX}.${BROWSER_PREFIX}.sso.capable`;
    function getAccountKeysCacheKey(schema = ACCOUNT_SCHEMA_VERSION) {
        if (schema < 1) {
            return `${PREFIX}.${ACCOUNT_KEYS}`;
        }
        return `${PREFIX}.${schema}.${ACCOUNT_KEYS}`;
    }
    function getTokenKeysCacheKey(clientId, schema = CREDENTIAL_SCHEMA_VERSION) {
        if (schema < 1) {
            return `${PREFIX}.${TOKEN_KEYS}.${clientId}`;
        }
        return `${PREFIX}.${schema}.${TOKEN_KEYS}.${clientId}`;
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    // Cookie life calculation (hours * minutes * seconds * ms)
    const COOKIE_LIFE_MULTIPLIER = 24 * 60 * 60 * 1000;
    const SameSiteOptions = {
        Lax: "Lax",
        None: "None",
    };
    class CookieStorage {
        initialize() {
            return Promise.resolve();
        }
        getItem(key) {
            const name = `${encodeURIComponent(key)}`;
            const cookieList = document.cookie.split(";");
            for (let i = 0; i < cookieList.length; i++) {
                const cookie = cookieList[i];
                const [key, ...rest] = decodeURIComponent(cookie).trim().split("=");
                const value = rest.join("=");
                if (key === name) {
                    return value;
                }
            }
            return "";
        }
        getUserData() {
            throw createClientAuthError(methodNotImplemented);
        }
        setItem(key, value, cookieLifeDays, secure = true, sameSite = SameSiteOptions.Lax) {
            let cookieStr = `${encodeURIComponent(key)}=${encodeURIComponent(value)};path=/;SameSite=${sameSite};`;
            if (cookieLifeDays) {
                const expireTime = getCookieExpirationTime(cookieLifeDays);
                cookieStr += `expires=${expireTime};`;
            }
            if (secure || sameSite === SameSiteOptions.None) {
                // SameSite None requires Secure flag
                cookieStr += "Secure;";
            }
            document.cookie = cookieStr;
        }
        async setUserData() {
            return Promise.reject(createClientAuthError(methodNotImplemented));
        }
        removeItem(key) {
            // Setting expiration to -1 removes it
            this.setItem(key, "", -1);
        }
        getKeys() {
            const cookieList = document.cookie.split(";");
            const keys = [];
            cookieList.forEach((cookie) => {
                const cookieParts = decodeURIComponent(cookie).trim().split("=");
                keys.push(cookieParts[0]);
            });
            return keys;
        }
        containsKey(key) {
            return this.getKeys().includes(key);
        }
        decryptData() {
            // Cookie storage does not support encryption, so this method is a no-op
            return Promise.resolve(null);
        }
    }
    /**
     * Get cookie expiration time
     * @param cookieLifeDays
     */
    function getCookieExpirationTime(cookieLifeDays) {
        const today = new Date();
        const expr = new Date(today.getTime() + cookieLifeDays * COOKIE_LIFE_MULTIPLIER);
        return expr.toUTCString();
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Returns a list of cache keys for all known accounts
     * @param storage
     * @returns
     */
    function getAccountKeys(storage, schemaVersion) {
        const accountKeys = storage.getItem(getAccountKeysCacheKey(schemaVersion));
        if (accountKeys) {
            return JSON.parse(accountKeys);
        }
        return [];
    }
    /**
     * Returns a list of cache keys for all known tokens
     * @param clientId
     * @param storage
     * @returns
     */
    function getTokenKeys(clientId, storage, schemaVersion) {
        const item = storage.getItem(getTokenKeysCacheKey(clientId, schemaVersion));
        if (item) {
            const tokenKeys = JSON.parse(item);
            if (tokenKeys &&
                tokenKeys.hasOwnProperty("idToken") &&
                tokenKeys.hasOwnProperty("accessToken") &&
                tokenKeys.hasOwnProperty("refreshToken")) {
                return tokenKeys;
            }
        }
        return {
            idToken: [],
            accessToken: [],
            refreshToken: [],
        };
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function isEncrypted(data) {
        return (data.hasOwnProperty("id") &&
            data.hasOwnProperty("nonce") &&
            data.hasOwnProperty("data"));
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const ENCRYPTION_KEY = "msal.cache.encryption";
    const BROADCAST_CHANNEL_NAME$1 = "msal.broadcast.cache";
    class LocalStorage {
        constructor(clientId, logger, performanceClient) {
            if (!window.localStorage) {
                throw createBrowserConfigurationAuthError(storageNotSupported);
            }
            this.memoryStorage = new MemoryStorage();
            this.initialized = false;
            this.clientId = clientId;
            this.logger = logger;
            this.performanceClient = performanceClient;
            this.broadcast = new BroadcastChannel(BROADCAST_CHANNEL_NAME$1);
        }
        async initialize(correlationId) {
            const cookies = new CookieStorage();
            const cookieString = cookies.getItem(ENCRYPTION_KEY);
            let parsedCookie = { key: "", id: "" };
            if (cookieString) {
                try {
                    parsedCookie = JSON.parse(cookieString);
                }
                catch (e) { }
            }
            if (parsedCookie.key && parsedCookie.id) {
                // Encryption key already exists, import
                const baseKey = invoke(base64DecToArr, Base64Decode, this.logger, this.performanceClient, correlationId)(parsedCookie.key);
                this.encryptionCookie = {
                    id: parsedCookie.id,
                    key: await invokeAsync(generateHKDF, GenerateHKDF, this.logger, this.performanceClient, correlationId)(baseKey),
                };
            }
            else {
                // Encryption key doesn't exist or is invalid, generate a new one
                const id = createNewGuid();
                const baseKey = await invokeAsync(generateBaseKey, GenerateBaseKey, this.logger, this.performanceClient, correlationId)();
                const keyStr = invoke(urlEncodeArr, UrlEncodeArr, this.logger, this.performanceClient, correlationId)(new Uint8Array(baseKey));
                this.encryptionCookie = {
                    id: id,
                    key: await invokeAsync(generateHKDF, GenerateHKDF, this.logger, this.performanceClient, correlationId)(baseKey),
                };
                const cookieData = {
                    id: id,
                    key: keyStr,
                };
                cookies.setItem(ENCRYPTION_KEY, JSON.stringify(cookieData), 0, // Expiration - 0 means cookie will be cleared at the end of the browser session
                true, // Secure flag
                SameSiteOptions.None // SameSite must be None to support iframed apps
                );
            }
            await invokeAsync(this.importExistingCache.bind(this), ImportExistingCache, this.logger, this.performanceClient, correlationId)(correlationId);
            // Register listener for cache updates in other tabs
            this.broadcast.addEventListener("message", (event) => {
                this.updateCache(event, correlationId);
            });
            this.initialized = true;
        }
        getItem(key) {
            return window.localStorage.getItem(key);
        }
        getUserData(key) {
            if (!this.initialized) {
                throw createBrowserAuthError(uninitializedPublicClientApplication);
            }
            return this.memoryStorage.getItem(key);
        }
        async decryptData(key, data, correlationId) {
            if (!this.initialized || !this.encryptionCookie) {
                throw createBrowserAuthError(uninitializedPublicClientApplication);
            }
            if (data.id !== this.encryptionCookie.id) {
                // Data was encrypted with a different key. It must be removed because it is from a previous session.
                this.performanceClient.incrementFields({ encryptedCacheExpiredCount: 1 }, correlationId);
                return null;
            }
            const decryptedData = await invokeAsync(decrypt, Decrypt, this.logger, this.performanceClient, correlationId)(this.encryptionCookie.key, data.nonce, this.getContext(key), data.data);
            if (!decryptedData) {
                return null;
            }
            try {
                return {
                    ...JSON.parse(decryptedData),
                    lastUpdatedAt: data.lastUpdatedAt,
                };
            }
            catch (e) {
                this.performanceClient.incrementFields({ encryptedCacheCorruptionCount: 1 }, correlationId);
                return null;
            }
        }
        setItem(key, value) {
            window.localStorage.setItem(key, value);
        }
        async setUserData(key, value, correlationId, timestamp, kmsi) {
            if (!this.initialized || !this.encryptionCookie) {
                throw createBrowserAuthError(uninitializedPublicClientApplication);
            }
            if (kmsi) {
                this.setItem(key, value);
            }
            else {
                const { data, nonce } = await invokeAsync(encrypt, Encrypt, this.logger, this.performanceClient, correlationId)(this.encryptionCookie.key, value, this.getContext(key));
                const encryptedData = {
                    id: this.encryptionCookie.id,
                    nonce: nonce,
                    data: data,
                    lastUpdatedAt: timestamp,
                };
                this.setItem(key, JSON.stringify(encryptedData));
            }
            this.memoryStorage.setItem(key, value);
            // Notify other frames to update their in-memory cache
            this.broadcast.postMessage({
                key: key,
                value: value,
                context: this.getContext(key),
            });
        }
        removeItem(key) {
            if (this.memoryStorage.containsKey(key)) {
                this.memoryStorage.removeItem(key);
                this.broadcast.postMessage({
                    key: key,
                    value: null,
                    context: this.getContext(key),
                });
            }
            window.localStorage.removeItem(key);
        }
        getKeys() {
            return Object.keys(window.localStorage);
        }
        containsKey(key) {
            return window.localStorage.hasOwnProperty(key);
        }
        /**
         * Removes all known MSAL keys from the cache
         */
        clear() {
            // Removes all remaining MSAL cache items
            this.memoryStorage.clear();
            const accountKeys = getAccountKeys(this);
            accountKeys.forEach((key) => this.removeItem(key));
            const tokenKeys = getTokenKeys(this.clientId, this);
            tokenKeys.idToken.forEach((key) => this.removeItem(key));
            tokenKeys.accessToken.forEach((key) => this.removeItem(key));
            tokenKeys.refreshToken.forEach((key) => this.removeItem(key));
            // Clean up anything left
            this.getKeys().forEach((cacheKey) => {
                if (cacheKey.startsWith(PREFIX) ||
                    cacheKey.indexOf(this.clientId) !== -1) {
                    this.removeItem(cacheKey);
                }
            });
        }
        /**
         * Helper to decrypt all known MSAL keys in localStorage and save them to inMemory storage
         * @returns
         */
        async importExistingCache(correlationId) {
            if (!this.encryptionCookie) {
                return;
            }
            let accountKeys = getAccountKeys(this);
            accountKeys = await this.importArray(accountKeys, correlationId);
            // Write valid account keys back to map
            if (accountKeys.length) {
                this.setItem(getAccountKeysCacheKey(), JSON.stringify(accountKeys));
            }
            else {
                this.removeItem(getAccountKeysCacheKey());
            }
            const tokenKeys = getTokenKeys(this.clientId, this);
            tokenKeys.idToken = await this.importArray(tokenKeys.idToken, correlationId);
            tokenKeys.accessToken = await this.importArray(tokenKeys.accessToken, correlationId);
            tokenKeys.refreshToken = await this.importArray(tokenKeys.refreshToken, correlationId);
            // Write valid token keys back to map
            if (tokenKeys.idToken.length ||
                tokenKeys.accessToken.length ||
                tokenKeys.refreshToken.length) {
                this.setItem(getTokenKeysCacheKey(this.clientId), JSON.stringify(tokenKeys));
            }
            else {
                this.removeItem(getTokenKeysCacheKey(this.clientId));
            }
        }
        /**
         * Helper to decrypt and save cache entries
         * @param key
         * @returns
         */
        async getItemFromEncryptedCache(key, correlationId) {
            if (!this.encryptionCookie) {
                return null;
            }
            const rawCache = this.getItem(key);
            if (!rawCache) {
                return null;
            }
            let encObj;
            try {
                encObj = JSON.parse(rawCache);
            }
            catch (e) {
                // Not a valid encrypted object, remove
                return null;
            }
            if (!isEncrypted(encObj)) {
                // Data is not encrypted
                this.performanceClient.incrementFields({ unencryptedCacheCount: 1 }, correlationId);
                return rawCache;
            }
            if (encObj.id !== this.encryptionCookie.id) {
                // Data was encrypted with a different key. It must be removed because it is from a previous session.
                this.performanceClient.incrementFields({ encryptedCacheExpiredCount: 1 }, correlationId);
                return null;
            }
            this.performanceClient.incrementFields({ encryptedCacheCount: 1 }, correlationId);
            return invokeAsync(decrypt, Decrypt, this.logger, this.performanceClient, correlationId)(this.encryptionCookie.key, encObj.nonce, this.getContext(key), encObj.data);
        }
        /**
         * Helper to decrypt and save an array of cache keys
         * @param arr
         * @returns Array of keys successfully imported
         */
        async importArray(arr, correlationId) {
            const importedArr = [];
            const promiseArr = [];
            arr.forEach((key) => {
                const promise = this.getItemFromEncryptedCache(key, correlationId).then((value) => {
                    if (value) {
                        this.memoryStorage.setItem(key, value);
                        importedArr.push(key);
                    }
                    else {
                        // If value is empty, unencrypted or expired remove
                        this.removeItem(key);
                    }
                });
                promiseArr.push(promise);
            });
            await Promise.all(promiseArr);
            return importedArr;
        }
        /**
         * Gets encryption context for a given cache entry. This is clientId for app specific entries, empty string for shared entries
         * @param key
         * @returns
         */
        getContext(key) {
            let context = "";
            if (key.includes(this.clientId)) {
                context = this.clientId; // Used to bind encryption key to this appId
            }
            return context;
        }
        updateCache(event, correlationId) {
            this.logger.trace("17cxcm", correlationId);
            const perfMeasurement = this.performanceClient.startMeasurement(LocalStorageUpdated);
            perfMeasurement.add({ isBackground: true });
            const { key, value, context } = event.data;
            if (!key) {
                this.logger.error("0e10qr", correlationId);
                perfMeasurement.end({ success: false, errorCode: "noKey" });
                return;
            }
            if (context && context !== this.clientId) {
                this.logger.trace("04rtdy", correlationId);
                perfMeasurement.end({
                    success: false,
                    errorCode: "contextMismatch",
                });
                return;
            }
            if (!value) {
                this.memoryStorage.removeItem(key);
                this.logger.verbose("04ypih", correlationId);
            }
            else {
                this.memoryStorage.setItem(key, value);
                this.logger.verbose("1vzsgt", correlationId);
            }
            perfMeasurement.end({ success: true });
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class SessionStorage {
        constructor() {
            if (!window.sessionStorage) {
                throw createBrowserConfigurationAuthError(storageNotSupported);
            }
        }
        async initialize() {
            // Session storage does not require initialization
        }
        getItem(key) {
            return window.sessionStorage.getItem(key);
        }
        getUserData(key) {
            return this.getItem(key);
        }
        setItem(key, value) {
            window.sessionStorage.setItem(key, value);
        }
        async setUserData(key, value) {
            this.setItem(key, value);
        }
        removeItem(key) {
            window.sessionStorage.removeItem(key);
        }
        getKeys() {
            return Object.keys(window.sessionStorage);
        }
        containsKey(key) {
            return window.sessionStorage.hasOwnProperty(key);
        }
        decryptData() {
            // Session storage does not support encryption, so this method is a no-op
            return Promise.resolve(null);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const EventType = {
        INITIALIZE_START: "msal:initializeStart",
        INITIALIZE_END: "msal:initializeEnd",
        ACTIVE_ACCOUNT_CHANGED: "msal:activeAccountChanged",
        LOGIN_SUCCESS: "msal:loginSuccess",
        ACQUIRE_TOKEN_START: "msal:acquireTokenStart",
        BROKERED_REQUEST_START: "msal:brokeredRequestStart",
        ACQUIRE_TOKEN_SUCCESS: "msal:acquireTokenSuccess",
        BROKERED_REQUEST_SUCCESS: "msal:brokeredRequestSuccess",
        ACQUIRE_TOKEN_FAILURE: "msal:acquireTokenFailure",
        BROKERED_REQUEST_FAILURE: "msal:brokeredRequestFailure",
        ACQUIRE_TOKEN_NETWORK_START: "msal:acquireTokenFromNetworkStart",
        HANDLE_REDIRECT_START: "msal:handleRedirectStart",
        HANDLE_REDIRECT_END: "msal:handleRedirectEnd",
        POPUP_OPENED: "msal:popupOpened",
        LOGOUT_START: "msal:logoutStart",
        LOGOUT_SUCCESS: "msal:logoutSuccess",
        LOGOUT_FAILURE: "msal:logoutFailure",
        LOGOUT_END: "msal:logoutEnd",
        RESTORE_FROM_BFCACHE: "msal:restoreFromBFCache",
        BROKER_CONNECTION_ESTABLISHED: "msal:brokerConnectionEstablished",
    };
 
    /* eslint-disable header/header */
    const name = "@azure/msal-browser";
    const version = "5.7.0";
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Utility function to remove an element from an array in place.
     * @param array - The array from which to remove the element.
     * @param element - The element to remove from the array.
     */
    function removeElementFromArray(array, element) {
        const index = array.indexOf(element);
        if (index > -1) {
            array.splice(index, 1);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This class implements the cache storage interface for MSAL through browser local or session storage.
     */
    class BrowserCacheManager extends CacheManager {
        constructor(clientId, cacheConfig, cryptoImpl, logger, performanceClient, eventHandler, staticAuthorityOptions) {
            super(clientId, cryptoImpl, logger, performanceClient, staticAuthorityOptions);
            this.cacheConfig = cacheConfig;
            this.logger = logger;
            this.internalStorage = new MemoryStorage();
            this.browserStorage = getStorageImplementation(clientId, cacheConfig.cacheLocation, logger, performanceClient);
            this.temporaryCacheStorage = getStorageImplementation(clientId, BrowserCacheLocation.SessionStorage, logger, performanceClient);
            this.cookieStorage = new CookieStorage();
            this.eventHandler = eventHandler;
        }
        async initialize(correlationId) {
            this.performanceClient.addFields({
                cacheLocation: this.cacheConfig.cacheLocation,
                cacheRetentionDays: this.cacheConfig.cacheRetentionDays,
            }, correlationId);
            await this.browserStorage.initialize(correlationId);
            await this.migrateExistingCache(correlationId);
            this.trackVersionChanges(correlationId);
        }
        /**
         * Migrates any existing cache data from previous versions of MSAL.js into the current cache structure.
         */
        async migrateExistingCache(correlationId) {
            let accountKeys = getAccountKeys(this.browserStorage);
            let tokenKeys = getTokenKeys(this.clientId, this.browserStorage);
            this.performanceClient.addFields({
                preMigrateAcntCount: accountKeys.length,
                preMigrateATCount: tokenKeys.accessToken.length,
                preMigrateITCount: tokenKeys.idToken.length,
                preMigrateRTCount: tokenKeys.refreshToken.length,
            }, correlationId);
            for (let i = 0; i < ACCOUNT_SCHEMA_VERSION; i++) {
                const credentialSchema = i; // For now account and credential schemas are the same, but may diverge in future
                await this.removeStaleAccounts(i, credentialSchema, correlationId);
            }
            // Must migrate idTokens first to ensure we have KMSI info for the rest
            for (let i = 0; i < CREDENTIAL_SCHEMA_VERSION; i++) {
                const accountSchema = i; // For now account and credential schemas are the same, but may diverge in future
                await this.migrateIdTokens(i, accountSchema, correlationId);
            }
            const kmsiMap = this.getKMSIValues();
            for (let i = 0; i < CREDENTIAL_SCHEMA_VERSION; i++) {
                await this.migrateAccessTokens(i, kmsiMap, correlationId);
                await this.migrateRefreshTokens(i, kmsiMap, correlationId);
            }
            accountKeys = getAccountKeys(this.browserStorage);
            tokenKeys = getTokenKeys(this.clientId, this.browserStorage);
            this.performanceClient.addFields({
                postMigrateAcntCount: accountKeys.length,
                postMigrateATCount: tokenKeys.accessToken.length,
                postMigrateITCount: tokenKeys.idToken.length,
                postMigrateRTCount: tokenKeys.refreshToken.length,
            }, correlationId);
        }
        /**
         * Parses entry, adds lastUpdatedAt if it doesn't exist, removes entry if expired or invalid
         * @param key
         * @param correlationId
         * @returns
         */
        async updateOldEntry(key, correlationId) {
            const rawValue = this.browserStorage.getItem(key);
            const parsedValue = this.validateAndParseJson(rawValue || "");
            if (!parsedValue) {
                this.browserStorage.removeItem(key);
                return null;
            }
            if (!parsedValue.lastUpdatedAt) {
                // Add lastUpdatedAt to the existing v0 entry if it doesnt exist so we know when it's safe to remove it
                parsedValue.lastUpdatedAt = Date.now().toString();
                this.setItem(key, JSON.stringify(parsedValue), correlationId);
            }
            else if (isCacheExpired(parsedValue.lastUpdatedAt, this.cacheConfig.cacheRetentionDays)) {
                this.browserStorage.removeItem(key);
                this.performanceClient.incrementFields({ expiredCacheRemovedCount: 1 }, correlationId);
                return null;
            }
            const decryptedData = isEncrypted(parsedValue)
                ? await this.browserStorage.decryptData(key, parsedValue, correlationId)
                : parsedValue;
            if (!decryptedData || !isCredentialEntity(decryptedData)) {
                this.performanceClient.incrementFields({ invalidCacheCount: 1 }, correlationId);
                return null;
            }
            if ((isAccessTokenEntity(decryptedData) ||
                isRefreshTokenEntity(decryptedData)) &&
                decryptedData.expiresOn &&
                isTokenExpired(decryptedData.expiresOn, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC)) {
                this.browserStorage.removeItem(key);
                this.performanceClient.incrementFields({ expiredCacheRemovedCount: 1 }, correlationId);
                return null;
            }
            return decryptedData;
        }
        /**
         * Remove accounts from the cache for older schema versions if they have not been updated in the last cacheRetentionDays
         * @param accountSchema
         * @param credentialSchema
         * @param correlationId
         * @returns
         */
        async removeStaleAccounts(accountSchema, credentialSchema, correlationId) {
            const accountKeysToCheck = getAccountKeys(this.browserStorage, accountSchema);
            if (accountKeysToCheck.length === 0) {
                return;
            }
            for (const accountKey of [...accountKeysToCheck]) {
                this.performanceClient.incrementFields({ oldAcntCount: 1 }, correlationId);
                const rawValue = this.browserStorage.getItem(accountKey);
                const parsedValue = this.validateAndParseJson(rawValue || "");
                if (!parsedValue) {
                    removeElementFromArray(accountKeysToCheck, accountKey);
                    continue;
                }
                if (!parsedValue.lastUpdatedAt) {
                    // Add lastUpdatedAt to the existing entry if it doesnt exist so we know when it's safe to remove it
                    parsedValue.lastUpdatedAt = Date.now().toString();
                    this.setItem(accountKey, JSON.stringify(parsedValue), correlationId);
                    continue;
                }
                else if (isCacheExpired(parsedValue.lastUpdatedAt, this.cacheConfig.cacheRetentionDays)) {
                    // Cache expired remove account and associated tokens
                    await this.removeAccountOldSchema(accountKey, parsedValue, credentialSchema, correlationId);
                    removeElementFromArray(accountKeysToCheck, accountKey);
                }
            }
            this.setAccountKeys(accountKeysToCheck, correlationId, accountSchema);
        }
        /**
         * Remove the given account and all associated tokens from the cache
         * @param accountKey
         * @param rawObject
         * @param credentialSchema
         * @param correlationId
         */
        async removeAccountOldSchema(accountKey, rawObject, credentialSchema, correlationId) {
            const decryptedData = isEncrypted(rawObject)
                ? (await this.browserStorage.decryptData(accountKey, rawObject, correlationId))
                : rawObject;
            const homeAccountId = decryptedData?.homeAccountId;
            if (homeAccountId) {
                const tokenKeys = this.getTokenKeys(credentialSchema);
                [...tokenKeys.idToken]
                    .filter((key) => key.includes(homeAccountId))
                    .forEach((key) => {
                    this.browserStorage.removeItem(key);
                    removeElementFromArray(tokenKeys.idToken, key);
                });
                [...tokenKeys.accessToken]
                    .filter((key) => key.includes(homeAccountId))
                    .forEach((key) => {
                    this.browserStorage.removeItem(key);
                    removeElementFromArray(tokenKeys.accessToken, key);
                });
                [...tokenKeys.refreshToken]
                    .filter((key) => key.includes(homeAccountId))
                    .forEach((key) => {
                    this.browserStorage.removeItem(key);
                    removeElementFromArray(tokenKeys.refreshToken, key);
                });
                this.setTokenKeys(tokenKeys, correlationId, credentialSchema);
            }
            this.performanceClient.incrementFields({ expiredAcntRemovedCount: 1 }, correlationId);
            this.browserStorage.removeItem(accountKey);
        }
        /**
         * Gets key value pair mapping homeAccountId to KMSI value
         * @returns
         */
        getKMSIValues() {
            const kmsiMap = {};
            const tokenKeys = this.getTokenKeys().idToken;
            for (const key of tokenKeys) {
                const rawValue = this.browserStorage.getUserData(key);
                if (rawValue) {
                    const idToken = JSON.parse(rawValue);
                    const claims = extractTokenClaims(idToken.secret, base64Decode);
                    if (claims) {
                        kmsiMap[idToken.homeAccountId] = isKmsi(claims);
                    }
                }
            }
            return kmsiMap;
        }
        /**
         * Migrates id tokens from the old schema to the new schema, also migrates associated account object if it doesn't already exist in the new schema
         * @param credentialSchema
         * @param accountSchema
         * @param correlationId
         * @returns
         */
        async migrateIdTokens(credentialSchema, accountSchema, correlationId) {
            const credentialKeysToMigrate = getTokenKeys(this.clientId, this.browserStorage, credentialSchema);
            if (credentialKeysToMigrate.idToken.length === 0) {
                return;
            }
            const currentCredentialKeys = getTokenKeys(this.clientId, this.browserStorage, CREDENTIAL_SCHEMA_VERSION);
            const currentAccountKeys = getAccountKeys(this.browserStorage);
            const previousAccountKeys = getAccountKeys(this.browserStorage, accountSchema);
            for (const idTokenKey of [...credentialKeysToMigrate.idToken]) {
                this.performanceClient.incrementFields({ oldITCount: 1 }, correlationId);
                const oldSchemaData = (await this.updateOldEntry(idTokenKey, correlationId));
                if (!oldSchemaData) {
                    removeElementFromArray(credentialKeysToMigrate.idToken, idTokenKey);
                    continue;
                }
                const currentAccountKey = currentAccountKeys.find((key) => key.includes(oldSchemaData.homeAccountId));
                const previousAccountKey = previousAccountKeys.find((key) => key.includes(oldSchemaData.homeAccountId));
                let account = null;
                if (currentAccountKey) {
                    account = this.getAccount(currentAccountKey, correlationId);
                }
                else if (previousAccountKey) {
                    const rawValue = this.browserStorage.getItem(previousAccountKey);
                    const parsedValue = this.validateAndParseJson(rawValue || "");
                    account =
                        parsedValue && isEncrypted(parsedValue)
                            ? (await this.browserStorage.decryptData(previousAccountKey, parsedValue, correlationId))
                            : parsedValue;
                }
                if (!account) {
                    // Don't migrate idToken if we don't have an account for it
                    this.performanceClient.incrementFields({ skipITMigrateCount: 1 }, correlationId);
                    continue;
                }
                const claims = extractTokenClaims(oldSchemaData.secret, base64Decode);
                const newIdTokenKey = this.generateCredentialKey(oldSchemaData);
                const currentIdToken = this.getIdTokenCredential(newIdTokenKey, correlationId);
                const oldTokenHasSignInState = Object.keys(claims).includes("signin_state");
                const currentTokenHasSignInState = currentIdToken &&
                    Object.keys(extractTokenClaims(currentIdToken.secret, base64Decode) || {}).includes("signin_state");
                /**
                 * Only migrate if:
                 * 1. Token doesn't yet exist in current schema
                 * 2. Old schema token has been updated more recently than the current one AND migrating it won't result in loss of KMSI state
                 */
                if (!currentIdToken ||
                    (oldSchemaData.lastUpdatedAt > currentIdToken.lastUpdatedAt &&
                        (oldTokenHasSignInState || !currentTokenHasSignInState))) {
                    const tenantProfiles = account.tenantProfiles || [];
                    const tenantId = getTenantIdFromIdTokenClaims(claims) || account.realm;
                    if (tenantId &&
                        !tenantProfiles.find((tenantProfile) => {
                            return tenantProfile.tenantId === tenantId;
                        })) {
                        const newTenantProfile = buildTenantProfile(account.homeAccountId, account.localAccountId, tenantId, claims);
                        tenantProfiles.push(newTenantProfile);
                    }
                    account.tenantProfiles = tenantProfiles;
                    const newAccountKey = this.generateAccountKey(getAccountInfo(account));
                    const kmsi = isKmsi(claims);
                    await this.setUserData(newAccountKey, JSON.stringify(account), correlationId, account.lastUpdatedAt, kmsi);
                    if (!currentAccountKeys.includes(newAccountKey)) {
                        currentAccountKeys.push(newAccountKey);
                    }
                    await this.setUserData(newIdTokenKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
                    this.performanceClient.incrementFields({ migratedITCount: 1 }, correlationId);
                    currentCredentialKeys.idToken.push(newIdTokenKey);
                }
            }
            this.setTokenKeys(credentialKeysToMigrate, correlationId, credentialSchema);
            this.setTokenKeys(currentCredentialKeys, correlationId);
            this.setAccountKeys(currentAccountKeys, correlationId);
        }
        /**
         * Migrates access tokens from old cache schema to current schema
         * @param credentialSchema
         * @param kmsiMap
         * @param correlationId
         * @returns
         */
        async migrateAccessTokens(credentialSchema, kmsiMap, correlationId) {
            const credentialKeysToMigrate = getTokenKeys(this.clientId, this.browserStorage, credentialSchema);
            if (credentialKeysToMigrate.accessToken.length === 0) {
                return;
            }
            const currentCredentialKeys = getTokenKeys(this.clientId, this.browserStorage, CREDENTIAL_SCHEMA_VERSION);
            for (const accessTokenKey of [...credentialKeysToMigrate.accessToken]) {
                this.performanceClient.incrementFields({ oldATCount: 1 }, correlationId);
                const oldSchemaData = (await this.updateOldEntry(accessTokenKey, correlationId));
                if (!oldSchemaData) {
                    removeElementFromArray(credentialKeysToMigrate.accessToken, accessTokenKey);
                    continue;
                }
                if (!(oldSchemaData.homeAccountId in kmsiMap)) {
                    // Don't migrate tokens if we don't have an idToken for them
                    this.performanceClient.incrementFields({ skipATMigrateCount: 1 }, correlationId);
                    continue;
                }
                const newKey = this.generateCredentialKey(oldSchemaData);
                const kmsi = kmsiMap[oldSchemaData.homeAccountId];
                if (!currentCredentialKeys.accessToken.includes(newKey)) {
                    await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
                    this.performanceClient.incrementFields({ migratedATCount: 1 }, correlationId);
                    currentCredentialKeys.accessToken.push(newKey);
                }
                else {
                    const currentToken = this.getAccessTokenCredential(newKey, correlationId);
                    if (!currentToken ||
                        oldSchemaData.lastUpdatedAt > currentToken.lastUpdatedAt) {
                        // If the token already exists, only overwrite it if the old token has a more recent lastUpdatedAt
                        await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
                        this.performanceClient.incrementFields({ migratedATCount: 1 }, correlationId);
                    }
                }
            }
            this.setTokenKeys(credentialKeysToMigrate, correlationId, credentialSchema);
            this.setTokenKeys(currentCredentialKeys, correlationId);
        }
        /**
         * Migrates refresh tokens from old cache schema to current schema
         * @param credentialSchema
         * @param kmsiMap
         * @param correlationId
         * @returns
         */
        async migrateRefreshTokens(credentialSchema, kmsiMap, correlationId) {
            const credentialKeysToMigrate = getTokenKeys(this.clientId, this.browserStorage, credentialSchema);
            if (credentialKeysToMigrate.refreshToken.length === 0) {
                return;
            }
            const currentCredentialKeys = getTokenKeys(this.clientId, this.browserStorage, CREDENTIAL_SCHEMA_VERSION);
            for (const refreshTokenKey of [
                ...credentialKeysToMigrate.refreshToken,
            ]) {
                this.performanceClient.incrementFields({ oldRTCount: 1 }, correlationId);
                const oldSchemaData = (await this.updateOldEntry(refreshTokenKey, correlationId));
                if (!oldSchemaData) {
                    removeElementFromArray(credentialKeysToMigrate.refreshToken, refreshTokenKey);
                    continue;
                }
                if (!(oldSchemaData.homeAccountId in kmsiMap)) {
                    // Don't migrate tokens if we don't have an idToken for them
                    this.performanceClient.incrementFields({ skipRTMigrateCount: 1 }, correlationId);
                    continue;
                }
                const newKey = this.generateCredentialKey(oldSchemaData);
                const kmsi = kmsiMap[oldSchemaData.homeAccountId];
                if (!currentCredentialKeys.refreshToken.includes(newKey)) {
                    await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
                    this.performanceClient.incrementFields({ migratedRTCount: 1 }, correlationId);
                    currentCredentialKeys.refreshToken.push(newKey);
                }
                else {
                    const currentToken = this.getRefreshTokenCredential(newKey, correlationId);
                    if (!currentToken ||
                        oldSchemaData.lastUpdatedAt > currentToken.lastUpdatedAt) {
                        // If the token already exists, only overwrite it if the old token has a more recent lastUpdatedAt
                        await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
                        this.performanceClient.incrementFields({ migratedRTCount: 1 }, correlationId);
                    }
                }
            }
            this.setTokenKeys(credentialKeysToMigrate, correlationId, credentialSchema);
            this.setTokenKeys(currentCredentialKeys, correlationId);
        }
        /**
         * Tracks upgrades and downgrades for telemetry and debugging purposes
         */
        trackVersionChanges(correlationId) {
            const previousVersion = this.browserStorage.getItem(VERSION_CACHE_KEY);
            if (previousVersion) {
                this.logger.info("1wuc87", correlationId);
                this.performanceClient.addFields({ previousLibraryVersion: previousVersion }, correlationId);
            }
            if (previousVersion !== version) {
                this.setItem(VERSION_CACHE_KEY, version, correlationId);
            }
        }
        /**
         * Parses passed value as JSON object, JSON.parse() will throw an error.
         * @param input
         */
        validateAndParseJson(jsonValue) {
            if (!jsonValue) {
                return null;
            }
            try {
                const parsedJson = JSON.parse(jsonValue);
                /**
                 * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object
                 * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check
                 * of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
                 *
                 */
                return parsedJson && typeof parsedJson === "object"
                    ? parsedJson
                    : null;
            }
            catch (error) {
                return null;
            }
        }
        /**
         * Helper to setItem in browser storage, with cleanup in case of quota errors
         * @param key
         * @param value
         */
        setItem(key, value, correlationId) {
            const tokenKeysCount = new Array(CREDENTIAL_SCHEMA_VERSION + 1).fill(0); // Array mapping schema version to number of token keys stored for that version
            const accessTokenKeys = []; // Flat map of all access token keys stored, ordered by schema version
            const maxRetries = 20;
            for (let i = 0; i <= maxRetries; i++) {
                // Attempt to store item in cache, if cache is full this call will throw and we'll attempt to clear space by removing access tokens from the cache one by one, starting with tokens stored by previous versions of MSAL.js
                try {
                    this.browserStorage.setItem(key, value);
                    if (i > 0) {
                        // If any tokens were removed in order to store this item update the token keys array with the tokens removed
                        for (let schemaVersion = 0; schemaVersion <= CREDENTIAL_SCHEMA_VERSION; schemaVersion++) {
                            // Get the sum of all previous token counts to use as start index for this schema version
                            const startIndex = tokenKeysCount
                                .slice(0, schemaVersion)
                                .reduce((sum, count) => sum + count, 0);
                            if (startIndex >= i) {
                                // Done removing tokens
                                break;
                            }
                            const endIndex = i > startIndex + tokenKeysCount[schemaVersion]
                                ? startIndex + tokenKeysCount[schemaVersion]
                                : i;
                            if (i > startIndex &&
                                tokenKeysCount[schemaVersion] > 0) {
                                this.removeAccessTokenKeys(accessTokenKeys.slice(startIndex, endIndex), correlationId, schemaVersion);
                            }
                        }
                    }
                    break; // If setItem succeeds, exit the loop
                }
                catch (e) {
                    const cacheError = createCacheError(e);
                    if (cacheError.errorCode ===
                        cacheQuotaExceeded &&
                        i < maxRetries) {
                        if (!accessTokenKeys.length) {
                            // If we are currently trying to set the token keys, use the value we're trying to set
                            for (let i = 0; i <= CREDENTIAL_SCHEMA_VERSION; i++) {
                                if (key ===
                                    getTokenKeysCacheKey(this.clientId, i)) {
                                    const tokenKeys = JSON.parse(value).accessToken;
                                    accessTokenKeys.push(...tokenKeys);
                                    tokenKeysCount[i] = tokenKeys.length;
                                }
                                else {
                                    const tokenKeys = this.getTokenKeys(i).accessToken;
                                    accessTokenKeys.push(...tokenKeys);
                                    tokenKeysCount[i] = tokenKeys.length;
                                }
                            }
                        }
                        if (accessTokenKeys.length <= i) {
                            // Nothing to remove, rethrow the error
                            throw cacheError;
                        }
                        // When cache quota is exceeded, start removing access tokens until we can successfully set the item
                        this.removeAccessToken(accessTokenKeys[i], correlationId, false // Don't save token keys yet, do it at the end
                        );
                    }
                    else {
                        // If the error is not a quota exceeded error, rethrow it
                        throw cacheError;
                    }
                }
            }
        }
        /**
         * Helper to setUserData in browser storage, with cleanup in case of quota errors
         * @param key
         * @param value
         * @param correlationId
         */
        async setUserData(key, value, correlationId, timestamp, kmsi) {
            const tokenKeysCount = new Array(CREDENTIAL_SCHEMA_VERSION + 1).fill(0); // Array mapping schema version to number of token keys stored for that version
            const accessTokenKeys = []; // Flat map of all access token keys stored, ordered by schema version
            const maxRetries = 20;
            for (let i = 0; i <= maxRetries; i++) {
                try {
                    // Attempt to store item in cache, if cache is full this call will throw and we'll attempt to clear space by removing access tokens from the cache one by one, starting with tokens stored by previous versions of MSAL.js
                    await invokeAsync(this.browserStorage.setUserData.bind(this.browserStorage), SetUserData, this.logger, this.performanceClient, correlationId)(key, value, correlationId, timestamp, kmsi);
                    if (i > 0) {
                        // If any tokens were removed in order to store this item update the token keys array with the tokens removed
                        for (let schemaVersion = 0; schemaVersion <= CREDENTIAL_SCHEMA_VERSION; schemaVersion++) {
                            // Get the sum of all previous token counts to use as start index for this schema version
                            const startIndex = tokenKeysCount
                                .slice(0, schemaVersion)
                                .reduce((sum, count) => sum + count, 0);
                            if (startIndex >= i) {
                                // Done removing tokens
                                break;
                            }
                            const endIndex = i > startIndex + tokenKeysCount[schemaVersion]
                                ? startIndex + tokenKeysCount[schemaVersion]
                                : i;
                            if (i > startIndex &&
                                tokenKeysCount[schemaVersion] > 0) {
                                this.removeAccessTokenKeys(accessTokenKeys.slice(startIndex, endIndex), correlationId, schemaVersion);
                            }
                        }
                    }
                    break; // If setItem succeeds, exit the loop
                }
                catch (e) {
                    const cacheError = createCacheError(e);
                    if (cacheError.errorCode ===
                        cacheQuotaExceeded &&
                        i < maxRetries) {
                        if (!accessTokenKeys.length) {
                            // If we are currently trying to set the token keys, use the value we're trying to set
                            for (let i = 0; i <= CREDENTIAL_SCHEMA_VERSION; i++) {
                                const tokenKeys = this.getTokenKeys(i).accessToken;
                                accessTokenKeys.push(...tokenKeys);
                                tokenKeysCount[i] = tokenKeys.length;
                            }
                        }
                        if (accessTokenKeys.length <= i) {
                            // Nothing left to remove, rethrow the error
                            throw cacheError;
                        }
                        // When cache quota is exceeded, start removing access tokens until we can successfully set the item
                        this.removeAccessToken(accessTokenKeys[i], correlationId, false // Don't save token keys yet, do it at the end
                        );
                    }
                    else {
                        // If the error is not a quota exceeded error, rethrow it
                        throw cacheError;
                    }
                }
            }
        }
        /**
         * Reads account from cache, deserializes it into an account entity and returns it.
         * If account is not found from the key, returns null and removes key from map.
         * @param accountKey
         * @returns
         */
        getAccount(accountKey, correlationId) {
            this.logger.trace("1lfvm6", correlationId);
            const serializedAccount = this.browserStorage.getUserData(accountKey);
            if (!serializedAccount) {
                this.removeAccountKeyFromMap(accountKey, correlationId);
                return null;
            }
            const parsedAccount = this.validateAndParseJson(serializedAccount);
            if (!parsedAccount ||
                !isAccountEntity(parsedAccount)) {
                return null;
            }
            const account = CacheManager.toObject({}, parsedAccount);
            this.performanceClient.addFields({
                accountCachedBy: apiIdToName(account.cachedByApiId),
            }, correlationId);
            return account;
        }
        /**
         * set account entity in the platform cache
         * @param account
         */
        async setAccount(account, correlationId, kmsi, apiId) {
            this.logger.trace("1bz3wr", correlationId);
            const key = this.generateAccountKey(getAccountInfo(account));
            const timestamp = Date.now().toString();
            account.lastUpdatedAt = timestamp;
            account.cachedByApiId = apiId;
            await this.setUserData(key, JSON.stringify(account), correlationId, timestamp, kmsi);
            this.addAccountKeyToMap(key, correlationId);
            this.performanceClient.addFields({ kmsi: kmsi }, correlationId);
        }
        setAccountKeys(accountKeys, correlationId, schemaVersion = ACCOUNT_SCHEMA_VERSION) {
            if (accountKeys.length === 0) {
                this.removeItem(getAccountKeysCacheKey(schemaVersion));
            }
            else {
                this.setItem(getAccountKeysCacheKey(schemaVersion), JSON.stringify(accountKeys), correlationId);
            }
        }
        /**
         * Returns the array of account keys currently cached
         * @returns
         */
        getAccountKeys() {
            return getAccountKeys(this.browserStorage);
        }
        /**
         * Add a new account to the key map
         * @param key
         */
        addAccountKeyToMap(key, correlationId) {
            this.logger.trace("0rb85k", correlationId);
            this.logger.tracePii("1l9bdo", correlationId);
            const accountKeys = this.getAccountKeys();
            if (accountKeys.indexOf(key) === -1) {
                // Only add key if it does not already exist in the map
                accountKeys.push(key);
                this.setItem(getAccountKeysCacheKey(), JSON.stringify(accountKeys), correlationId);
                this.logger.verbose("0xia39", correlationId);
                return true;
            }
            else {
                this.logger.verbose("0161kk", correlationId);
                return false;
            }
        }
        /**
         * Remove an account from the key map
         * @param key
         */
        removeAccountKeyFromMap(key, correlationId) {
            this.logger.trace("1jpigu", correlationId);
            this.logger.tracePii("1xzspl", correlationId);
            const accountKeys = this.getAccountKeys();
            const removalIndex = accountKeys.indexOf(key);
            if (removalIndex > -1) {
                accountKeys.splice(removalIndex, 1);
                this.setAccountKeys(accountKeys, correlationId);
            }
            else {
                this.logger.trace("1dytu2", correlationId);
            }
        }
        /**
         * Extends inherited removeAccount function to include removal of the account key from the map
         * @param key
         */
        removeAccount(account, correlationId) {
            const activeAccount = this.getActiveAccount(correlationId);
            if (activeAccount?.homeAccountId === account.homeAccountId &&
                activeAccount?.environment === account.environment) {
                this.setActiveAccount(null, correlationId);
            }
            super.removeAccount(account, correlationId);
            this.removeAccountKeyFromMap(this.generateAccountKey(account), correlationId);
            // Remove all other associated cache items
            this.browserStorage.getKeys().forEach((key) => {
                if (key.includes(account.homeAccountId) &&
                    key.includes(account.environment)) {
                    this.browserStorage.removeItem(key);
                }
            });
        }
        /**
         * Removes given idToken from the cache and from the key map
         * @param key
         */
        removeIdToken(key, correlationId) {
            super.removeIdToken(key, correlationId);
            const tokenKeys = this.getTokenKeys();
            const idRemoval = tokenKeys.idToken.indexOf(key);
            if (idRemoval > -1) {
                this.logger.info("05udv9", correlationId);
                tokenKeys.idToken.splice(idRemoval, 1);
                this.setTokenKeys(tokenKeys, correlationId);
            }
        }
        /**
         * Removes given accessToken from the cache and from the key map
         * @param key
         */
        removeAccessToken(key, correlationId, updateTokenKeys = true) {
            super.removeAccessToken(key, correlationId);
            updateTokenKeys && this.removeAccessTokenKeys([key], correlationId);
        }
        /**
         * Remove access token key from the key map
         * @param key
         * @param correlationId
         * @param tokenKeys
         */
        removeAccessTokenKeys(keys, correlationId, schemaVersion = CREDENTIAL_SCHEMA_VERSION) {
            this.logger.trace("17o18n", correlationId);
            const tokenKeys = this.getTokenKeys(schemaVersion);
            let keysRemoved = 0;
            keys.forEach((key) => {
                const accessRemoval = tokenKeys.accessToken.indexOf(key);
                if (accessRemoval > -1) {
                    tokenKeys.accessToken.splice(accessRemoval, 1);
                    keysRemoved++;
                }
            });
            if (keysRemoved > 0) {
                this.logger.info("15i5d5", correlationId);
                this.setTokenKeys(tokenKeys, correlationId, schemaVersion);
                return;
            }
        }
        /**
         * Removes given refreshToken from the cache and from the key map
         * @param key
         */
        removeRefreshToken(key, correlationId) {
            super.removeRefreshToken(key, correlationId);
            const tokenKeys = this.getTokenKeys();
            const refreshRemoval = tokenKeys.refreshToken.indexOf(key);
            if (refreshRemoval > -1) {
                this.logger.info("1f4fq3", correlationId);
                tokenKeys.refreshToken.splice(refreshRemoval, 1);
                this.setTokenKeys(tokenKeys, correlationId);
            }
        }
        /**
         * Gets the keys for the cached tokens associated with this clientId
         * @returns
         */
        getTokenKeys(schemaVersion = CREDENTIAL_SCHEMA_VERSION) {
            return getTokenKeys(this.clientId, this.browserStorage, schemaVersion);
        }
        /**
         * Sets the token keys in the cache
         * @param tokenKeys
         * @param correlationId
         * @returns
         */
        setTokenKeys(tokenKeys, correlationId, schemaVersion = CREDENTIAL_SCHEMA_VERSION) {
            if (tokenKeys.idToken.length === 0 &&
                tokenKeys.accessToken.length === 0 &&
                tokenKeys.refreshToken.length === 0) {
                // If no keys left, remove the map
                this.removeItem(getTokenKeysCacheKey(this.clientId, schemaVersion));
                return;
            }
            else {
                this.setItem(getTokenKeysCacheKey(this.clientId, schemaVersion), JSON.stringify(tokenKeys), correlationId);
            }
        }
        /**
         * generates idToken entity from a string
         * @param idTokenKey
         */
        getIdTokenCredential(idTokenKey, correlationId) {
            const value = this.browserStorage.getUserData(idTokenKey);
            if (!value) {
                this.logger.trace("1jukz6", correlationId);
                this.removeIdToken(idTokenKey, correlationId);
                return null;
            }
            const parsedIdToken = this.validateAndParseJson(value);
            if (!parsedIdToken || !isIdTokenEntity(parsedIdToken)) {
                this.logger.trace("1jukz6", correlationId);
                return null;
            }
            this.logger.trace("01ju66", correlationId);
            return parsedIdToken;
        }
        /**
         * set IdToken credential to the platform cache
         * @param idToken
         */
        async setIdTokenCredential(idToken, correlationId, kmsi) {
            this.logger.trace("13hjll", correlationId);
            const idTokenKey = this.generateCredentialKey(idToken);
            const timestamp = Date.now().toString();
            idToken.lastUpdatedAt = timestamp;
            await this.setUserData(idTokenKey, JSON.stringify(idToken), correlationId, timestamp, kmsi);
            const tokenKeys = this.getTokenKeys();
            if (tokenKeys.idToken.indexOf(idTokenKey) === -1) {
                this.logger.info("07jy92", correlationId);
                tokenKeys.idToken.push(idTokenKey);
                this.setTokenKeys(tokenKeys, correlationId);
            }
        }
        /**
         * generates accessToken entity from a string
         * @param key
         */
        getAccessTokenCredential(accessTokenKey, correlationId) {
            const value = this.browserStorage.getUserData(accessTokenKey);
            if (!value) {
                this.logger.trace("0bqvx8", correlationId);
                this.removeAccessTokenKeys([accessTokenKey], correlationId);
                return null;
            }
            const parsedAccessToken = this.validateAndParseJson(value);
            if (!parsedAccessToken ||
                !isAccessTokenEntity(parsedAccessToken)) {
                this.logger.trace("0bqvx8", correlationId);
                return null;
            }
            this.logger.trace("1o81rl", correlationId);
            return parsedAccessToken;
        }
        /**
         * set accessToken credential to the platform cache
         * @param accessToken
         */
        async setAccessTokenCredential(accessToken, correlationId, kmsi) {
            this.logger.trace("1pondb", correlationId);
            const accessTokenKey = this.generateCredentialKey(accessToken);
            const timestamp = Date.now().toString();
            accessToken.lastUpdatedAt = timestamp;
            await this.setUserData(accessTokenKey, JSON.stringify(accessToken), correlationId, timestamp, kmsi);
            const tokenKeys = this.getTokenKeys();
            const index = tokenKeys.accessToken.indexOf(accessTokenKey);
            if (index !== -1) {
                tokenKeys.accessToken.splice(index, 1); // Remove existing key before pushing to the end
            }
            this.logger.trace("1onhey", correlationId);
            tokenKeys.accessToken.push(accessTokenKey);
            this.setTokenKeys(tokenKeys, correlationId);
        }
        /**
         * generates refreshToken entity from a string
         * @param refreshTokenKey
         */
        getRefreshTokenCredential(refreshTokenKey, correlationId) {
            const value = this.browserStorage.getUserData(refreshTokenKey);
            if (!value) {
                this.logger.trace("0jlizt", correlationId);
                this.removeRefreshToken(refreshTokenKey, correlationId);
                return null;
            }
            const parsedRefreshToken = this.validateAndParseJson(value);
            if (!parsedRefreshToken ||
                !isRefreshTokenEntity(parsedRefreshToken)) {
                this.logger.trace("0jlizt", correlationId);
                return null;
            }
            this.logger.trace("0nokxi", correlationId);
            return parsedRefreshToken;
        }
        /**
         * set refreshToken credential to the platform cache
         * @param refreshToken
         */
        async setRefreshTokenCredential(refreshToken, correlationId, kmsi) {
            this.logger.trace("0tcg8d", correlationId);
            const refreshTokenKey = this.generateCredentialKey(refreshToken);
            const timestamp = Date.now().toString();
            refreshToken.lastUpdatedAt = timestamp;
            await this.setUserData(refreshTokenKey, JSON.stringify(refreshToken), correlationId, timestamp, kmsi);
            const tokenKeys = this.getTokenKeys();
            if (tokenKeys.refreshToken.indexOf(refreshTokenKey) === -1) {
                this.logger.info("0eckjs", correlationId);
                tokenKeys.refreshToken.push(refreshTokenKey);
                this.setTokenKeys(tokenKeys, correlationId);
            }
        }
        /**
         * fetch appMetadata entity from the platform cache
         * @param appMetadataKey
         * @param correlationId
         */
        getAppMetadata(appMetadataKey, correlationId) {
            const value = this.browserStorage.getItem(appMetadataKey);
            if (!value) {
                this.logger.trace("1q101h", correlationId);
                return null;
            }
            const parsedMetadata = this.validateAndParseJson(value);
            if (!parsedMetadata ||
                !isAppMetadataEntity(appMetadataKey, parsedMetadata)) {
                this.logger.trace("1q101h", correlationId);
                return null;
            }
            this.logger.trace("19pvg2", correlationId);
            return parsedMetadata;
        }
        /**
         * set appMetadata entity to the platform cache
         * @param appMetadata
         * @param correlationId
         */
        setAppMetadata(appMetadata, correlationId) {
            this.logger.trace("0cyma6", correlationId);
            const appMetadataKey = generateAppMetadataKey(appMetadata);
            this.setItem(appMetadataKey, JSON.stringify(appMetadata), correlationId);
        }
        /**
         * fetch server telemetry entity from the platform cache
         * @param serverTelemetryKey
         * @param correlationId
         */
        getServerTelemetry(serverTelemetryKey, correlationId) {
            const value = this.browserStorage.getItem(serverTelemetryKey);
            if (!value) {
                this.logger.trace("0jk19c", correlationId);
                return null;
            }
            const parsedEntity = this.validateAndParseJson(value);
            if (!parsedEntity ||
                !isServerTelemetryEntity(serverTelemetryKey, parsedEntity)) {
                this.logger.trace("0jk19c", correlationId);
                return null;
            }
            this.logger.trace("12jguk", correlationId);
            return parsedEntity;
        }
        /**
         * set server telemetry entity to the platform cache
         * @param serverTelemetryKey
         * @param serverTelemetry
         */
        setServerTelemetry(serverTelemetryKey, serverTelemetry, correlationId) {
            this.logger.trace("1poh61", correlationId);
            this.setItem(serverTelemetryKey, JSON.stringify(serverTelemetry), correlationId);
        }
        /**
         *
         */
        getAuthorityMetadata(key, correlationId) {
            const value = this.internalStorage.getItem(key);
            if (!value) {
                this.logger.trace("1r39oe", correlationId);
                return null;
            }
            const parsedMetadata = this.validateAndParseJson(value);
            if (parsedMetadata &&
                isAuthorityMetadataEntity(key, parsedMetadata)) {
                this.logger.trace("1ohvk3", correlationId);
                return parsedMetadata;
            }
            return null;
        }
        /**
         *
         */
        getAuthorityMetadataKeys() {
            const allKeys = this.internalStorage.getKeys();
            return allKeys.filter((key) => {
                return this.isAuthorityMetadata(key);
            });
        }
        /**
         * Sets wrapper metadata in memory
         * @param wrapperSKU
         * @param wrapperVersion
         */
        setWrapperMetadata(wrapperSKU, wrapperVersion) {
            this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_SKU, wrapperSKU);
            this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_VER, wrapperVersion);
        }
        /**
         * Returns wrapper metadata from in-memory storage
         */
        getWrapperMetadata() {
            const sku = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_SKU) || "";
            const version = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_VER) || "";
            return [sku, version];
        }
        /**
         *
         * @param key
         * @param entity
         * @param correlationId
         */
        setAuthorityMetadata(key, entity, correlationId) {
            this.logger.trace("07w8n2", correlationId);
            this.internalStorage.setItem(key, JSON.stringify(entity));
        }
        /**
         * Gets the active account
         */
        getActiveAccount(correlationId) {
            const activeAccountKeyFilters = this.generateCacheKey(PersistentCacheKeys.ACTIVE_ACCOUNT_FILTERS);
            const activeAccountValueFilters = this.browserStorage.getItem(activeAccountKeyFilters);
            if (!activeAccountValueFilters) {
                this.logger.trace("08gw0e", correlationId);
                return null;
            }
            const activeAccountValueObj = this.validateAndParseJson(activeAccountValueFilters);
            if (activeAccountValueObj) {
                this.logger.trace("1t3ch7", correlationId);
                return this.getAccountInfoFilteredBy({
                    homeAccountId: activeAccountValueObj.homeAccountId,
                    localAccountId: activeAccountValueObj.localAccountId,
                    tenantId: activeAccountValueObj.tenantId,
                }, correlationId);
            }
            this.logger.trace("0me1up", correlationId);
            return null;
        }
        /**
         * Sets the active account's localAccountId in cache
         * @param account
         */
        setActiveAccount(account, correlationId) {
            const activeAccountKey = this.generateCacheKey(PersistentCacheKeys.ACTIVE_ACCOUNT_FILTERS);
            if (account) {
                this.logger.verbose("0rsj80", correlationId);
                const activeAccountValue = {
                    homeAccountId: account.homeAccountId,
                    localAccountId: account.localAccountId,
                    tenantId: account.tenantId,
                };
                this.setItem(activeAccountKey, JSON.stringify(activeAccountValue), correlationId);
            }
            else {
                this.logger.verbose("1bp5z5", correlationId);
                this.browserStorage.removeItem(activeAccountKey);
            }
            this.eventHandler.emitEvent(EventType.ACTIVE_ACCOUNT_CHANGED, correlationId);
        }
        /**
         * fetch throttling entity from the platform cache
         * @param throttlingCacheKey
         * @param correlationId
         */
        getThrottlingCache(throttlingCacheKey, correlationId) {
            const value = this.browserStorage.getItem(throttlingCacheKey);
            if (!value) {
                this.logger.trace("1h4wa6", correlationId);
                return null;
            }
            const parsedThrottlingCache = this.validateAndParseJson(value);
            if (!parsedThrottlingCache ||
                !isThrottlingEntity(throttlingCacheKey, parsedThrottlingCache)) {
                this.logger.trace("1h4wa6", correlationId);
                return null;
            }
            this.logger.trace("0of6n8", correlationId);
            return parsedThrottlingCache;
        }
        /**
         * set throttling entity to the platform cache
         * @param throttlingCacheKey
         * @param throttlingCache
         */
        setThrottlingCache(throttlingCacheKey, throttlingCache, correlationId) {
            this.logger.trace("0wfgh6", correlationId);
            this.setItem(throttlingCacheKey, JSON.stringify(throttlingCache), correlationId);
        }
        /**
         * Gets cache item with given key.
         * @param cacheKey
         * @param correlationId
         * @param generateKey
         */
        getTemporaryCache(cacheKey, correlationId, generateKey) {
            const key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
            const value = this.temporaryCacheStorage.getItem(key);
            if (!value) {
                // If temp cache item not found in session/memory, check local storage for items set by old versions
                if (this.cacheConfig.cacheLocation ===
                    BrowserCacheLocation.LocalStorage) {
                    const item = this.browserStorage.getItem(key);
                    if (item) {
                        this.logger.trace("1yt61y", correlationId);
                        return item;
                    }
                }
                this.logger.trace("1qhy81", correlationId);
                return null;
            }
            return value;
        }
        /**
         * Sets the cache item with the key and value given.
         * @param key
         * @param value
         */
        setTemporaryCache(cacheKey, value, generateKey) {
            const key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
            this.temporaryCacheStorage.setItem(key, value);
        }
        /**
         * Removes the cache item with the given key.
         * @param key
         */
        removeItem(key) {
            this.browserStorage.removeItem(key);
        }
        /**
         * Removes the temporary cache item with the given key.
         * @param key
         */
        removeTemporaryItem(key) {
            this.temporaryCacheStorage.removeItem(key);
        }
        /**
         * Gets all keys in window.
         */
        getKeys() {
            return this.browserStorage.getKeys();
        }
        /**
         * Clears all cache entries created by MSAL.
         */
        clear(correlationId) {
            // Removes all accounts and their credentials
            this.removeAllAccounts(correlationId);
            this.removeAppMetadata(correlationId);
            // Remove temp storage first to make sure any cookies are cleared
            this.temporaryCacheStorage.getKeys().forEach((cacheKey) => {
                if (cacheKey.indexOf(PREFIX) !== -1 ||
                    cacheKey.indexOf(this.clientId) !== -1) {
                    this.removeTemporaryItem(cacheKey);
                }
            });
            // Removes all remaining MSAL cache items
            this.browserStorage.getKeys().forEach((cacheKey) => {
                if (cacheKey.indexOf(PREFIX) !== -1 ||
                    cacheKey.indexOf(this.clientId) !== -1) {
                    this.browserStorage.removeItem(cacheKey);
                }
            });
            this.internalStorage.clear();
        }
        /**
         * Prepend msal.<client-id> to each key
         * @param key
         * @param addInstanceId
         */
        generateCacheKey(key) {
            if (StringUtils.startsWith(key, PREFIX)) {
                return key;
            }
            return `${PREFIX}.${this.clientId}.${key}`;
        }
        /**
         * Cache Key: msal.<schema_version>-<home_account_id>-<environment>-<credential_type>-<client_id or familyId>-<realm>-<scopes>-<claims hash>-<scheme>
         * IdToken Example: uid.utid-login.microsoftonline.com-idtoken-app_client_id-contoso.com
         * AccessToken Example: uid.utid-login.microsoftonline.com-accesstoken-app_client_id-contoso.com-scope1 scope2--pop
         * RefreshToken Example: uid.utid-login.microsoftonline.com-refreshtoken-1-contoso.com
         * @param credentialEntity
         * @returns
         */
        generateCredentialKey(credential) {
            const familyId = (credential.credentialType ===
                CredentialType.REFRESH_TOKEN &&
                credential.familyId) ||
                credential.clientId;
            const scheme = credential.tokenType &&
                credential.tokenType.toLowerCase() !==
                    AuthenticationScheme$1.BEARER.toLowerCase()
                ? credential.tokenType.toLowerCase()
                : "";
            const credentialKey = [
                `${PREFIX}.${CREDENTIAL_SCHEMA_VERSION}`,
                credential.homeAccountId,
                credential.environment,
                credential.credentialType,
                familyId,
                credential.realm || "",
                credential.target || "",
                scheme,
            ];
            return credentialKey.join(CACHE_KEY_SEPARATOR).toLowerCase();
        }
        /**
         * Cache Key: msal.<schema_version>.<home_account_id>.<environment>.<tenant_id>
         * @param account
         * @returns
         */
        generateAccountKey(account) {
            const homeTenantId = account.homeAccountId.split(".")[1];
            const accountKey = [
                `${PREFIX}.${ACCOUNT_SCHEMA_VERSION}`,
                account.homeAccountId,
                account.environment,
                homeTenantId || account.tenantId || "",
            ];
            return accountKey.join(CACHE_KEY_SEPARATOR).toLowerCase();
        }
        /**
         * Reset all temporary cache items
         * @param correlationId
         */
        resetRequestCache(correlationId) {
            this.logger.trace("0h0ynu", correlationId);
            this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
            this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.VERIFIER));
            this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.ORIGIN_URI));
            this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.URL_HASH));
            this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
            this.setInteractionInProgress(false, undefined);
        }
        cacheAuthorizeRequest(authCodeRequest, correlationId, codeVerifier) {
            this.logger.trace("1tzef5", correlationId);
            const encodedValue = base64Encode(JSON.stringify(authCodeRequest));
            this.setTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, encodedValue, true);
            if (codeVerifier) {
                const encodedVerifier = base64Encode(codeVerifier);
                this.setTemporaryCache(TemporaryCacheKeys.VERIFIER, encodedVerifier, true);
            }
        }
        /**
         * Gets the token exchange parameters from the cache. Throws an error if nothing is found.
         * @param correlationId
         */
        getCachedRequest(correlationId) {
            this.logger.trace("0uen20", correlationId);
            // Get token request from cache and parse as TokenExchangeParameters.
            const encodedTokenRequest = this.getTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, correlationId, true);
            if (!encodedTokenRequest) {
                throw createBrowserAuthError(noTokenRequestCacheError);
            }
            const encodedVerifier = this.getTemporaryCache(TemporaryCacheKeys.VERIFIER, correlationId, true);
            let parsedRequest;
            let verifier = "";
            try {
                parsedRequest = JSON.parse(base64Decode(encodedTokenRequest));
                if (encodedVerifier) {
                    verifier = base64Decode(encodedVerifier);
                }
            }
            catch (e) {
                this.logger.errorPii("0ewsey", correlationId);
                this.logger.error("0tvdic", correlationId);
                throw createBrowserAuthError(unableToParseTokenRequestCacheError);
            }
            return [parsedRequest, verifier];
        }
        /**
         * Gets cached native request for redirect flows
         * @param correlationId
         */
        getCachedNativeRequest() {
            this.logger.trace("1yxcdm", "");
            const cachedRequest = this.getTemporaryCache(TemporaryCacheKeys.NATIVE_REQUEST, "", true);
            if (!cachedRequest) {
                this.logger.trace("0mnxd4", "");
                return null;
            }
            const parsedRequest = this.validateAndParseJson(cachedRequest);
            if (!parsedRequest) {
                this.logger.error("0rrkip", "");
                return null;
            }
            return parsedRequest;
        }
        isInteractionInProgress(matchClientId) {
            const clientId = this.getInteractionInProgress()?.clientId;
            if (matchClientId) {
                return clientId === this.clientId;
            }
            else {
                return !!clientId;
            }
        }
        getInteractionInProgress() {
            const key = `${PREFIX}.${TemporaryCacheKeys.INTERACTION_STATUS_KEY}`;
            const value = this.getTemporaryCache(key, "", false);
            try {
                return value ? JSON.parse(value) : null;
            }
            catch (e) {
                // Remove interaction and other temp keys if interaction status can't be parsed
                this.logger.error("0jjyys", "");
                this.removeTemporaryItem(key);
                this.resetRequestCache("");
                clearHash(window);
                return null;
            }
        }
        setInteractionInProgress(inProgress, type = INTERACTION_TYPE.SIGNIN, allowOverride = false, correlationId = "") {
            // Ensure we don't overwrite interaction in progress for a different clientId
            const key = `${PREFIX}.${TemporaryCacheKeys.INTERACTION_STATUS_KEY}`;
            if (inProgress) {
                const existingInteraction = this.getInteractionInProgress();
                if (existingInteraction) {
                    if (allowOverride) {
                        this.logger.warning("1pmscr", correlationId);
                        // Cancel any active bridge monitor from the previous interaction
                        cancelPendingBridgeResponse(this.logger, correlationId);
                        // Clear existing interaction to allow new one
                        this.removeTemporaryItem(key);
                    }
                    else {
                        throw createBrowserAuthError(interactionInProgress);
                    }
                }
                // Set new interaction
                this.setTemporaryCache(key, JSON.stringify({ clientId: this.clientId, type }), false);
            }
            else if (!inProgress &&
                this.getInteractionInProgress()?.clientId === this.clientId) {
                this.removeTemporaryItem(key);
            }
        }
        /**
         * Builds credential entities from AuthenticationResult object and saves the resulting credentials to the cache
         * @param result
         * @param request
         */
        async hydrateCache(result, request) {
            const idTokenEntity = createIdTokenEntity(result.account.homeAccountId, result.account.environment, result.idToken, this.clientId, result.tenantId);
            /**
             * meta data for cache stores time in seconds from epoch
             * AuthenticationResult returns expiresOn and extExpiresOn in milliseconds (as a Date object which is in ms)
             * We need to map these for the cache when building tokens from AuthenticationResult
             *
             * The next MSAL VFuture should map these both to same value if possible
             */
            const accessTokenEntity = createAccessTokenEntity(result.account.homeAccountId, result.account.environment, result.accessToken, this.clientId, result.tenantId, result.scopes.join(" "), 
            // Access token expiresOn stored in seconds, converting from AuthenticationResult expiresOn stored as Date
            result.expiresOn
                ? toSecondsFromDate(result.expiresOn)
                : 0, result.extExpiresOn
                ? toSecondsFromDate(result.extExpiresOn)
                : 0, base64Decode, undefined, // refreshOn
            result.tokenType, undefined, // userAssertionHash
            request.sshKid);
            if (request.resource) {
                accessTokenEntity.resource = request.resource;
            }
            const cacheRecord = {
                idToken: idTokenEntity,
                accessToken: accessTokenEntity,
            };
            return this.saveCacheRecord(cacheRecord, result.correlationId, isKmsi(extractTokenClaims(result.idToken, base64Decode)), ApiId.hydrateCache);
        }
        /**
         * saves a cache record
         * @param cacheRecord {CacheRecord}
         * @param storeInCache {?StoreInCache}
         * @param correlationId {?string} correlation id
         */
        async saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache) {
            try {
                await super.saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache);
            }
            catch (e) {
                if (e instanceof CacheError &&
                    this.performanceClient &&
                    correlationId) {
                    try {
                        const tokenKeys = this.getTokenKeys();
                        this.performanceClient.addFields({
                            cacheRtCount: tokenKeys.refreshToken.length,
                            cacheIdCount: tokenKeys.idToken.length,
                            cacheAtCount: tokenKeys.accessToken.length,
                        }, correlationId);
                    }
                    catch (e) { }
                }
                throw e;
            }
        }
    }
    /**
     * Returns a window storage class implementing the IWindowStorage interface that corresponds to the configured cacheLocation.
     * @param cacheLocation
     */
    function getStorageImplementation(clientId, cacheLocation, logger, performanceClient) {
        try {
            switch (cacheLocation) {
                case BrowserCacheLocation.LocalStorage:
                    return new LocalStorage(clientId, logger, performanceClient);
                case BrowserCacheLocation.SessionStorage:
                    return new SessionStorage();
                case BrowserCacheLocation.MemoryStorage:
                default:
                    break;
            }
        }
        catch (e) {
            logger.error(e, "");
        }
        return new MemoryStorage();
    }
    const DEFAULT_BROWSER_CACHE_MANAGER = (clientId, logger, performanceClient, eventHandler) => {
        const cacheOptions = {
            cacheLocation: BrowserCacheLocation.MemoryStorage,
            cacheRetentionDays: 5,
        };
        return new BrowserCacheManager(clientId, cacheOptions, DEFAULT_CRYPTO_IMPLEMENTATION, logger, performanceClient, eventHandler);
    };
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
     * @param accountFilter - (Optional) filter to narrow down the accounts returned
     * @returns Array of AccountInfo objects in cache
     */
    function getAllAccounts(logger, browserStorage, isInBrowser, correlationId, accountFilter) {
        logger.verbose("1yd030", correlationId);
        return isInBrowser
            ? browserStorage.getAllAccounts(accountFilter, correlationId)
            : [];
    }
    /**
     * Returns the first account found in the cache that matches the account filter passed in.
     * @param accountFilter
     * @returns The first account found in the cache matching the provided filter or null if no account could be found.
     */
    function getAccount(accountFilter, logger, browserStorage, correlationId) {
        logger.trace("0u7b90", correlationId);
        const account = browserStorage.getAccountInfoFilteredBy(accountFilter, correlationId);
        if (account) {
            logger.verbose("0btgll", correlationId);
            return account;
        }
        else {
            logger.verbose("0ltaj5", correlationId);
            return null;
        }
    }
    /**
     * Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
     * @param account
     */
    function setActiveAccount(account, browserStorage, correlationId) {
        browserStorage.setActiveAccount(account, correlationId);
    }
    /**
     * Gets the currently active account
     */
    function getActiveAccount(browserStorage, correlationId) {
        return browserStorage.getActiveAccount(correlationId);
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const BROADCAST_CHANNEL_NAME = "msal.broadcast.event";
    class EventHandler {
        constructor(logger) {
            this.eventCallbacks = new Map();
            this.logger = logger || new Logger({});
            if (typeof BroadcastChannel !== "undefined") {
                this.broadcastChannel = new BroadcastChannel(BROADCAST_CHANNEL_NAME);
            }
            this.invokeCrossTabCallbacks = this.invokeCrossTabCallbacks.bind(this);
        }
        /**
         * Adds event callbacks to array
         * @param callback - callback to be invoked when an event is raised
         * @param eventTypes - list of events that this callback will be invoked for, if not provided callback will be invoked for all events
         * @param callbackId - Identifier for the callback, used to locate and remove the callback when no longer required
         */
        addEventCallback(callback, eventTypes, callbackId) {
            if (typeof window !== "undefined") {
                const id = callbackId || createGuid();
                if (this.eventCallbacks.has(id)) {
                    this.logger.error("1578i0", "");
                    return null;
                }
                this.eventCallbacks.set(id, [callback, eventTypes || []]);
                this.logger.verbose("1cnec4", "");
                return id;
            }
            return null;
        }
        /**
         * Removes callback with provided id from callback array
         * @param callbackId
         */
        removeEventCallback(callbackId) {
            this.eventCallbacks.delete(callbackId);
            this.logger.verbose("12zotd", "");
        }
        /**
         * Emits events by calling callback with event message
         * @param eventType
         * @param interactionType
         * @param payload
         * @param error
         */
        emitEvent(eventType, correlationId, interactionType, payload, error) {
            const message = {
                eventType: eventType,
                interactionType: interactionType || null,
                payload: payload || null,
                error: error || null,
                correlationId: correlationId,
                timestamp: Date.now(),
            };
            switch (eventType) {
                case EventType.LOGIN_SUCCESS:
                case EventType.LOGOUT_SUCCESS:
                case EventType.ACTIVE_ACCOUNT_CHANGED:
                    // Send event to other open tabs / MSAL instances on same domain
                    this.broadcastChannel?.postMessage(message);
            }
            // Emit event to callbacks registered in this instance
            this.invokeCallbacks(message);
        }
        /**
         * Invoke registered callbacks
         * @param message
         */
        invokeCallbacks(message) {
            this.eventCallbacks.forEach(([callback, eventTypes], callbackId) => {
                if (eventTypes.length === 0 ||
                    eventTypes.includes(message.eventType)) {
                    this.logger.verbose("15jpwk", "");
                    callback.apply(null, [message]);
                }
            });
        }
        /**
         * Wrapper around invokeCallbacks to handle broadcast events received from other tabs/instances
         * @param event
         */
        invokeCrossTabCallbacks(event) {
            const message = event.data;
            this.invokeCallbacks(message);
        }
        /**
         * Listen for events broadcasted from other tabs/instances
         */
        subscribeCrossTab() {
            this.broadcastChannel?.addEventListener("message", this.invokeCrossTabCallbacks);
        }
        /**
         * Unsubscribe from broadcast events
         */
        unsubscribeCrossTab() {
            this.broadcastChannel?.removeEventListener("message", this.invokeCrossTabCallbacks);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class BaseInteractionClient {
        constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthProvider) {
            this.config = config;
            this.browserStorage = storageImpl;
            this.browserCrypto = browserCrypto;
            this.networkClient = this.config.system.networkClient;
            this.eventHandler = eventHandler;
            this.navigationClient = navigationClient;
            this.platformAuthProvider = platformAuthProvider;
            this.correlationId = correlationId;
            this.logger = logger.clone(BrowserConstants.MSAL_SKU, version);
            this.performanceClient = performanceClient;
        }
    }
    /**
     * Use to get the redirect URI configured in MSAL or construct one from the current page.
     * @param requestRedirectUri - Redirect URI from the request or undefined if not configured
     * @param clientConfigRedirectUri - Redirect URI from the client configuration or undefined if not configured
     * @param logger - Logger instance from the calling client
     * @param correlationId
     * @returns Absolute redirect URL constructed from the provided URI, config, or current page
     */
    function getRedirectUri(requestRedirectUri, clientConfigRedirectUri, logger, correlationId) {
        logger.verbose("0bd1la", correlationId);
        const redirectUri = requestRedirectUri || clientConfigRedirectUri || "";
        return UrlString.getAbsoluteUrl(redirectUri, getCurrentUri());
    }
    /**
     * Initializes and returns a ServerTelemetryManager with the provided telemetry configuration.
     * @param apiId - The API identifier for telemetry tracking
     * @param clientId - The client application identifier
     * @param correlationId - Unique identifier for correlating requests
     * @param browserStorage - Browser cache manager instance for storing telemetry data
     * @param logger - Optional logger instance for verbose logging
     * @param forceRefresh - Optional flag to force refresh of telemetry data
     * @returns Configured ServerTelemetryManager instance
     */
    function initializeServerTelemetryManager(apiId, clientId, correlationId, browserStorage, logger, forceRefresh) {
        logger.verbose("1p12tq", correlationId);
        const telemetryPayload = {
            clientId: clientId,
            correlationId: correlationId,
            apiId: apiId,
            forceRefresh: false,
            wrapperSKU: browserStorage.getWrapperMetadata()[0],
            wrapperVer: browserStorage.getWrapperMetadata()[1],
        };
        return new ServerTelemetryManager(telemetryPayload, browserStorage);
    }
    /**
     * Used to get a discovered version of the default authority.
     * @param params - Configuration object containing authority and cloud options
     * @param params.requestAuthority - Optional specific authority URL to use
     * @param params.requestAzureCloudOptions - Optional Azure cloud configuration options
     * @param params.requestExtraQueryParameters - Optional additional query parameters
     * @param params.account - Optional account info for instance-aware scenarios
     * @param config - Browser configuration containing auth settings
     * @param correlationId - Unique identifier for correlating requests
     * @param performanceClient - Performance monitoring client instance
     * @param browserStorage - Browser cache manager instance
     * @param logger - Logger instance for tracking operations
     * @returns Promise that resolves to a discovered Authority instance
     */
    async function getDiscoveredAuthority(config, correlationId, performanceClient, browserStorage, logger, requestAuthority, requestAzureCloudOptions, requestExtraQueryParameters, account) {
        const instanceAwareEQ = requestExtraQueryParameters &&
            requestExtraQueryParameters.hasOwnProperty("instance_aware")
            ? requestExtraQueryParameters["instance_aware"]
            : undefined;
        const authorityOptions = {
            protocolMode: config.system.protocolMode,
            OIDCOptions: config.auth.OIDCOptions,
            knownAuthorities: config.auth.knownAuthorities,
            cloudDiscoveryMetadata: config.auth.cloudDiscoveryMetadata,
            authorityMetadata: config.auth.authorityMetadata,
        };
        // build authority string based on auth params, precedence - azureCloudInstance + tenant >> authority
        const resolvedAuthority = requestAuthority || config.auth.authority;
        const resolvedInstanceAware = instanceAwareEQ?.length
            ? instanceAwareEQ === "true"
            : config.auth.instanceAware;
        const userAuthority = account && resolvedInstanceAware
            ? config.auth.authority.replace(UrlString.getDomainFromUrl(resolvedAuthority), account.environment)
            : resolvedAuthority;
        // fall back to the authority from config
        const builtAuthority = Authority.generateAuthority(userAuthority, requestAzureCloudOptions || config.auth.azureCloudOptions);
        const discoveredAuthority = await invokeAsync(createDiscoveredInstance, AuthorityFactoryCreateDiscoveredInstance, logger, performanceClient, correlationId)(builtAuthority, config.system.networkClient, browserStorage, authorityOptions, logger, correlationId, performanceClient);
        if (account && !discoveredAuthority.isAlias(account.environment)) {
            throw createClientConfigurationError(authorityMismatch);
        }
        return discoveredAuthority;
    }
    /**
     * Clears cache and account information during logout.
     *
     * If an account is provided, removes the account from cache and, if it is the active account, sets the active account to null.
     * If no account is provided, clears all accounts and tokens from cache.
     *
     * @param browserStorage - The browser cache manager instance used to manage cache.
     * @param browserCrypto - The crypto interface for cache operations.
     * @param logger - Logger instance for logging operations.
     * @param correlationId - Correlation ID for the logout operation.
     * @param account - (Optional) The account to clear from cache. If not provided, all accounts are cleared.
     * @returns A promise that resolves when the cache has been cleared.
     */
    async function clearCacheOnLogout(browserStorage, browserCrypto, logger, correlationId, account) {
        if (account) {
            // Clear given account.
            try {
                browserStorage.removeAccount(account, correlationId);
                logger.verbose("0s4z6h", correlationId);
            }
            catch (error) {
                logger.error("0mgg1d", correlationId);
            }
        }
        else {
            try {
                logger.verbose("0zj631", correlationId);
                // Clear all accounts and tokens
                browserStorage.clear(correlationId);
                // Clear any stray keys from IndexedDB
                await browserCrypto.clearKeystore(correlationId);
            }
            catch (e) {
                logger.error("12ih0c", correlationId);
            }
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Initializer function for all request APIs
     * @param request
     * @param config
     * @param performanceClient
     * @param logger
     * @param correlationId
     */
    async function initializeBaseRequest(request, config, performanceClient, logger, correlationId) {
        const authority = request.authority || config.auth.authority;
        const scopes = [...((request && request.scopes) || [])];
        const validatedRequest = {
            ...request,
            correlationId: request.correlationId,
            authority,
            scopes,
        };
        // Set authenticationScheme to BEARER if not explicitly set in the request
        if (!validatedRequest.authenticationScheme) {
            validatedRequest.authenticationScheme =
                AuthenticationScheme$1.BEARER;
            logger.verbose("1l4fwv", correlationId);
        }
        else {
            if (validatedRequest.authenticationScheme ===
                AuthenticationScheme$1.SSH) {
                if (!request.sshJwk) {
                    throw createClientConfigurationError(missingSshJwk);
                }
                if (!request.sshKid) {
                    throw createClientConfigurationError(missingSshKid);
                }
            }
            logger.verbose("1ecmns", correlationId);
        }
        return validatedRequest;
    }
    async function initializeSilentRequest(request, account, config, performanceClient, logger) {
        const baseRequest = await invokeAsync(initializeBaseRequest, InitializeBaseRequest, logger, performanceClient, request.correlationId)(request, config, performanceClient, logger, request.correlationId);
        return {
            ...request,
            ...baseRequest,
            account: account,
            forceRefresh: request.forceRefresh || false,
        };
    }
    /**
     * Validates that the combination of request method, protocol mode and authorize body parameters is correct.
     * Returns the validated or defaulted HTTP method or throws if the configured combination is invalid.
     * @param interactionRequest
     * @param protocolMode
     * @returns
     */
    function validateRequestMethod(interactionRequest, protocolMode) {
        let httpMethod;
        const requestMethod = interactionRequest.httpMethod;
        if (protocolMode === ProtocolMode.EAR) {
            // Validate that method can only be POST when protocol mode is EAR
            if (requestMethod && requestMethod !== HttpMethod.POST) {
                throw createClientConfigurationError(invalidRequestMethodForEAR);
            }
            else {
                httpMethod = HttpMethod.POST;
            }
        }
        else {
            // For non-EAR protocol modes, default to GET if httpMethod is not set
            httpMethod = requestMethod || HttpMethod.GET;
        }
        return httpMethod;
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Defines the class structure and helper functions used by the "standard", non-brokered auth flows (popup, redirect, silent (RT), silent (iframe))
     */
    class StandardInteractionClient extends BaseInteractionClient {
        /**
         * Initializer for the logout request.
         * @param logoutRequest
         */
        initializeLogoutRequest(logoutRequest) {
            this.logger.verbose("0546u4", this.correlationId);
            const validLogoutRequest = {
                correlationId: this.correlationId,
                ...logoutRequest,
            };
            /**
             * Set logout_hint to be login_hint from ID Token Claims if present
             * and logoutHint attribute wasn't manually set in logout request
             */
            if (logoutRequest) {
                // If logoutHint isn't set and an account was passed in, try to extract logoutHint from ID Token Claims
                if (!logoutRequest.logoutHint) {
                    if (logoutRequest.account) {
                        const logoutHint = this.getLogoutHintFromIdTokenClaims(logoutRequest.account);
                        if (logoutHint) {
                            this.logger.verbose("0st5di", this.correlationId);
                            validLogoutRequest.logoutHint = logoutHint;
                        }
                    }
                    else {
                        this.logger.verbose("0pdtc3", this.correlationId);
                    }
                }
                else {
                    this.logger.verbose("12k4l4", this.correlationId);
                }
            }
            else {
                this.logger.verbose("07ndze", this.correlationId);
            }
            /*
             * Only set redirect uri if logout request isn't provided or the set uri isn't null.
             * Otherwise, use passed uri, config, or current page.
             */
            if (!logoutRequest || logoutRequest.postLogoutRedirectUri !== null) {
                if (logoutRequest && logoutRequest.postLogoutRedirectUri) {
                    this.logger.verbose("1vamm6", validLogoutRequest.correlationId);
                    validLogoutRequest.postLogoutRedirectUri =
                        UrlString.getAbsoluteUrl(logoutRequest.postLogoutRedirectUri, getCurrentUri());
                }
                else if (this.config.auth.postLogoutRedirectUri === null) {
                    this.logger.verbose("15m5g7", validLogoutRequest.correlationId);
                }
                else if (this.config.auth.postLogoutRedirectUri) {
                    this.logger.verbose("1f4xlz", validLogoutRequest.correlationId);
                    validLogoutRequest.postLogoutRedirectUri =
                        UrlString.getAbsoluteUrl(this.config.auth.postLogoutRedirectUri, getCurrentUri());
                }
                else {
                    this.logger.verbose("17s5rf", validLogoutRequest.correlationId);
                    validLogoutRequest.postLogoutRedirectUri =
                        UrlString.getAbsoluteUrl(getCurrentUri(), getCurrentUri());
                }
            }
            else {
                this.logger.verbose("0ljv63", validLogoutRequest.correlationId);
            }
            return validLogoutRequest;
        }
        /**
         * Parses login_hint ID Token Claim out of AccountInfo object to be used as
         * logout_hint in end session request.
         * @param account
         */
        getLogoutHintFromIdTokenClaims(account) {
            const idTokenClaims = account.idTokenClaims;
            if (idTokenClaims) {
                if (idTokenClaims.login_hint) {
                    return idTokenClaims.login_hint;
                }
                else {
                    this.logger.verbose("0mvp54", this.correlationId);
                }
            }
            else {
                this.logger.verbose("1e7bdp", this.correlationId);
            }
            return null;
        }
        /**
         * Creates an Authorization Code Client with the given authority, or the default authority.
         * @param params {
         *         serverTelemetryManager: ServerTelemetryManager;
         *         authorityUrl?: string;
         *         requestAzureCloudOptions?: AzureCloudOptions;
         *         requestExtraQueryParameters?: StringDict;
         *         account?: AccountInfo;
         *        }
         */
        async createAuthCodeClient(params) {
            // Create auth module.
            const clientConfig = await invokeAsync(this.getClientConfiguration.bind(this), StandardInteractionClientGetClientConfiguration, this.logger, this.performanceClient, this.correlationId)(params);
            return new AuthorizationCodeClient(clientConfig, this.performanceClient);
        }
        /**
         * Creates a Client Configuration object with the given request authority, or the default authority.
         * @param params {
         *         serverTelemetryManager: ServerTelemetryManager;
         *         requestAuthority?: string;
         *         requestAzureCloudOptions?: AzureCloudOptions;
         *         requestExtraQueryParameters?: boolean;
         *         account?: AccountInfo;
         *        }
         */
        async getClientConfiguration(params) {
            const { serverTelemetryManager, requestAuthority, requestAzureCloudOptions, requestExtraQueryParameters, account, } = params;
            const discoveredAuthority = params.authority ||
                (await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, this.correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, requestAuthority, requestAzureCloudOptions, requestExtraQueryParameters, account));
            const logger = this.config.system.loggerOptions;
            return {
                authOptions: {
                    clientId: this.config.auth.clientId,
                    authority: discoveredAuthority,
                    clientCapabilities: this.config.auth.clientCapabilities,
                    redirectUri: this.config.auth.redirectUri,
                    isMcp: this.config.auth.isMcp,
                },
                systemOptions: {
                    tokenRenewalOffsetSeconds: this.config.system.tokenRenewalOffsetSeconds,
                    preventCorsPreflight: true,
                },
                loggerOptions: {
                    loggerCallback: logger.loggerCallback,
                    piiLoggingEnabled: logger.piiLoggingEnabled,
                    logLevel: logger.logLevel,
                    correlationId: this.correlationId,
                },
                cryptoInterface: this.browserCrypto,
                networkInterface: this.networkClient,
                storageInterface: this.browserStorage,
                serverTelemetryManager: serverTelemetryManager,
                libraryInfo: {
                    sku: BrowserConstants.MSAL_SKU,
                    version: version,
                    cpu: "",
                    os: "",
                },
                telemetry: this.config.telemetry,
            };
        }
    }
    /**
     * Helper to initialize required request parameters for interactive APIs and ssoSilent().
     *
     * @param request - The authentication request object (RedirectRequest, PopupRequest, or SsoSilentRequest).
     * @param interactionType - The type of interaction (e.g., redirect, popup, silent).
     * @param config - The browser configuration object.
     * @param browserCrypto - The cryptographic interface for browser operations.
     * @param browserStorage - The browser storage manager instance.
     * @param logger - The logger instance for logging messages.
     * @param performanceClient - The performance client for telemetry.
     * @param correlationId - The correlation ID for the request.
     * @returns A promise that resolves to a CommonAuthorizationUrlRequest object with initialized parameters.
     */
    async function initializeAuthorizationRequest(request, interactionType, config, browserCrypto, browserStorage, logger, performanceClient, correlationId) {
        const redirectUri = getRedirectUri(request.redirectUri, config.auth.redirectUri, logger, correlationId);
        if (new URL(redirectUri).origin !== new URL(window.location.href).origin) {
            logger.warning("08qbvw", correlationId);
            performanceClient.addFields({ isRedirectUriCrossOrigin: true }, correlationId);
        }
        const browserState = {
            interactionType: interactionType,
        };
        const state = setRequestState(browserCrypto, (request && request.state) || "", browserState);
        const baseRequest = await invokeAsync(initializeBaseRequest, InitializeBaseRequest, logger, performanceClient, correlationId)({ ...request, correlationId: correlationId }, config, performanceClient, logger, correlationId);
        const interactionRequest = {
            ...baseRequest,
            redirectUri: redirectUri,
            state: state,
            nonce: request.nonce || createNewGuid(),
            responseMode: config.auth.OIDCOptions.responseMode,
        };
        const validatedRequest = {
            ...interactionRequest,
            httpMethod: validateRequestMethod(interactionRequest, config.system.protocolMode),
        };
        // Skip active account lookup if either login hint or session id is set
        if (request.loginHint || request.sid) {
            return validatedRequest;
        }
        const account = request.account || browserStorage.getActiveAccount(correlationId);
        if (account) {
            logger.verbose("1eqlb3", correlationId);
            logger.verbosePii("0tf99t", correlationId);
            validatedRequest.account = account;
        }
        return validatedRequest;
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Extracts the BrowserStateObject from the state string.
     * @param browserCrypto
     * @param state
     */
    function extractBrowserRequestState(browserCrypto, state) {
        if (!state) {
            return null;
        }
        try {
            const requestStateObj = parseRequestState(browserCrypto.base64Decode, state);
            return requestStateObj.libraryState.meta;
        }
        catch (e) {
            throw createClientAuthError(invalidState);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function deserializeResponse(responseString, responseLocation, logger, correlationId) {
        // Deserialize hash fragment response parameters.
        const serverParams = getDeserializedResponse(responseString);
        if (!serverParams) {
            if (!stripLeadingHashOrQuery(responseString)) {
                // Hash or Query string is empty
                logger.error("18h0l1", correlationId);
                throw createBrowserAuthError(hashEmptyError);
            }
            else {
                logger.error("13pl0s", correlationId);
                logger.errorPii("1097vx", correlationId);
                throw createBrowserAuthError(hashDoesNotContainKnownProperties);
            }
        }
        return serverParams;
    }
    /**
     * Returns the interaction type that the response object belongs to
     */
    function validateInteractionType(response, browserCrypto, interactionType) {
        if (!response.state) {
            throw createBrowserAuthError(noStateInHash);
        }
        const platformStateObj = extractBrowserRequestState(browserCrypto, response.state);
        if (!platformStateObj) {
            throw createBrowserAuthError(unableToParseState);
        }
        if (platformStateObj.interactionType !== interactionType) {
            throw createBrowserAuthError(stateInteractionTypeMismatch);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Abstract class which defines operations for a browser interaction handling class.
     */
    class InteractionHandler {
        constructor(authCodeModule, storageImpl, authCodeRequest, logger, performanceClient) {
            this.authModule = authCodeModule;
            this.browserStorage = storageImpl;
            this.authCodeRequest = authCodeRequest;
            this.logger = logger;
            this.performanceClient = performanceClient;
        }
        /**
         * Function to handle response parameters from hash.
         * @param locationHash
         */
        async handleCodeResponse(response, request, apiId) {
            let authCodeResponse;
            try {
                authCodeResponse = getAuthorizationCodePayload(response, request.state);
            }
            catch (e) {
                if (e instanceof ServerError &&
                    e.subError === userCancelled) {
                    // Translate server error caused by user closing native prompt to corresponding first class MSAL error
                    throw createBrowserAuthError(userCancelled);
                }
                else {
                    throw e;
                }
            }
            return invokeAsync(this.handleCodeResponseFromServer.bind(this), HandleCodeResponseFromServer, this.logger, this.performanceClient, request.correlationId)(authCodeResponse, request, apiId);
        }
        /**
         * Process auth code response from AAD
         * @param authCodeResponse
         * @param request
         * @param validateNonce
         * @returns
         */
        async handleCodeResponseFromServer(authCodeResponse, request, apiId, validateNonce = true) {
            this.logger.trace("0mf2hb", request.correlationId);
            // Assign code to request
            this.authCodeRequest.code = authCodeResponse.code;
            // Nonce validation not needed when redirect not involved (e.g. hybrid spa, renewing token via rt)
            if (validateNonce) {
                // TODO: Assigning "response nonce" to "request nonce" is confusing. Refactor the function doing validation to accept request nonce directly
                authCodeResponse.nonce = request.nonce || undefined;
            }
            authCodeResponse.state = request.state;
            // Add CCS parameters if available
            if (authCodeResponse.client_info) {
                this.authCodeRequest.clientInfo = authCodeResponse.client_info;
            }
            else {
                const ccsCred = this.createCcsCredentials(request);
                if (ccsCred) {
                    this.authCodeRequest.ccsCredential = ccsCred;
                }
            }
            // Acquire token with retrieved code.
            const tokenResponse = (await invokeAsync(this.authModule.acquireToken.bind(this.authModule), AuthClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(this.authCodeRequest, apiId, authCodeResponse));
            return tokenResponse;
        }
        /**
         * Build ccs creds if available
         */
        createCcsCredentials(request) {
            if (request.account) {
                return {
                    credential: request.account.homeAccountId,
                    type: CcsCredentialType.HOME_ACCOUNT_ID,
                };
            }
            else if (request.loginHint) {
                return {
                    credential: request.loginHint,
                    type: CcsCredentialType.UPN,
                };
            }
            return null;
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const contentError = "ContentError";
    const pageException = "PageException";
    const userSwitch = "user_switch";
    const unsupportedMethod = "unsupported_method";
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    // Status Codes that can be thrown by WAM
    const USER_INTERACTION_REQUIRED = "USER_INTERACTION_REQUIRED";
    const USER_CANCEL = "USER_CANCEL";
    const NO_NETWORK = "NO_NETWORK";
    const DISABLED = "DISABLED";
    const ACCOUNT_UNAVAILABLE = "ACCOUNT_UNAVAILABLE";
    const UX_NOT_ALLOWED = "UX_NOT_ALLOWED";
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const INVALID_METHOD_ERROR = -2147186943;
    class NativeAuthError extends AuthError {
        constructor(errorCode, description, ext) {
            super(errorCode, description || getDefaultErrorMessage(errorCode));
            Object.setPrototypeOf(this, NativeAuthError.prototype);
            this.name = "NativeAuthError";
            this.ext = ext;
        }
    }
    /**
     * These errors should result in a fallback to the 'standard' browser based auth flow.
     */
    function isFatalNativeAuthError(error) {
        if (error.ext &&
            error.ext.status &&
            error.ext.status === DISABLED) {
            return true;
        }
        if (error.ext &&
            error.ext.error &&
            error.ext.error === INVALID_METHOD_ERROR) {
            return true;
        }
        switch (error.errorCode) {
            case contentError:
            case pageException:
                return true;
            default:
                return false;
        }
    }
    /**
     * Create the appropriate error object based on the WAM status code.
     * @param code
     * @param description
     * @param ext
     * @returns
     */
    function createNativeAuthError(code, description, ext) {
        if (ext && ext.status) {
            switch (ext.status) {
                case ACCOUNT_UNAVAILABLE:
                    return createInteractionRequiredAuthError(nativeAccountUnavailable, getDefaultErrorMessage(code));
                case USER_INTERACTION_REQUIRED:
                    return new InteractionRequiredAuthError(code, description);
                case USER_CANCEL:
                    return createBrowserAuthError(userCancelled);
                case NO_NETWORK:
                    return createBrowserAuthError(noNetworkConnectivity);
                case UX_NOT_ALLOWED:
                    return createInteractionRequiredAuthError(uxNotAllowed);
            }
        }
        return new NativeAuthError(code, description, ext);
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class SilentCacheClient extends StandardInteractionClient {
        /**
         * Returns unexpired tokens from the cache, if available
         * @param silentRequest
         */
        async acquireToken(silentRequest) {
            // Telemetry manager only used to increment cacheHits here
            const serverTelemetryManager = initializeServerTelemetryManager(ApiId.acquireTokenSilent_silentFlow, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
            const clientConfig = await invokeAsync(this.getClientConfiguration.bind(this), StandardInteractionClientGetClientConfiguration, this.logger, this.performanceClient, this.correlationId)({
                serverTelemetryManager,
                requestAuthority: silentRequest.authority,
                requestAzureCloudOptions: silentRequest.azureCloudOptions,
                account: silentRequest.account,
            });
            const silentAuthClient = new SilentFlowClient(clientConfig, this.performanceClient);
            this.logger.verbose("0wa871", this.correlationId);
            try {
                const response = await invokeAsync(silentAuthClient.acquireCachedToken.bind(silentAuthClient), SilentFlowClientAcquireCachedToken, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest);
                const authResponse = response[0];
                this.performanceClient.addFields({
                    fromCache: true,
                }, silentRequest.correlationId);
                return authResponse;
            }
            catch (error) {
                if (error instanceof BrowserAuthError &&
                    error.errorCode === cryptoKeyNotFound) {
                    this.logger.verbose("06wena", this.correlationId);
                }
                throw error;
            }
        }
        /**
         * API to silenty clear the browser cache.
         * @param logoutRequest
         */
        logout(logoutRequest) {
            this.logger.verbose("1rkurh", this.correlationId);
            const validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
            return clearCacheOnLogout(this.browserStorage, this.browserCrypto, this.logger, this.correlationId, validLogoutRequest.account);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class PlatformAuthInteractionClient extends BaseInteractionClient {
        constructor(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, provider, accountId, nativeStorageImpl, correlationId) {
            super(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, provider);
            this.apiId = apiId;
            this.accountId = accountId;
            this.platformAuthProvider = provider;
            this.nativeStorageManager = nativeStorageImpl;
            this.silentCacheClient = new SilentCacheClient(config, this.nativeStorageManager, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, provider);
            const extensionName = this.platformAuthProvider.getExtensionName();
            this.skus = ServerTelemetryManager.makeExtraSkuString({
                libraryName: BrowserConstants.MSAL_SKU,
                libraryVersion: version,
                extensionName: extensionName,
                extensionVersion: this.platformAuthProvider.getExtensionVersion(),
            });
        }
        /**
         * Adds SKUs to request extra query parameters
         * @param request {PlatformAuthRequest}
         * @private
         */
        addRequestSKUs(request) {
            request.extraParameters = {
                ...request.extraParameters,
                [X_CLIENT_EXTRA_SKU]: this.skus,
            };
        }
        /**
         * Acquire token from native platform via browser extension
         * @param request
         */
        async acquireToken(request, cacheLookupPolicy) {
            this.logger.trace("03qeos", this.correlationId);
            // start the perf measurement
            const nativeATMeasurement = this.performanceClient.startMeasurement(NativeInteractionClientAcquireToken, this.correlationId);
            const reqTimestamp = nowSeconds();
            const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
            try {
                // initialize native request
                const nativeRequest = await this.initializePlatformRequest(request);
                // check if the tokens can be retrieved from internal cache
                try {
                    const result = await this.acquireTokensFromCache(this.accountId, nativeRequest);
                    nativeATMeasurement.end({
                        success: true,
                        isNativeBroker: false,
                        fromCache: true,
                    });
                    return result;
                }
                catch (e) {
                    if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
                        this.logger.info("0eitbc", this.correlationId);
                        nativeATMeasurement.end({
                            success: false,
                            brokerErrorCode: "cache_request_failed",
                        });
                        throw e;
                    }
                    // continue with a native call for any and all errors
                    this.logger.info("0957j1", this.correlationId);
                }
                const validatedResponse = await this.platformAuthProvider.sendMessage(nativeRequest);
                return await this.handleNativeResponse(validatedResponse, nativeRequest, reqTimestamp)
                    .then((result) => {
                    nativeATMeasurement.end({
                        success: true,
                        isNativeBroker: true,
                        requestId: result.requestId,
                    });
                    serverTelemetryManager.clearNativeBrokerErrorCode();
                    return result;
                })
                    .catch((error) => {
                    nativeATMeasurement.end({
                        success: false,
                        errorCode: error.errorCode,
                        subErrorCode: error.subError,
                    });
                    throw error;
                });
            }
            catch (e) {
                if (e instanceof NativeAuthError) {
                    serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
                }
                nativeATMeasurement.end({
                    success: false,
                });
                throw e;
            }
        }
        /**
         * Creates silent flow request
         * @param request
         * @param cachedAccount
         * @returns CommonSilentFlowRequest
         */
        createSilentCacheRequest(request, cachedAccount) {
            return {
                authority: request.authority,
                correlationId: this.correlationId,
                scopes: ScopeSet.fromString(request.scope).asArray(),
                account: cachedAccount,
                forceRefresh: false,
            };
        }
        /**
         * Fetches the tokens from the cache if un-expired
         * @param nativeAccountId
         * @param request
         * @returns authenticationResult
         */
        async acquireTokensFromCache(nativeAccountId, request) {
            if (!nativeAccountId) {
                this.logger.warning("1ndf3e", this.correlationId);
                throw createClientAuthError(noAccountFound);
            }
            // fetch the account from browser cache
            const account = this.browserStorage.getBaseAccountInfo({
                nativeAccountId,
            }, this.correlationId);
            if (!account) {
                throw createClientAuthError(noAccountFound);
            }
            // leverage silent flow for cached tokens retrieval
            try {
                const silentRequest = this.createSilentCacheRequest(request, account);
                const result = await this.silentCacheClient.acquireToken(silentRequest);
                const fullAccount = {
                    ...account,
                    idTokenClaims: result?.idTokenClaims,
                    idToken: result?.idToken,
                };
                return {
                    ...result,
                    account: fullAccount,
                };
            }
            catch (e) {
                throw e;
            }
        }
        /**
         * Acquires a token from native platform then redirects to the redirectUri instead of returning the response
         * @param {RedirectRequest} request
         * @param {InProgressPerformanceEvent} rootMeasurement
         * @param {HandleRedirectPromiseOptions} options
         */
        async acquireTokenRedirect(request, rootMeasurement, options) {
            this.logger.trace("0luikq", this.correlationId);
            const nativeRequest = await this.initializePlatformRequest(request);
            const navigateToLoginRequestUrl = options?.navigateToLoginRequestUrl ?? true;
            try {
                await this.platformAuthProvider.sendMessage(nativeRequest);
            }
            catch (e) {
                // Only throw fatal errors here to allow application to fallback to regular redirect. Otherwise proceed and the error will be thrown in handleRedirectPromise
                if (e instanceof NativeAuthError) {
                    const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
                    serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
                    if (isFatalNativeAuthError(e)) {
                        throw e;
                    }
                }
            }
            this.browserStorage.setTemporaryCache(TemporaryCacheKeys.NATIVE_REQUEST, JSON.stringify(nativeRequest), true);
            const navigationOptions = {
                apiId: ApiId.acquireTokenRedirect,
                timeout: this.config.system.redirectNavigationTimeout,
                noHistory: false,
            };
            const redirectUri = navigateToLoginRequestUrl
                ? window.location.href
                : getRedirectUri(request.redirectUri, this.config.auth.redirectUri, this.logger, this.correlationId);
            rootMeasurement.end({ success: true });
            await this.navigationClient.navigateExternal(redirectUri, navigationOptions); // Need to treat this as external to ensure handleRedirectPromise is run again
        }
        /**
         * If the previous page called native platform for a token using redirect APIs, send the same request again and return the response
         * @param performanceClient {IPerformanceClient?}
         * @param correlationId {string?} correlation identifier
         */
        async handleRedirectPromise() {
            this.logger.trace("1c5lhw", this.correlationId);
            if (!this.browserStorage.isInteractionInProgress(true)) {
                this.logger.info("0le6uv", this.correlationId);
                return null;
            }
            // remove prompt from the request to prevent WAM from prompting twice
            const cachedRequest = this.browserStorage.getCachedNativeRequest();
            if (!cachedRequest) {
                this.logger.verbose("0a6zjb", this.correlationId);
                this.performanceClient?.addFields({ errorCode: "no_cached_request" }, this.correlationId);
                return null;
            }
            const { prompt, ...request } = cachedRequest;
            if (prompt) {
                this.logger.verbose("0ac34v", this.correlationId);
            }
            this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
            const reqTimestamp = nowSeconds();
            try {
                this.logger.verbose("003x5a", this.correlationId);
                const response = await this.platformAuthProvider.sendMessage(request);
                const authResult = await this.handleNativeResponse(response, request, reqTimestamp);
                const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
                serverTelemetryManager.clearNativeBrokerErrorCode();
                this.performanceClient?.addFields({ isNativeBroker: true }, this.correlationId);
                return authResult;
            }
            catch (e) {
                throw e;
            }
        }
        /**
         * Logout from native platform via browser extension
         * @param request
         */
        logout() {
            this.logger.trace("0u2sjm", this.correlationId);
            return Promise.reject("Logout not implemented yet");
        }
        /**
         * Transform response from native platform into AuthenticationResult object which will be returned to the end user
         * @param response
         * @param request
         * @param reqTimestamp
         */
        async handleNativeResponse(response, request, reqTimestamp) {
            this.logger.trace("1bojln", this.correlationId);
            // generate identifiers
            const idTokenClaims = extractTokenClaims(response.id_token, base64Decode);
            const homeAccountIdentifier = this.createHomeAccountIdentifier(response, idTokenClaims);
            const cachedhomeAccountId = this.browserStorage.getAccountInfoFilteredBy({
                nativeAccountId: request.accountId,
            }, this.correlationId)?.homeAccountId;
            // add exception for double brokering, please note this is temporary and will be fortified in future
            if (request.extraParameters?.child_client_id &&
                response.account.id !== request.accountId) {
                this.logger.info("1ub1in", this.correlationId);
            }
            else if (homeAccountIdentifier !== cachedhomeAccountId &&
                response.account.id !== request.accountId) {
                // User switch in native broker prompt is not supported. All users must first sign in through web flow to ensure server state is in sync
                throw createNativeAuthError(userSwitch);
            }
            // Get the preferred_cache domain for the given authority
            const authority = await getDiscoveredAuthority(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, request.authority);
            const baseAccount = buildAccountToCache(this.browserStorage, authority, homeAccountIdentifier, base64Decode, this.correlationId, idTokenClaims, response.client_info, authority.getPreferredCache(), // environment
            idTokenClaims.tid, undefined, // auth code payload
            response.account.id, this.logger, this.performanceClient);
            // Ensure expires_in is in number format
            response.expires_in = Number(response.expires_in);
            // generate authenticationResult
            const result = await this.generateAuthenticationResult(response, request, idTokenClaims, baseAccount, authority.canonicalAuthority, reqTimestamp);
            // cache accounts and tokens in the appropriate storage
            await this.cacheAccount(baseAccount, isKmsi(idTokenClaims));
            await this.cacheNativeTokens(response, request, homeAccountIdentifier, idTokenClaims, response.access_token, result.tenantId, reqTimestamp);
            return result;
        }
        /**
         * creates an homeAccountIdentifier for the account
         * @param response
         * @param idTokenObj
         * @returns
         */
        createHomeAccountIdentifier(response, idTokenClaims) {
            // Save account in browser storage
            const homeAccountIdentifier = generateHomeAccountId(response.client_info || "", AuthorityType.Default, this.logger, this.browserCrypto, this.correlationId, idTokenClaims);
            return homeAccountIdentifier;
        }
        /**
         * Helper to generate scopes
         * @param response
         * @param request
         * @returns
         */
        generateScopes(requestScopes, responseScopes) {
            return responseScopes
                ? ScopeSet.fromString(responseScopes)
                : ScopeSet.fromString(requestScopes);
        }
        /**
         * If PoP token is requesred, records the PoP token if returned from the WAM, else generates one in the browser
         * @param request
         * @param response
         */
        async generatePopAccessToken(response, request) {
            if (request.tokenType === AuthenticationScheme$1.POP &&
                request.signPopToken) {
                /**
                 * This code prioritizes SHR returned from the native layer. In case of error/SHR not calculated from WAM and the AT
                 * is still received, SHR is calculated locally
                 */
                // Check if native layer returned an SHR token
                if (response.shr) {
                    this.logger.trace("0coqhu", this.correlationId);
                    return response.shr;
                }
                // Generate SHR in msal js if WAM does not compute it when POP is enabled
                const popTokenGenerator = new PopTokenGenerator(this.browserCrypto, this.performanceClient);
                const shrParameters = {
                    resourceRequestMethod: request.resourceRequestMethod,
                    resourceRequestUri: request.resourceRequestUri,
                    shrClaims: request.shrClaims,
                    shrNonce: request.shrNonce,
                    correlationId: this.correlationId,
                };
                /**
                 * KeyID must be present in the native request from when the PoP key was generated in order for
                 * PopTokenGenerator to query the full key for signing
                 */
                if (!request.keyId) {
                    throw createClientAuthError(keyIdMissing);
                }
                return popTokenGenerator.signPopToken(response.access_token, request.keyId, shrParameters);
            }
            else {
                return response.access_token;
            }
        }
        /**
         * Generates authentication result
         * @param response
         * @param request
         * @param idTokenObj
         * @param accountEntity
         * @param authority
         * @param reqTimestamp
         * @returns
         */
        async generateAuthenticationResult(response, request, idTokenClaims, accountEntity, authority, reqTimestamp) {
            // Add Native Broker fields to Telemetry
            const mats = this.addTelemetryFromNativeResponse(response.properties.MATS);
            // If scopes not returned in server response, use request scopes
            const responseScopes = this.generateScopes(request.scope, response.scope);
            const accountProperties = response.account.properties || {};
            const uid = accountProperties["UID"] ||
                idTokenClaims.oid ||
                idTokenClaims.sub ||
                "";
            const tid = accountProperties["TenantId"] || idTokenClaims.tid || "";
            const accountInfo = updateAccountTenantProfileData(getAccountInfo(accountEntity), undefined, // tenantProfile optional
            idTokenClaims, response.id_token);
            /**
             * In pairwise broker flows, this check prevents the broker's native account id
             * from being returned over the embedded app's account id.
             */
            if (accountInfo.nativeAccountId !== response.account.id) {
                accountInfo.nativeAccountId = response.account.id;
            }
            // generate PoP token as needed
            const responseAccessToken = await this.generatePopAccessToken(response, request);
            const tokenType = request.tokenType === AuthenticationScheme$1.POP
                ? AuthenticationScheme$1.POP
                : AuthenticationScheme$1.BEARER;
            const result = {
                authority: authority,
                uniqueId: uid,
                tenantId: tid,
                scopes: responseScopes.asArray(),
                account: accountInfo,
                idToken: response.id_token,
                idTokenClaims: idTokenClaims,
                accessToken: responseAccessToken,
                fromCache: mats ? this.isResponseFromCache(mats) : false,
                // Request timestamp and NativeResponse expires_in are in seconds, converting to Date for AuthenticationResult
                expiresOn: toDateFromSeconds(reqTimestamp + response.expires_in),
                tokenType: tokenType,
                correlationId: this.correlationId,
                state: response.state,
                fromPlatformBroker: true,
                ...(request.resource && { resource: request.resource }),
            };
            return result;
        }
        /**
         * cache the account entity in browser storage
         * @param accountEntity
         */
        async cacheAccount(accountEntity, kmsi) {
            // Store the account info and hence `nativeAccountId` in browser cache
            await this.browserStorage.setAccount(accountEntity, this.correlationId, kmsi, this.apiId);
            // Remove any existing cached tokens for this account in browser storage
            this.browserStorage.removeAccountContext(getAccountInfo(accountEntity), this.correlationId);
        }
        /**
         * Stores the access_token and id_token in inmemory storage
         * @param response
         * @param request
         * @param homeAccountIdentifier
         * @param idTokenObj
         * @param responseAccessToken
         * @param tenantId
         * @param reqTimestamp
         */
        cacheNativeTokens(response, request, homeAccountIdentifier, idTokenClaims, responseAccessToken, tenantId, reqTimestamp) {
            const cachedIdToken = createIdTokenEntity(homeAccountIdentifier, request.authority, response.id_token || "", request.clientId, idTokenClaims.tid || "");
            // cache accessToken in inmemory storage
            const expiresIn = request.tokenType === AuthenticationScheme$1.POP
                ? SHR_NONCE_VALIDITY
                : (typeof response.expires_in === "string"
                    ? parseInt(response.expires_in, 10)
                    : response.expires_in) || 0;
            const tokenExpirationSeconds = reqTimestamp + expiresIn;
            const responseScopes = this.generateScopes(response.scope, request.scope);
            const cachedAccessToken = createAccessTokenEntity(homeAccountIdentifier, request.authority, responseAccessToken, request.clientId, idTokenClaims.tid || tenantId, responseScopes.printScopes(), tokenExpirationSeconds, 0, base64Decode, undefined, request.tokenType, undefined, request.keyId);
            const nativeCacheRecord = {
                idToken: cachedIdToken,
                accessToken: cachedAccessToken,
            };
            return this.nativeStorageManager.saveCacheRecord(nativeCacheRecord, this.correlationId, isKmsi(idTokenClaims), this.apiId, request.storeInCache);
        }
        getExpiresInValue(tokenType, expiresIn) {
            return tokenType === AuthenticationScheme$1.POP
                ? SHR_NONCE_VALIDITY
                : (typeof expiresIn === "string"
                    ? parseInt(expiresIn, 10)
                    : expiresIn) || 0;
        }
        addTelemetryFromNativeResponse(matsResponse) {
            const mats = this.getMATSFromResponse(matsResponse);
            if (!mats) {
                return null;
            }
            this.performanceClient.addFields({
                extensionId: this.platformAuthProvider.getExtensionId(),
                extensionVersion: this.platformAuthProvider.getExtensionVersion(),
                matsBrokerVersion: mats.broker_version,
                matsAccountJoinOnStart: mats.account_join_on_start,
                matsAccountJoinOnEnd: mats.account_join_on_end,
                matsDeviceJoin: mats.device_join,
                matsPromptBehavior: mats.prompt_behavior,
                matsApiErrorCode: mats.api_error_code,
                matsUiVisible: mats.ui_visible,
                matsSilentCode: mats.silent_code,
                matsSilentBiSubCode: mats.silent_bi_sub_code,
                matsSilentMessage: mats.silent_message,
                matsSilentStatus: mats.silent_status,
                matsHttpStatus: mats.http_status,
                matsHttpEventCount: mats.http_event_count,
            }, this.correlationId);
            return mats;
        }
        /**
         * Gets MATS telemetry from native response
         * @param response
         * @returns
         */
        getMATSFromResponse(matsResponse) {
            if (matsResponse) {
                try {
                    return JSON.parse(matsResponse);
                }
                catch (e) {
                    this.logger.error("0b3l57", this.correlationId);
                }
            }
            return null;
        }
        /**
         * Returns whether or not response came from native cache
         * @param response
         * @returns
         */
        isResponseFromCache(mats) {
            if (typeof mats.is_cached === "undefined") {
                this.logger.verbose("1okqev", this.correlationId);
                return false;
            }
            return !!mats.is_cached;
        }
        /**
         * Translates developer provided request object into NativeRequest object
         * @param request
         */
        async initializePlatformRequest(request) {
            this.logger.trace("1xdm2a", this.correlationId);
            const canonicalAuthority = await this.getCanonicalAuthority(request);
            // ignore config claims if skipBrokerClaims is set to true and this is a brokered authentication flow
            const configClaims = request.skipBrokerClaims && !!request.embeddedClientId
                ? undefined
                : this.config.auth.clientCapabilities;
            // scopes are expected to be received by the native broker as "scope" and will be added to the request below. Other properties that should be dropped from the request to the native broker can be included in the object destructuring here.
            const { scopes, claims, ...remainingProperties } = request;
            const scopeSet = new ScopeSet(scopes || []);
            scopeSet.appendScopes(OIDC_DEFAULT_SCOPES$1);
            const mergedClaims = configClaims && configClaims.length
                ? addClientCapabilitiesToClaims$1(claims, configClaims)
                : claims;
            const validatedRequest = {
                ...remainingProperties,
                claims: mergedClaims,
                accountId: this.accountId,
                clientId: this.config.auth.clientId,
                authority: canonicalAuthority.urlString,
                scope: scopeSet.printScopes(),
                redirectUri: getRedirectUri(request.redirectUri, this.config.auth.redirectUri, this.logger, this.correlationId),
                prompt: this.getPrompt(request.prompt),
                correlationId: this.correlationId,
                tokenType: request.authenticationScheme,
                windowTitleSubstring: document.title,
                extraParameters: {
                    ...request.extraParameters,
                },
                extendedExpiryToken: false,
                keyId: request.popKid,
            };
            // Check for PoP token requests: signPopToken should only be set to true if popKid is not set
            if (validatedRequest.signPopToken && !!request.popKid) {
                throw createBrowserAuthError(invalidPopTokenRequest);
            }
            this.handleExtraBrokerParams(validatedRequest);
            validatedRequest.extraParameters =
                validatedRequest.extraParameters || {};
            validatedRequest.extraParameters.telemetry =
                PlatformAuthConstants.MATS_TELEMETRY;
            if (request.authenticationScheme === AuthenticationScheme$1.POP) {
                // add POP request type
                const shrParameters = {
                    resourceRequestUri: request.resourceRequestUri,
                    resourceRequestMethod: request.resourceRequestMethod,
                    shrClaims: request.shrClaims,
                    shrNonce: request.shrNonce,
                    correlationId: this.correlationId,
                };
                const popTokenGenerator = new PopTokenGenerator(this.browserCrypto, this.performanceClient);
                // generate reqCnf if not provided in the request
                let reqCnfData;
                if (!validatedRequest.keyId) {
                    const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, this.correlationId)(shrParameters, this.logger);
                    reqCnfData = generatedReqCnfData.reqCnfString;
                    validatedRequest.keyId = generatedReqCnfData.kid;
                    validatedRequest.signPopToken = true;
                }
                else {
                    reqCnfData = this.browserCrypto.base64UrlEncode(JSON.stringify({ kid: validatedRequest.keyId }));
                    validatedRequest.signPopToken = false;
                }
                // SPAs require whole string to be passed to broker
                validatedRequest.reqCnf = reqCnfData;
            }
            this.addRequestSKUs(validatedRequest);
            return validatedRequest;
        }
        async getCanonicalAuthority(request) {
            const requestAuthority = request.authority || this.config.auth.authority;
            const { azureCloudOptions, account } = request;
            if (account) {
                // validate authority
                await getDiscoveredAuthority(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, requestAuthority, azureCloudOptions, undefined, // requestExtraQueryParameters
                account);
            }
            const canonicalAuthority = new UrlString(requestAuthority);
            canonicalAuthority.validateAsUri();
            return canonicalAuthority;
        }
        getPrompt(prompt) {
            // If request is silent, prompt is always none
            switch (this.apiId) {
                case ApiId.ssoSilent:
                case ApiId.acquireTokenSilent_silentFlow:
                    this.logger.trace("12n1y2", this.correlationId);
                    return PromptValue$1.NONE;
            }
            // Prompt not provided, request may proceed and native broker decides if it needs to prompt
            if (!prompt) {
                this.logger.trace("0uid1p", this.correlationId);
                return undefined;
            }
            // If request is interactive, check if prompt provided is allowed to go directly to native broker
            switch (prompt) {
                case PromptValue$1.NONE:
                case PromptValue$1.CONSENT:
                case PromptValue$1.LOGIN:
                    this.logger.trace("0i0hco", this.correlationId);
                    return prompt;
                default:
                    this.logger.trace("0w3tpw", this.correlationId);
                    throw createBrowserAuthError(nativePromptNotSupported);
            }
        }
        /**
         * Handles extra broker request parameters
         * @param request {PlatformAuthRequest}
         * @private
         */
        handleExtraBrokerParams(request) {
            const hasExtraBrokerParams = request.extraParameters &&
                request.extraParameters.hasOwnProperty(BROKER_CLIENT_ID) &&
                request.extraParameters.hasOwnProperty(BROKER_REDIRECT_URI) &&
                request.extraParameters.hasOwnProperty(CLIENT_ID);
            if (!request.embeddedClientId && !hasExtraBrokerParams) {
                return;
            }
            let child_client_id = "";
            const child_redirect_uri = request.redirectUri;
            if (request.embeddedClientId) {
                request.redirectUri = this.config.auth.redirectUri;
                child_client_id = request.embeddedClientId;
            }
            else if (request.extraParameters) {
                request.redirectUri =
                    request.extraParameters[BROKER_REDIRECT_URI];
                child_client_id =
                    request.extraParameters[CLIENT_ID];
            }
            request.extraParameters = {
                child_client_id,
                child_redirect_uri,
            };
            this.performanceClient?.addFields({
                embeddedClientId: child_client_id,
                embeddedRedirectUri: child_redirect_uri,
            }, this.correlationId);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const clientDataAccountTypeMapping = new Map([
        ["e", "AAD"],
        ["m", "MSA"],
    ]);
    /**
     * Parses the clientdata response parameter from the /authorize endpoint.
     *
     * Logically, the clientdata value is URL-encoded and pipe-delimited:
     *   urlencoded(account_type | error | sub_error | cloud_instance | caller_data_boundary)
     *
     * In normal browser flows, this value may already have been URL-decoded
     * (e.g. by URLSearchParams). This function will only apply decodeURIComponent
     * when the string appears to contain percent-encoded sequences to avoid
     * double-decoding.
     *
     * @param clientdata - The raw clientdata string from the authorize response
     * @returns Parsed ClientData object, or null if the input is empty/invalid
     */
    function parseClientData(clientdata) {
        if (!clientdata) {
            return null;
        }
        try {
            // Only decode when the string appears to contain percent-encoded sequences
            const shouldDecode = /%(?:[0-9A-Fa-f]{2})/.test(clientdata);
            const decoded = shouldDecode
                ? decodeURIComponent(clientdata)
                : clientdata;
            const parts = decoded.split("|");
            if (parts.length < 5) {
                return null;
            }
            return {
                accountType: clientDataAccountTypeMapping.get(parts[0]?.trim() || "") || "",
                error: parts[1]?.trim() || "",
                subError: parts[2]?.trim() || "",
                cloudInstance: parts[3]?.trim() || "",
                callerDataBoundary: parts[4]?.trim() || "",
            };
        }
        catch {
            return null;
        }
    }
    /**
     * Instruments account type, error, and suberror from clientdata
     */
    function instrumentClientData(response, correlationId, performanceClient) {
        const parsed = parseClientData(response.clientdata);
        parsed?.accountType &&
            performanceClient.addFields({ accountType: parsed.accountType }, correlationId);
        parsed?.error &&
            performanceClient.addFields({ serverErrorNo: parsed.error }, correlationId);
        parsed?.subError &&
            performanceClient.addFields({ serverSubErrorNo: parsed.subError }, correlationId);
    }
    /**
     * Returns map of parameters that are applicable to all calls to /authorize whether using PKCE or EAR
     * @param config
     * @param authority
     * @param request
     * @param logger
     * @param performanceClient
     * @returns
     */
    async function getStandardParameters(config, authority, request, logger, performanceClient) {
        const parameters = getStandardAuthorizeRequestParameters({ ...config.auth, authority: authority }, request, logger, performanceClient);
        addLibraryInfo(parameters, {
            sku: BrowserConstants.MSAL_SKU,
            version: version,
            os: "",
            cpu: "",
        });
        if (config.system.protocolMode !== ProtocolMode.OIDC) {
            addApplicationTelemetry(parameters, config.telemetry.application);
        }
        if (request.platformBroker) {
            // signal ests that this is a WAM call
            addNativeBroker(parameters);
            // instrument JS-platform bridge specific fields
            performanceClient.addFields({
                isPlatformAuthorizeRequest: true,
            }, request.correlationId);
            // pass the req_cnf for POP
            if (request.authenticationScheme === AuthenticationScheme$1.POP) {
                const cryptoOps = new CryptoOps(logger, performanceClient);
                const popTokenGenerator = new PopTokenGenerator(cryptoOps, performanceClient);
                // req_cnf is always sent as a string for SPAs
                let reqCnfData;
                if (!request.popKid) {
                    const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, logger, performanceClient, request.correlationId)(request, logger);
                    reqCnfData = generatedReqCnfData.reqCnfString;
                }
                else {
                    reqCnfData = cryptoOps.encodeKid(request.popKid);
                }
                addPopToken(parameters, reqCnfData);
            }
        }
        instrumentBrokerParams(parameters, request.correlationId, performanceClient);
        return parameters;
    }
    /**
     * Gets the full /authorize URL with request parameters when using Auth Code + PKCE
     * @param config
     * @param authority
     * @param request
     * @param logger
     * @param performanceClient
     * @returns
     */
    async function getAuthCodeRequestUrl(config, authority, request, logger, performanceClient) {
        if (!request.codeChallenge) {
            throw createClientConfigurationError(pkceParamsMissing);
        }
        const parameters = await invokeAsync(getStandardParameters, GetStandardParams, logger, performanceClient, request.correlationId)(config, authority, request, logger, performanceClient);
        addResponseType(parameters, OAuthResponseType.CODE);
        addCodeChallengeParams(parameters, request.codeChallenge, S256_CODE_CHALLENGE_METHOD);
        // Merge extraQueryParameters and extraParameters to be appended to request URL
        addExtraParameters(parameters, {
            ...request.extraQueryParameters,
            ...request.extraParameters,
        });
        return getAuthorizeUrl(authority, parameters);
    }
    /**
     * Gets the form that will be posted to /authorize with request parameters when using EAR
     */
    async function getEARForm(frame, config, authority, request, logger, performanceClient) {
        if (!request.earJwk) {
            throw createBrowserAuthError(earJwkEmpty);
        }
        const parameters = await getStandardParameters(config, authority, request, logger, performanceClient);
        addResponseType(parameters, OAuthResponseType.IDTOKEN_TOKEN_REFRESHTOKEN);
        addEARParameters(parameters, request.earJwk);
        // Also add codeChallenge as backup in case EAR is not supported
        addCodeChallengeParams(parameters, request.codeChallenge, S256_CODE_CHALLENGE_METHOD);
        addExtraParameters(parameters, {
            ...request.extraParameters,
        });
        const queryParams = new Map();
        addExtraParameters(queryParams, request.extraQueryParameters || {});
        // Add correlationId to query params so gateway can propagate it to IDPs
        addCorrelationId(queryParams, request.correlationId);
        const url = getAuthorizeUrl(authority, queryParams);
        return createForm(frame, url, parameters);
    }
    /**
     * Gets the form that will be posted to /authorize with request parameters when using POST method
     */
    async function getCodeForm(frame, config, authority, request, logger, performanceClient) {
        const parameters = await getStandardParameters(config, authority, request, logger, performanceClient);
        addResponseType(parameters, OAuthResponseType.CODE);
        addCodeChallengeParams(parameters, request.codeChallenge, request.codeChallengeMethod || S256_CODE_CHALLENGE_METHOD);
        // Add extraParameters to the request body
        addExtraParameters(parameters, {
            ...request.extraParameters,
        });
        // Add extraQueryParameters to be appended to request URL
        const queryParams = new Map();
        addExtraParameters(queryParams, request.extraQueryParameters || {});
        // Add correlationId to query params so gateway can propagate it to IDPs
        addCorrelationId(queryParams, request.correlationId);
        const url = getAuthorizeUrl(authority, queryParams);
        return createForm(frame, url, parameters);
    }
    /**
     * Creates form element in the provided document with auth parameters in the post body
     * @param frame
     * @param authorizeUrl
     * @param parameters
     * @returns
     */
    function createForm(frame, authorizeUrl, parameters) {
        const form = frame.createElement("form");
        form.method = "post";
        form.action = authorizeUrl;
        parameters.forEach((value, key) => {
            const param = frame.createElement("input");
            param.hidden = true;
            param.name = key;
            param.value = value;
            form.appendChild(param);
        });
        frame.body.appendChild(form);
        return form;
    }
    /**
     * Response handler when server returns accountId on the /authorize request
     * @param request
     * @param accountId
     * @param apiId
     * @param config
     * @param browserStorage
     * @param nativeStorage
     * @param eventHandler
     * @param logger
     * @param performanceClient
     * @param nativeMessageHandler
     * @returns
     */
    async function handleResponsePlatformBroker(request, accountId, apiId, config, browserStorage, nativeStorage, eventHandler, logger, performanceClient, platformAuthProvider) {
        logger.verbose("11qcow", request.correlationId);
        if (!platformAuthProvider) {
            throw createBrowserAuthError(nativeConnectionNotEstablished);
        }
        const browserCrypto = new CryptoOps(logger, performanceClient);
        const nativeInteractionClient = new PlatformAuthInteractionClient(config, browserStorage, browserCrypto, logger, eventHandler, config.system.navigationClient, apiId, performanceClient, platformAuthProvider, accountId, nativeStorage, request.correlationId);
        const { userRequestState } = parseRequestState(browserCrypto.base64Decode, request.state);
        return invokeAsync(nativeInteractionClient.acquireToken.bind(nativeInteractionClient), NativeInteractionClientAcquireToken, logger, performanceClient, request.correlationId)({
            ...request,
            state: userRequestState,
            prompt: undefined, // Server should handle the prompt, ideally native broker can do this part silently
        });
    }
    /**
     * Response handler when server returns code on the /authorize request
     * @param request
     * @param response
     * @param codeVerifier
     * @param authClient
     * @param browserStorage
     * @param logger
     * @param performanceClient
     * @returns
     */
    async function handleResponseCode(request, response, codeVerifier, apiId, config, authClient, browserStorage, nativeStorage, eventHandler, logger, performanceClient, platformAuthProvider) {
        // Remove throttle if it exists
        ThrottlingUtils.removeThrottle(browserStorage, config.auth.clientId, request);
        // Instrument clientdata telemetry fields from the authorize response
        instrumentClientData(response, request.correlationId, performanceClient);
        if (response.accountId) {
            return invokeAsync(handleResponsePlatformBroker, HandleResponsePlatformBroker, logger, performanceClient, request.correlationId)(request, response.accountId, apiId, config, browserStorage, nativeStorage, eventHandler, logger, performanceClient, platformAuthProvider);
        }
        const authCodeRequest = {
            ...request,
            code: response.code || "",
            codeVerifier: codeVerifier,
        };
        // Create popup interaction handler.
        const interactionHandler = new InteractionHandler(authClient, browserStorage, authCodeRequest, logger, performanceClient);
        // Handle response from hash string.
        const result = await invokeAsync(interactionHandler.handleCodeResponse.bind(interactionHandler), HandleCodeResponse, logger, performanceClient, request.correlationId)(response, request, apiId);
        return result;
    }
    /**
     * Response handler when server returns ear_jwe on the /authorize request
     * @param request
     * @param response
     * @param apiId
     * @param config
     * @param authority
     * @param browserStorage
     * @param nativeStorage
     * @param eventHandler
     * @param logger
     * @param performanceClient
     * @param nativeMessageHandler
     * @returns
     */
    async function handleResponseEAR(request, response, apiId, config, authority, browserStorage, nativeStorage, eventHandler, logger, performanceClient, platformAuthProvider) {
        // Remove throttle if it exists
        ThrottlingUtils.removeThrottle(browserStorage, config.auth.clientId, request);
        // Instrument clientdata telemetry fields from the authorize response
        instrumentClientData(response, request.correlationId, performanceClient);
        // Validate state & check response for errors
        validateAuthorizationResponse(response, request.state);
        if (!response.ear_jwe) {
            throw createBrowserAuthError(earJweEmpty);
        }
        if (!request.earJwk) {
            throw createBrowserAuthError(earJwkEmpty);
        }
        const decryptedData = JSON.parse(await invokeAsync(decryptEarResponse, DecryptEarResponse, logger, performanceClient, request.correlationId)(request.earJwk, response.ear_jwe));
        if (decryptedData.accountId) {
            return invokeAsync(handleResponsePlatformBroker, HandleResponsePlatformBroker, logger, performanceClient, request.correlationId)(request, decryptedData.accountId, apiId, config, browserStorage, nativeStorage, eventHandler, logger, performanceClient, platformAuthProvider);
        }
        const responseHandler = new ResponseHandler(config.auth.clientId, browserStorage, new CryptoOps(logger, performanceClient), logger, performanceClient, null, null);
        // Validate response. This function throws a server error if an error is returned by the server.
        responseHandler.validateTokenResponse(decryptedData, request.correlationId);
        // Temporary until response handler is refactored to be more flow agnostic.
        const additionalData = {
            code: "",
            state: request.state,
            nonce: request.nonce,
            client_info: decryptedData.client_info,
            cloud_graph_host_name: decryptedData.cloud_graph_host_name,
            cloud_instance_host_name: decryptedData.cloud_instance_host_name,
            cloud_instance_name: decryptedData.cloud_instance_name,
            msgraph_host: decryptedData.msgraph_host,
        };
        return (await invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, logger, performanceClient, request.correlationId)(decryptedData, authority, nowSeconds(), request, apiId, additionalData, undefined, undefined, undefined, undefined));
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    // Constant byte array length
    const RANDOM_BYTE_ARR_LENGTH = 32;
    /**
     * This file defines APIs to generate PKCE codes and code verifiers.
     */
    /**
     * Generates PKCE Codes. See the RFC for more information: https://tools.ietf.org/html/rfc7636
     */
    async function generatePkceCodes(performanceClient, logger, correlationId) {
        const codeVerifier = invoke(generateCodeVerifier, GenerateCodeVerifier, logger, performanceClient, correlationId)(performanceClient, logger, correlationId);
        const codeChallenge = await invokeAsync(generateCodeChallengeFromVerifier, GenerateCodeChallengeFromVerifier, logger, performanceClient, correlationId)(codeVerifier, performanceClient, logger, correlationId);
        return {
            verifier: codeVerifier,
            challenge: codeChallenge,
        };
    }
    /**
     * Generates a random 32 byte buffer and returns the base64
     * encoded string to be used as a PKCE Code Verifier
     */
    function generateCodeVerifier(performanceClient, logger, correlationId) {
        try {
            // Generate random values as utf-8
            const buffer = new Uint8Array(RANDOM_BYTE_ARR_LENGTH);
            invoke(getRandomValues, GetRandomValues, logger, performanceClient, correlationId)(buffer);
            // encode verifier as base64
            const pkceCodeVerifierB64 = urlEncodeArr(buffer);
            return pkceCodeVerifierB64;
        }
        catch (e) {
            throw createBrowserAuthError(pkceNotCreated);
        }
    }
    /**
     * Creates a base64 encoded PKCE Code Challenge string from the
     * hash created from the PKCE Code Verifier supplied
     */
    async function generateCodeChallengeFromVerifier(pkceCodeVerifier, performanceClient, logger, correlationId) {
        try {
            // hashed verifier
            const pkceHashedCodeVerifier = await invokeAsync(sha256Digest, Sha256Digest, logger, performanceClient, correlationId)(pkceCodeVerifier);
            // encode hash as base64
            return urlEncodeArr(new Uint8Array(pkceHashedCodeVerifier));
        }
        catch (e) {
            throw createBrowserAuthError(pkceNotCreated);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class NavigationClient {
        /**
         * Navigates to other pages within the same web application
         * @param url
         * @param options
         */
        navigateInternal(url, options) {
            return NavigationClient.defaultNavigateWindow(url, options);
        }
        /**
         * Navigates to other pages outside the web application i.e. the Identity Provider
         * @param url
         * @param options
         */
        navigateExternal(url, options) {
            return NavigationClient.defaultNavigateWindow(url, options);
        }
        /**
         * Default navigation implementation invoked by the internal and external functions
         * @param url
         * @param options
         */
        static defaultNavigateWindow(url, options) {
            if (options.noHistory) {
                window.location.replace(url); // CodeQL [SM03712] Application owner controls the URL. User can't change it.
            }
            else {
                window.location.assign(url); // CodeQL [SM03712] Application owner controls the URL. User can't change it.
            }
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    reject(createBrowserAuthError(timedOut, "failed_to_redirect"));
                }, options.timeout);
            });
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * This class implements the Fetch API for GET and POST requests. See more here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
     */
    class FetchClient {
        /**
         * Fetch Client for REST endpoints - Get request
         * @param url
         * @param headers
         * @param body
         */
        async sendGetRequestAsync(url, options) {
            let response;
            let responseHeaders = {};
            let responseStatus = 0;
            const reqHeaders = getFetchHeaders(options);
            try {
                response = await fetch(url, {
                    method: HTTP_REQUEST_TYPE.GET,
                    headers: reqHeaders,
                });
            }
            catch (e) {
                throw createNetworkError(createBrowserAuthError(window.navigator.onLine
                    ? getRequestFailed
                    : noNetworkConnectivity), undefined, undefined, e);
            }
            responseHeaders = getHeaderDict(response.headers);
            try {
                responseStatus = response.status;
                return {
                    headers: responseHeaders,
                    body: (await response.json()),
                    status: responseStatus,
                };
            }
            catch (e) {
                throw createNetworkError(createBrowserAuthError(failedToParseResponse), responseStatus, responseHeaders, e);
            }
        }
        /**
         * Fetch Client for REST endpoints - Post request
         * @param url
         * @param headers
         * @param body
         */
        async sendPostRequestAsync(url, options) {
            const reqBody = (options && options.body) || "";
            const reqHeaders = getFetchHeaders(options);
            let response;
            let responseStatus = 0;
            let responseHeaders = {};
            try {
                response = await fetch(url, {
                    method: HTTP_REQUEST_TYPE.POST,
                    headers: reqHeaders,
                    body: reqBody,
                });
            }
            catch (e) {
                throw createNetworkError(createBrowserAuthError(window.navigator.onLine
                    ? postRequestFailed
                    : noNetworkConnectivity), undefined, undefined, e);
            }
            responseHeaders = getHeaderDict(response.headers);
            try {
                responseStatus = response.status;
                return {
                    headers: responseHeaders,
                    body: (await response.json()),
                    status: responseStatus,
                };
            }
            catch (e) {
                throw createNetworkError(createBrowserAuthError(failedToParseResponse), responseStatus, responseHeaders, e);
            }
        }
    }
    /**
     * Get Fetch API Headers object from string map
     * @param inputHeaders
     */
    function getFetchHeaders(options) {
        try {
            const headers = new Headers();
            if (!(options && options.headers)) {
                return headers;
            }
            const optionsHeaders = options.headers;
            Object.entries(optionsHeaders).forEach(([key, value]) => {
                headers.append(key, value);
            });
            return headers;
        }
        catch (e) {
            throw createNetworkError(createBrowserAuthError(failedToBuildHeaders), undefined, undefined, e);
        }
    }
    /**
     * Returns object representing response headers
     * @param headers
     * @returns
     */
    function getHeaderDict(headers) {
        try {
            const headerDict = {};
            headers.forEach((value, key) => {
                headerDict[key] = value;
            });
            return headerDict;
        }
        catch (e) {
            throw createBrowserAuthError(failedToParseHeaders);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    // Default timeout for popup windows and iframes in milliseconds
    const DEFAULT_POPUP_TIMEOUT_MS = 60000;
    const DEFAULT_IFRAME_TIMEOUT_MS = 10000;
    const DEFAULT_REDIRECT_TIMEOUT_MS = 30000;
    const DEFAULT_NATIVE_BROKER_HANDSHAKE_TIMEOUT_MS = 2000;
    /**
     * MSAL function that sets the default options when not explicitly configured from app developer
     *
     * @param auth
     * @param cache
     * @param system
     *
     * @returns Configuration object
     */
    function buildConfiguration({ auth: userInputAuth, cache: userInputCache, system: userInputSystem, experimental: userInputExperimental, telemetry: userInputTelemetry, }, isBrowserEnvironment) {
        // Default auth options for browser
        const DEFAULT_AUTH_OPTIONS = {
            clientId: "",
            authority: `${DEFAULT_AUTHORITY}`,
            knownAuthorities: [],
            cloudDiscoveryMetadata: "",
            authorityMetadata: "",
            redirectUri: typeof window !== "undefined" && window.location
                ? window.location.href.split("?")[0].split("#")[0]
                : "",
            postLogoutRedirectUri: "",
            clientCapabilities: [],
            OIDCOptions: {
                responseMode: ResponseMode$1.FRAGMENT,
                defaultScopes: [
                    OPENID_SCOPE,
                    PROFILE_SCOPE,
                    OFFLINE_ACCESS_SCOPE,
                ],
            },
            azureCloudOptions: {
                azureCloudInstance: AzureCloudInstance.None,
                tenant: "",
            },
            instanceAware: false,
            isMcp: false,
            verifySSO: false,
        };
        // Default cache options for browser
        const DEFAULT_CACHE_OPTIONS = {
            cacheLocation: BrowserCacheLocation.SessionStorage,
            cacheRetentionDays: 5,
        };
        // Default logger options for browser
        const DEFAULT_LOGGER_OPTIONS = {
            // eslint-disable-next-line @typescript-eslint/no-empty-function
            loggerCallback: () => {
                // allow users to not set logger call back
            },
            logLevel: exports.LogLevel.Info,
            piiLoggingEnabled: false,
        };
        // Default system options for browser
        const DEFAULT_BROWSER_SYSTEM_OPTIONS = {
            ...DEFAULT_SYSTEM_OPTIONS,
            loggerOptions: DEFAULT_LOGGER_OPTIONS,
            networkClient: isBrowserEnvironment
                ? new FetchClient()
                : StubbedNetworkModule,
            navigationClient: new NavigationClient(),
            popupBridgeTimeout: userInputSystem?.popupBridgeTimeout || DEFAULT_POPUP_TIMEOUT_MS,
            iframeBridgeTimeout: userInputSystem?.iframeBridgeTimeout || DEFAULT_IFRAME_TIMEOUT_MS,
            redirectNavigationTimeout: DEFAULT_REDIRECT_TIMEOUT_MS,
            allowRedirectInIframe: false,
            navigatePopups: true,
            allowPlatformBroker: false,
            nativeBrokerHandshakeTimeout: userInputSystem?.nativeBrokerHandshakeTimeout ||
                DEFAULT_NATIVE_BROKER_HANDSHAKE_TIMEOUT_MS,
            protocolMode: ProtocolMode.AAD,
        };
        const providedSystemOptions = {
            ...DEFAULT_BROWSER_SYSTEM_OPTIONS,
            ...userInputSystem,
            loggerOptions: userInputSystem?.loggerOptions || DEFAULT_LOGGER_OPTIONS,
        };
        const DEFAULT_TELEMETRY_OPTIONS = {
            application: {
                appName: "",
                appVersion: "",
            },
            client: new StubPerformanceClient(),
        };
        const DEFAULT_EXPERIMENTAL_OPTIONS = {
            iframeTimeoutTelemetry: false,
        };
        // Throw an error if user has set OIDCOptions without being in OIDC protocol mode
        if (userInputSystem?.protocolMode !== ProtocolMode.OIDC &&
            userInputAuth?.OIDCOptions) {
            const logger = new Logger(providedSystemOptions.loggerOptions);
            logger.warning(JSON.stringify(createClientConfigurationError(cannotSetOIDCOptions)), "");
        }
        // Throw an error if user has set allowPlatformBroker to true with OIDC protocol mode
        if (userInputSystem?.protocolMode &&
            userInputSystem.protocolMode === ProtocolMode.OIDC &&
            providedSystemOptions?.allowPlatformBroker) {
            throw createClientConfigurationError(cannotAllowPlatformBroker);
        }
        const overlayedConfig = {
            auth: {
                ...DEFAULT_AUTH_OPTIONS,
                ...userInputAuth,
                OIDCOptions: {
                    ...DEFAULT_AUTH_OPTIONS.OIDCOptions,
                    ...userInputAuth?.OIDCOptions,
                },
            },
            cache: { ...DEFAULT_CACHE_OPTIONS, ...userInputCache },
            system: providedSystemOptions,
            experimental: {
                ...DEFAULT_EXPERIMENTAL_OPTIONS,
                ...userInputExperimental,
            },
            telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...userInputTelemetry },
        };
        return overlayedConfig;
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class PlatformAuthExtensionHandler {
        constructor(logger, handshakeTimeoutMs, performanceClient, extensionId) {
            this.logger = logger;
            this.handshakeTimeoutMs = handshakeTimeoutMs;
            this.extensionId = extensionId;
            this.resolvers = new Map(); // Used for non-handshake messages
            this.handshakeResolvers = new Map(); // Used for handshake messages
            this.messageChannel = new MessageChannel();
            this.windowListener = this.onWindowMessage.bind(this); // Window event callback doesn't have access to 'this' unless it's bound
            this.performanceClient = performanceClient;
            this.handshakeEvent = performanceClient.startMeasurement(NativeMessageHandlerHandshake);
            this.platformAuthType =
                PlatformAuthConstants.PLATFORM_EXTENSION_PROVIDER;
        }
        /**
         * Sends a given message to the extension and resolves with the extension response
         * @param request
         */
        async sendMessage(request) {
            this.logger.trace("0on4p2", request.correlationId);
            // fall back to native calls
            const messageBody = {
                method: NativeExtensionMethod.GetToken,
                request: request,
            };
            const req = {
                channel: PlatformAuthConstants.CHANNEL_ID,
                extensionId: this.extensionId,
                responseId: createNewGuid(),
                body: messageBody,
            };
            this.logger.trace("1qadfi", request.correlationId);
            this.logger.tracePii("1xm533", request.correlationId);
            this.messageChannel.port1.postMessage(req);
            const response = await new Promise((resolve, reject) => {
                this.resolvers.set(req.responseId, { resolve, reject });
            });
            const validatedResponse = this.validatePlatformBrokerResponse(response);
            return validatedResponse;
        }
        /**
         * Returns an instance of the MessageHandler that has successfully established a connection with an extension
         * @param {Logger} logger
         * @param {number} handshakeTimeoutMs
         * @param {IPerformanceClient} performanceClient
         * @param {ICrypto} crypto
         */
        static async createProvider(logger, handshakeTimeoutMs, performanceClient, correlationId) {
            logger.trace("15zfnw", correlationId);
            try {
                const preferredProvider = new PlatformAuthExtensionHandler(logger, handshakeTimeoutMs, performanceClient, PlatformAuthConstants.PREFERRED_EXTENSION_ID);
                await preferredProvider.sendHandshakeRequest(correlationId);
                return preferredProvider;
            }
            catch (e) {
                // If preferred extension fails for whatever reason, fallback to using any installed extension
                const backupProvider = new PlatformAuthExtensionHandler(logger, handshakeTimeoutMs, performanceClient);
                await backupProvider.sendHandshakeRequest(correlationId);
                return backupProvider;
            }
        }
        /**
         * Send handshake request helper.
         */
        async sendHandshakeRequest(correlationId) {
            this.logger.trace("1dpg9o", correlationId);
            // Register this event listener before sending handshake
            window.addEventListener("message", this.windowListener, false); // false is important, because content script message processing should work first
            const req = {
                channel: PlatformAuthConstants.CHANNEL_ID,
                extensionId: this.extensionId,
                responseId: createNewGuid(),
                body: {
                    method: NativeExtensionMethod.HandshakeRequest,
                },
            };
            this.handshakeEvent.add({
                extensionId: this.extensionId,
                extensionHandshakeTimeoutMs: this.handshakeTimeoutMs,
            });
            this.messageChannel.port1.onmessage = (event) => {
                this.onChannelMessage(event);
            };
            window.postMessage(req, window.origin, [this.messageChannel.port2]);
            return new Promise((resolve, reject) => {
                this.handshakeResolvers.set(req.responseId, { resolve, reject });
                this.timeoutId = window.setTimeout(() => {
                    /*
                     * Throw an error if neither HandshakeResponse nor original Handshake request are received in a reasonable timeframe.
                     * This typically suggests an event handler stopped propagation of the Handshake request but did not respond to it on the MessageChannel port
                     */
                    window.removeEventListener("message", this.windowListener, false);
                    this.messageChannel.port1.close();
                    this.messageChannel.port2.close();
                    this.handshakeEvent.end({
                        extensionHandshakeTimedOut: true,
                        success: false,
                    });
                    reject(createBrowserAuthError(nativeHandshakeTimeout));
                    this.handshakeResolvers.delete(req.responseId);
                }, this.handshakeTimeoutMs); // Use a reasonable timeout in milliseconds here
            });
        }
        /**
         * Invoked when a message is posted to the window. If a handshake request is received it means the extension is not installed.
         * @param event
         */
        onWindowMessage(event) {
            const correlationId = createGuid();
            this.logger.trace("0jpn5u", correlationId);
            // We only accept messages from ourselves
            if (event.source !== window) {
                return;
            }
            const request = event.data;
            if (!request.channel ||
                request.channel !== PlatformAuthConstants.CHANNEL_ID) {
                return;
            }
            if (request.extensionId && request.extensionId !== this.extensionId) {
                return;
            }
            if (request.body.method === NativeExtensionMethod.HandshakeRequest) {
                const handshakeResolver = this.handshakeResolvers.get(request.responseId);
                /*
                 * Filter out responses with no matched resolvers sooner to keep channel ports open while waiting for
                 * the proper response.
                 */
                if (!handshakeResolver) {
                    this.logger.trace("07buhm", correlationId);
                    return;
                }
                // If we receive this message back it means no extension intercepted the request, meaning no extension supporting handshake protocol is installed
                this.logger.verbose(request.extensionId
                    ? "0xrkug"
                    : "No extension installed", correlationId);
                clearTimeout(this.timeoutId);
                this.messageChannel.port1.close();
                this.messageChannel.port2.close();
                window.removeEventListener("message", this.windowListener, false);
                this.handshakeEvent.end({
                    success: false,
                    extensionInstalled: false,
                });
                handshakeResolver.reject(createBrowserAuthError(nativeExtensionNotInstalled));
            }
        }
        /**
         * Invoked when a message is received from the extension on the MessageChannel port
         * @param event
         */
        onChannelMessage(event) {
            const correlationId = createGuid();
            this.logger.trace("1py8yf", correlationId);
            const request = event.data;
            const resolver = this.resolvers.get(request.responseId);
            const handshakeResolver = this.handshakeResolvers.get(request.responseId);
            try {
                const method = request.body.method;
                if (method === NativeExtensionMethod.Response) {
                    if (!resolver) {
                        return;
                    }
                    const response = request.body.response;
                    this.logger.trace("19hpgm", correlationId);
                    this.logger.tracePii("179a24", correlationId);
                    if (response.status !== "Success") {
                        resolver.reject(createNativeAuthError(response.code, response.description, response.ext));
                    }
                    else if (response.result) {
                        if (response.result["code"] &&
                            response.result["description"]) {
                            resolver.reject(createNativeAuthError(response.result["code"], response.result["description"], response.result["ext"]));
                        }
                        else {
                            resolver.resolve(response.result);
                        }
                    }
                    else {
                        throw createAuthError(unexpectedError, "Event does not contain result.");
                    }
                    this.resolvers.delete(request.responseId);
                }
                else if (method === NativeExtensionMethod.HandshakeResponse) {
                    if (!handshakeResolver) {
                        this.logger.trace("082qnt", correlationId);
                        return;
                    }
                    clearTimeout(this.timeoutId); // Clear setTimeout
                    window.removeEventListener("message", this.windowListener, false); // Remove 'No extension' listener
                    this.extensionId = request.extensionId;
                    this.extensionVersion = request.body.version;
                    this.logger.verbose("0yf5ib", correlationId);
                    this.handshakeEvent.end({
                        extensionInstalled: true,
                        success: true,
                    });
                    handshakeResolver.resolve();
                    this.handshakeResolvers.delete(request.responseId);
                }
                // Do nothing if method is not Response or HandshakeResponse
            }
            catch (err) {
                this.logger.error("0xf978", correlationId);
                this.logger.errorPii("04i99o", correlationId);
                this.logger.errorPii("0xdvsy", correlationId);
                if (resolver) {
                    resolver.reject(err);
                }
                else if (handshakeResolver) {
                    handshakeResolver.reject(err);
                }
            }
        }
        /**
         * Validates native platform response before processing
         * @param response
         */
        validatePlatformBrokerResponse(response) {
            if (response.hasOwnProperty("access_token") &&
                response.hasOwnProperty("id_token") &&
                response.hasOwnProperty("client_info") &&
                response.hasOwnProperty("account") &&
                response.hasOwnProperty("scope") &&
                response.hasOwnProperty("expires_in")) {
                return response;
            }
            else {
                throw createAuthError(unexpectedError, "Response missing expected properties.");
            }
        }
        /**
         * Returns the Id for the browser extension this handler is communicating with
         * @returns
         */
        getExtensionId() {
            return this.extensionId;
        }
        /**
         * Returns the version for the browser extension this handler is communicating with
         * @returns
         */
        getExtensionVersion() {
            return this.extensionVersion;
        }
        getExtensionName() {
            return this.getExtensionId() ===
                PlatformAuthConstants.PREFERRED_EXTENSION_ID
                ? "chrome"
                : this.getExtensionId()?.length
                    ? "unknown"
                    : undefined;
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class PlatformAuthDOMHandler {
        constructor(logger, performanceClient, correlationId) {
            this.logger = logger;
            this.performanceClient = performanceClient;
            this.correlationId = correlationId;
            this.platformAuthType = PlatformAuthConstants.PLATFORM_DOM_PROVIDER;
        }
        static async createProvider(logger, performanceClient, correlationId) {
            logger.trace("12mj4a", correlationId);
            // @ts-ignore
            if (window.navigator?.platformAuthentication) {
                const supportedContracts = 
                // @ts-ignore
                await window.navigator.platformAuthentication.getSupportedContracts(PlatformAuthConstants.MICROSOFT_ENTRA_BROKERID);
                if (supportedContracts?.includes(PlatformAuthConstants.PLATFORM_DOM_APIS)) {
                    logger.trace("1h5q1r", correlationId);
                    return new PlatformAuthDOMHandler(logger, performanceClient, correlationId);
                }
            }
            return undefined;
        }
        /**
         * Returns the Id for the broker extension this handler is communicating with
         * @returns
         */
        getExtensionId() {
            return PlatformAuthConstants.MICROSOFT_ENTRA_BROKERID;
        }
        getExtensionVersion() {
            return "";
        }
        getExtensionName() {
            return PlatformAuthConstants.DOM_API_NAME;
        }
        /**
         * Send token request to platform broker via browser DOM API
         * @param request
         * @returns
         */
        async sendMessage(request) {
            this.logger.trace("02bcil", request.correlationId);
            try {
                const platformDOMRequest = this.initializePlatformDOMRequest(request);
                const response = 
                // @ts-ignore
                await window.navigator.platformAuthentication.executeGetToken(platformDOMRequest);
                return this.validatePlatformBrokerResponse(response, request.correlationId);
            }
            catch (e) {
                this.logger.error("11im7g", request.correlationId);
                throw e;
            }
        }
        initializePlatformDOMRequest(request) {
            this.logger.trace("15d6yv", request.correlationId);
            const { accountId, clientId, authority, scope, redirectUri, correlationId, state, storeInCache, embeddedClientId, extraParameters, ...remainingProperties } = request;
            const validExtraParameters = this.getDOMExtraParams(remainingProperties, correlationId);
            const platformDOMRequest = {
                accountId: accountId,
                brokerId: this.getExtensionId(),
                authority: authority,
                clientId: clientId,
                correlationId: correlationId || this.correlationId,
                extraParameters: {
                    ...extraParameters,
                    ...validExtraParameters,
                },
                isSecurityTokenService: false,
                redirectUri: redirectUri,
                scope: scope,
                state: state,
                storeInCache: storeInCache,
                embeddedClientId: embeddedClientId,
            };
            return platformDOMRequest;
        }
        validatePlatformBrokerResponse(response, correlationId) {
            if (response.hasOwnProperty("isSuccess")) {
                if (response.hasOwnProperty("accessToken") &&
                    response.hasOwnProperty("idToken") &&
                    response.hasOwnProperty("clientInfo") &&
                    response.hasOwnProperty("account") &&
                    response.hasOwnProperty("scopes") &&
                    response.hasOwnProperty("expiresIn")) {
                    this.logger.trace("0h4vei", correlationId);
                    return this.convertToPlatformBrokerResponse(response, correlationId);
                }
                else if (response.hasOwnProperty("error")) {
                    const errorResponse = response;
                    if (errorResponse.isSuccess === false &&
                        errorResponse.error &&
                        errorResponse.error.code) {
                        this.logger.trace("0g92vm", correlationId);
                        throw createNativeAuthError(errorResponse.error.code, errorResponse.error.description, {
                            error: parseInt(errorResponse.error.errorCode),
                            protocol_error: errorResponse.error.protocolError,
                            status: errorResponse.error.status,
                            properties: errorResponse.error.properties,
                        });
                    }
                }
            }
            throw createAuthError(unexpectedError, "Response missing expected properties.");
        }
        convertToPlatformBrokerResponse(response, correlationId) {
            this.logger.trace("14913t", correlationId);
            const nativeResponse = {
                access_token: response.accessToken,
                id_token: response.idToken,
                client_info: response.clientInfo,
                account: response.account,
                expires_in: response.expiresIn,
                scope: response.scopes,
                state: response.state || "",
                properties: response.properties || {},
                extendedLifetimeToken: response.extendedLifetimeToken ?? false,
                shr: response.proofOfPossessionPayload,
            };
            return nativeResponse;
        }
        getDOMExtraParams(extraParameters, correlationId) {
            try {
                const stringifiedProperties = {};
                for (const [key, value] of Object.entries(extraParameters)) {
                    if (!value) {
                        continue;
                    }
                    if (typeof value === "object") {
                        stringifiedProperties[key] = JSON.stringify(value);
                    }
                    else {
                        stringifiedProperties[key] = String(value);
                    }
                }
                return stringifiedProperties;
            }
            catch (e) {
                this.logger.error("0eu9o3", correlationId);
                this.logger.errorPii("17rpl5", correlationId);
                return {};
            }
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Checks if the platform broker is available in the current environment.
     * @param loggerOptions
     * @param perfClient
     * @param correlationId
     * @returns
     */
    async function isPlatformBrokerAvailable(loggerOptions, perfClient, correlationId) {
        const logger = new Logger(loggerOptions || {}, name, version);
        const cid = correlationId || "";
        logger.trace("07660b", cid);
        const performanceClient = perfClient || new StubPerformanceClient();
        if (typeof window === "undefined") {
            logger.trace("082ed3", cid);
            return false;
        }
        return !!(await getPlatformAuthProvider(logger, performanceClient, cid));
    }
    async function getPlatformAuthProvider(logger, performanceClient, correlationId, nativeBrokerHandshakeTimeout) {
        logger.trace("134j0v", correlationId);
        const enablePlatformBrokerDOMSupport = isDomEnabledForPlatformAuth();
        logger.trace("04c81g", correlationId);
        let platformAuthProvider;
        try {
            if (enablePlatformBrokerDOMSupport) {
                // Check if DOM platform API is supported first
                platformAuthProvider = await PlatformAuthDOMHandler.createProvider(logger, performanceClient, correlationId);
            }
            if (!platformAuthProvider) {
                logger.trace("0l3na8", correlationId);
                /*
                 * If DOM APIs are not available, check if browser extension is available.
                 * Platform authentication via DOM APIs is preferred over extension APIs.
                 */
                platformAuthProvider =
                    await PlatformAuthExtensionHandler.createProvider(logger, nativeBrokerHandshakeTimeout ||
                        DEFAULT_NATIVE_BROKER_HANDSHAKE_TIMEOUT_MS, performanceClient, correlationId);
            }
        }
        catch (e) {
            logger.trace("0icbd7", e);
        }
        return platformAuthProvider;
    }
    /**
     * Returns true if the DOM API support for platform auth is enabled in session storage
     * @returns boolean
     * @deprecated
     */
    function isDomEnabledForPlatformAuth() {
        let sessionStorage;
        try {
            sessionStorage = window[BrowserCacheLocation.SessionStorage];
            // Mute errors if it's a non-browser environment or cookies are blocked.
            return sessionStorage?.getItem(PLATFORM_AUTH_DOM_SUPPORT) === "true";
        }
        catch (e) {
            return false;
        }
    }
    /**
     * Returns boolean indicating whether or not the request should attempt to use platform broker
     * @param logger
     * @param config
     * @param correlationId
     * @param platformAuthProvider
     * @param authenticationScheme
     */
    function isPlatformAuthAllowed(config, logger, correlationId, platformAuthProvider, authenticationScheme) {
        logger.trace("0uko3r", correlationId);
        if (!config.system.allowPlatformBroker) {
            logger.trace("04hozs", correlationId);
            // Developer disabled WAM
            return false;
        }
        if (!platformAuthProvider) {
            logger.trace("0kvv1r", correlationId);
            // Platform broker auth providers are not available
            return false;
        }
        if (authenticationScheme) {
            switch (authenticationScheme) {
                case AuthenticationScheme$1.BEARER:
                case AuthenticationScheme$1.POP:
                    logger.trace("18tev1", correlationId);
                    return true;
                default:
                    logger.trace("1dd2nh", correlationId);
                    return false;
            }
        }
        return true;
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class PopupClient extends StandardInteractionClient {
        constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, nativeStorageImpl, correlationId, platformAuthHandler) {
            super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthHandler);
            this.nativeStorage = nativeStorageImpl;
            this.eventHandler = eventHandler;
        }
        /**
         * Acquires tokens by opening a popup window to the /authorize endpoint of the authority
         * @param request
         * @param pkceCodes
         */
        acquireToken(request, pkceCodes) {
            let popupParams = undefined;
            try {
                const popupName = this.generatePopupName(request.scopes || OIDC_DEFAULT_SCOPES$1, request.authority || this.config.auth.authority);
                popupParams = {
                    popupName,
                    popupWindowAttributes: request.popupWindowAttributes || {},
                    popupWindowParent: request.popupWindowParent ?? window,
                };
                this.performanceClient.addFields({ isAsyncPopup: !this.config.system.navigatePopups }, this.correlationId);
                // navigatePopups flag is false. Acquires token without first opening popup. Popup will be opened later asynchronously.
                if (!this.config.system.navigatePopups) {
                    this.logger.verbose("162h4u", this.correlationId);
                    // Passes on popup position and dimensions if in request
                    return this.acquireTokenPopupAsync(request, popupParams, pkceCodes);
                }
                else {
                    // navigatePopups flag is set to true. Opens popup before acquiring token.
                    // Pre-validate request method to avoid opening popup if the request is invalid
                    const validatedRequest = {
                        ...request,
                        httpMethod: validateRequestMethod(request, this.config.system.protocolMode),
                    };
                    this.logger.verbose("1f9ok3", this.correlationId);
                    popupParams.popup = this.openSizedPopup("about:blank", popupParams);
                    return this.acquireTokenPopupAsync(validatedRequest, popupParams, pkceCodes);
                }
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
        /**
         * Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
         * @param logoutRequest
         */
        logout(logoutRequest) {
            try {
                this.logger.verbose("068rup", this.correlationId);
                const validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
                const popupParams = {
                    popupName: this.generateLogoutPopupName(validLogoutRequest),
                    popupWindowAttributes: logoutRequest?.popupWindowAttributes || {},
                    popupWindowParent: logoutRequest?.popupWindowParent ?? window,
                };
                const authority = logoutRequest && logoutRequest.authority;
                const mainWindowRedirectUri = logoutRequest && logoutRequest.mainWindowRedirectUri;
                // navigatePopups flag set to false. Acquires token without first opening popup. Popup will be opened later asynchronously.
                if (!this.config.system.navigatePopups) {
                    this.logger.verbose("1phd8u", this.correlationId);
                    // Passes on popup position and dimensions if in request
                    return this.logoutPopupAsync(validLogoutRequest, popupParams, authority, mainWindowRedirectUri);
                }
                else {
                    // navigatePopups flag is set to true. Opens popup before logging out.
                    this.logger.verbose("1a28da", this.correlationId);
                    popupParams.popup = this.openSizedPopup("about:blank", popupParams);
                    return this.logoutPopupAsync(validLogoutRequest, popupParams, authority, mainWindowRedirectUri);
                }
            }
            catch (e) {
                // Since this function is synchronous we need to reject
                return Promise.reject(e);
            }
        }
        /**
         * Helper which obtains an access_token for your API via opening a popup window in the user's browser
         * @param request
         * @param popupParams
         * @param pkceCodes
         *
         * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
         */
        async acquireTokenPopupAsync(request, popupParams, pkceCodes) {
            this.logger.verbose("1g77pg", this.correlationId);
            const validRequest = await invokeAsync(initializeAuthorizationRequest, StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(request, exports.InteractionType.Popup, this.config, this.browserCrypto, this.browserStorage, this.logger, this.performanceClient, this.correlationId);
            /*
             * Skip pre-connect for async popups to reduce time between user interaction and popup window creation to avoid
             * popup from being blocked by browsers with shorter popup timers
             */
            if (popupParams.popup) {
                preconnect(validRequest.authority);
            }
            const isPlatformBroker = isPlatformAuthAllowed(this.config, this.logger, this.correlationId, this.platformAuthProvider, request.authenticationScheme);
            validRequest.platformBroker = isPlatformBroker;
            if (this.config.system.protocolMode === ProtocolMode.EAR) {
                return this.executeEarFlow(validRequest, popupParams, pkceCodes);
            }
            else {
                return this.executeCodeFlow(validRequest, popupParams, pkceCodes);
            }
        }
        /**
         * Executes auth code + PKCE flow
         * @param request
         * @param popupParams
         * @param pkceCodes
         * @returns
         */
        async executeCodeFlow(request, popupParams, pkceCodes) {
            const correlationId = request.correlationId;
            const serverTelemetryManager = initializeServerTelemetryManager(ApiId.acquireTokenPopup, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
            const pkce = pkceCodes ||
                (await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId));
            const popupRequest = {
                ...request,
                codeChallenge: pkce.challenge,
            };
            try {
                // Initialize the client
                const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, correlationId)({
                    serverTelemetryManager,
                    requestAuthority: popupRequest.authority,
                    requestAzureCloudOptions: popupRequest.azureCloudOptions,
                    requestExtraQueryParameters: popupRequest.extraQueryParameters,
                    account: popupRequest.account,
                });
                if (popupRequest.httpMethod === HttpMethod.POST) {
                    return await this.executeCodeFlowWithPost(popupRequest, popupParams, authClient, pkce.verifier);
                }
                else {
                    // Create acquire token url.
                    const navigateUrl = await invokeAsync(getAuthCodeRequestUrl, GetAuthCodeUrl, this.logger, this.performanceClient, correlationId)(this.config, authClient.authority, popupRequest, this.logger, this.performanceClient);
                    // Show the UI once the url has been created. Get the window handle for the popup.
                    const popupWindow = this.initiateAuthRequest(navigateUrl, popupParams);
                    this.eventHandler.emitEvent(EventType.POPUP_OPENED, correlationId, exports.InteractionType.Popup, { popupWindow }, null);
                    // Wait for the redirect bridge response
                    const responseString = await waitForBridgeResponse(this.config.system.popupBridgeTimeout, this.logger, this.browserCrypto, request, this.performanceClient);
                    const serverParams = invoke(deserializeResponse, DeserializeResponse, this.logger, this.performanceClient, this.correlationId)(responseString, this.config.auth.OIDCOptions.responseMode, this.logger, this.correlationId);
                    return await invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, correlationId)(request, serverParams, pkce.verifier, ApiId.acquireTokenPopup, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
                }
            }
            catch (e) {
                // Close the synchronous popup if an error is thrown before the window unload event is registered
                popupParams.popup?.close();
                if (e instanceof AuthError) {
                    e.setCorrelationId(this.correlationId);
                    serverTelemetryManager.cacheFailedRequest(e);
                }
                throw e;
            }
        }
        /**
         * Executes EAR flow
         * @param request
         */
        async executeEarFlow(request, popupParams, pkceCodes) {
            const { correlationId, authority, azureCloudOptions, extraQueryParameters, account, } = request;
            // Get the frame handle for the silent request
            const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, authority, azureCloudOptions, extraQueryParameters, account);
            const earJwk = await invokeAsync(generateEarKey, GenerateEarKey, this.logger, this.performanceClient, correlationId)();
            const pkce = pkceCodes ||
                (await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId));
            const popupRequest = {
                ...request,
                earJwk: earJwk,
                codeChallenge: pkce.challenge,
            };
            const popupWindow = popupParams.popup || this.openPopup("about:blank", popupParams);
            const form = await getEARForm(popupWindow.document, this.config, discoveredAuthority, popupRequest, this.logger, this.performanceClient);
            form.submit();
            // Monitor the popup for the hash. Return the string value and close the popup when the hash is received. Default timeout is 60 seconds.
            const responseString = await invokeAsync(waitForBridgeResponse, SilentHandlerMonitorIframeForHash, this.logger, this.performanceClient, correlationId)(this.config.system.popupBridgeTimeout, this.logger, this.browserCrypto, popupRequest, this.performanceClient);
            const serverParams = invoke(deserializeResponse, DeserializeResponse, this.logger, this.performanceClient, this.correlationId)(responseString, this.config.auth.OIDCOptions.responseMode, this.logger, this.correlationId);
            if (!serverParams.ear_jwe && serverParams.code) {
                const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, correlationId)({
                    serverTelemetryManager: initializeServerTelemetryManager(ApiId.acquireTokenPopup, this.config.auth.clientId, correlationId, this.browserStorage, this.logger),
                    requestAuthority: request.authority,
                    requestAzureCloudOptions: request.azureCloudOptions,
                    requestExtraQueryParameters: request.extraQueryParameters,
                    account: request.account,
                    authority: discoveredAuthority,
                });
                return invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, correlationId)(popupRequest, serverParams, pkce.verifier, ApiId.acquireTokenPopup, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
            }
            else {
                return invokeAsync(handleResponseEAR, HandleResponseEar, this.logger, this.performanceClient, correlationId)(popupRequest, serverParams, ApiId.acquireTokenPopup, this.config, discoveredAuthority, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
            }
        }
        async executeCodeFlowWithPost(request, popupParams, authClient, pkceVerifier) {
            const correlationId = request.correlationId;
            // Get the frame handle for the silent request
            const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger);
            const popupWindow = popupParams.popup || this.openPopup("about:blank", popupParams);
            const form = await getCodeForm(popupWindow.document, this.config, discoveredAuthority, request, this.logger, this.performanceClient);
            form.submit();
            // Monitor the popup for the hash. Return the string value and close the popup when the hash is received. Default timeout is 60 seconds.
            const responseString = await invokeAsync(waitForBridgeResponse, SilentHandlerMonitorIframeForHash, this.logger, this.performanceClient, correlationId)(this.config.system.popupBridgeTimeout, this.logger, this.browserCrypto, request, this.performanceClient);
            const serverParams = invoke(deserializeResponse, DeserializeResponse, this.logger, this.performanceClient, this.correlationId)(responseString, this.config.auth.OIDCOptions.responseMode, this.logger, this.correlationId);
            return invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, correlationId)(request, serverParams, pkceVerifier, ApiId.acquireTokenPopup, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
        }
        /**
         *
         * @param validRequest
         * @param popupName
         * @param requestAuthority
         * @param popup
         * @param mainWindowRedirectUri
         * @param popupWindowAttributes
         */
        async logoutPopupAsync(validRequest, popupParams, requestAuthority, mainWindowRedirectUri) {
            this.logger.verbose("0b7yrk", this.correlationId);
            this.eventHandler.emitEvent(EventType.LOGOUT_START, this.correlationId, exports.InteractionType.Popup, validRequest);
            const serverTelemetryManager = initializeServerTelemetryManager(ApiId.logoutPopup, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
            try {
                // Clear cache on logout
                await clearCacheOnLogout(this.browserStorage, this.browserCrypto, this.logger, this.correlationId, validRequest.account);
                // Initialize the client
                const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)({
                    serverTelemetryManager,
                    requestAuthority: requestAuthority,
                    account: validRequest.account || undefined,
                });
                try {
                    authClient.authority.endSessionEndpoint;
                }
                catch {
                    if (validRequest.account?.homeAccountId &&
                        validRequest.postLogoutRedirectUri &&
                        authClient.authority.protocolMode === ProtocolMode.OIDC) {
                        this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, validRequest.correlationId, exports.InteractionType.Popup, validRequest);
                        if (mainWindowRedirectUri) {
                            const navigationOptions = {
                                apiId: ApiId.logoutPopup,
                                timeout: this.config.system.redirectNavigationTimeout,
                                noHistory: false,
                            };
                            const absoluteUrl = UrlString.getAbsoluteUrl(mainWindowRedirectUri, getCurrentUri());
                            await this.navigationClient.navigateInternal(absoluteUrl, navigationOptions);
                        }
                        popupParams.popup?.close();
                        return;
                    }
                }
                // Redirect bridge requires "state" param to work properly
                validRequest.state = setRequestState(this.browserCrypto, validRequest.state || "", {
                    interactionType: exports.InteractionType.Popup,
                });
                // Create logout string and navigate user window to logout.
                const logoutUri = authClient.getLogoutUri(validRequest);
                this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, validRequest.correlationId, exports.InteractionType.Popup, validRequest);
                // Open the popup window to requestUrl.
                const popupWindow = this.openPopup(logoutUri, popupParams);
                this.eventHandler.emitEvent(EventType.POPUP_OPENED, validRequest.correlationId, exports.InteractionType.Popup, { popupWindow }, null);
                await waitForBridgeResponse(this.config.system.popupBridgeTimeout, this.logger, this.browserCrypto, validRequest, this.performanceClient).catch(() => {
                    // Swallow any errors related to monitoring the window. Server logout is best effort
                });
                if (mainWindowRedirectUri) {
                    const navigationOptions = {
                        apiId: ApiId.logoutPopup,
                        timeout: this.config.system.redirectNavigationTimeout,
                        noHistory: false,
                    };
                    const absoluteUrl = UrlString.getAbsoluteUrl(mainWindowRedirectUri, getCurrentUri());
                    this.logger.verbose("0qcur2", this.correlationId);
                    this.logger.verbosePii("0oj7lk", this.correlationId);
                    await this.navigationClient.navigateInternal(absoluteUrl, navigationOptions);
                }
                else {
                    this.logger.verbose("03zgcf", this.correlationId);
                }
            }
            catch (e) {
                // Close the synchronous popup if an error is thrown before the window unload event is registered
                popupParams.popup?.close();
                if (e instanceof AuthError) {
                    e.setCorrelationId(this.correlationId);
                    serverTelemetryManager.cacheFailedRequest(e);
                }
                this.eventHandler.emitEvent(EventType.LOGOUT_FAILURE, this.correlationId, exports.InteractionType.Popup, null, e);
                this.eventHandler.emitEvent(EventType.LOGOUT_END, this.correlationId, exports.InteractionType.Popup);
                throw e;
            }
            this.eventHandler.emitEvent(EventType.LOGOUT_END, this.correlationId, exports.InteractionType.Popup);
        }
        /**
         * Opens a popup window with given request Url.
         * @param requestUrl
         */
        initiateAuthRequest(requestUrl, params) {
            // Check that request url is not empty.
            if (requestUrl) {
                this.logger.infoPii("1kcr9k", this.correlationId);
                // Open the popup window to requestUrl.
                return this.openPopup(requestUrl, params);
            }
            else {
                // Throw error if request URL is empty.
                this.logger.error("1l7hyp", this.correlationId);
                throw createBrowserAuthError(emptyNavigateUri);
            }
        }
        /**
         * @hidden
         *
         * Configures popup window for login.
         *
         * @param urlNavigate
         * @param title
         * @param popUpWidth
         * @param popUpHeight
         * @param popupWindowAttributes
         * @ignore
         * @hidden
         */
        openPopup(urlNavigate, popupParams) {
            try {
                let popupWindow;
                // Popup window passed in, setting url to navigate to
                if (popupParams.popup) {
                    popupWindow = popupParams.popup;
                    this.logger.verbosePii("0cgeo7", this.correlationId);
                    popupWindow.location.assign(urlNavigate);
                }
                else if (typeof popupParams.popup === "undefined") {
                    // Popup will be undefined if it was not passed in
                    this.logger.verbosePii("0c2awd", this.correlationId);
                    popupWindow = this.openSizedPopup(urlNavigate, popupParams);
                }
                // Popup will be null if popups are blocked
                if (!popupWindow) {
                    throw createBrowserAuthError(emptyWindowError);
                }
                if (popupWindow.focus) {
                    popupWindow.focus();
                }
                this.currentWindow = popupWindow;
                return popupWindow;
            }
            catch (e) {
                this.logger.error("0dxfb9", this.correlationId);
                throw createBrowserAuthError(popupWindowError);
            }
        }
        /**
         * Helper function to set popup window dimensions and position
         * @param urlNavigate
         * @param popupName
         * @param popupWindowAttributes
         * @returns
         */
        openSizedPopup(urlNavigate, { popupName, popupWindowAttributes, popupWindowParent }) {
            /**
             * adding winLeft and winTop to account for dual monitor
             * using screenLeft and screenTop for IE8 and earlier
             */
            const winLeft = popupWindowParent.screenLeft
                ? popupWindowParent.screenLeft
                : popupWindowParent.screenX;
            const winTop = popupWindowParent.screenTop
                ? popupWindowParent.screenTop
                : popupWindowParent.screenY;
            /**
             * window.innerWidth displays browser window"s height and width excluding toolbars
             * using document.documentElement.clientWidth for IE8 and earlier
             */
            const winWidth = popupWindowParent.innerWidth ||
                document.documentElement.clientWidth ||
                document.body.clientWidth;
            const winHeight = popupWindowParent.innerHeight ||
                document.documentElement.clientHeight ||
                document.body.clientHeight;
            let width = popupWindowAttributes.popupSize?.width;
            let height = popupWindowAttributes.popupSize?.height;
            let top = popupWindowAttributes.popupPosition?.top;
            let left = popupWindowAttributes.popupPosition?.left;
            if (!width || width < 0 || width > winWidth) {
                this.logger.verbose("08vfmo", this.correlationId);
                width = BrowserConstants.POPUP_WIDTH;
            }
            if (!height || height < 0 || height > winHeight) {
                this.logger.verbose("09cxa0", this.correlationId);
                height = BrowserConstants.POPUP_HEIGHT;
            }
            if (!top || top < 0 || top > winHeight) {
                this.logger.verbose("1qh4wo", this.correlationId);
                top = Math.max(0, winHeight / 2 - BrowserConstants.POPUP_HEIGHT / 2 + winTop);
            }
            if (!left || left < 0 || left > winWidth) {
                this.logger.verbose("1sz3en", this.correlationId);
                left = Math.max(0, winWidth / 2 - BrowserConstants.POPUP_WIDTH / 2 + winLeft);
            }
            return popupWindowParent.open(urlNavigate, popupName, `width=${width}, height=${height}, top=${top}, left=${left}, scrollbars=yes`);
        }
        /**
         * Generates the name for the popup based on the client id and request
         * @param clientId
         * @param request
         */
        generatePopupName(scopes, authority) {
            return `${BrowserConstants.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${scopes.join("-")}.${authority}.${this.correlationId}`;
        }
        /**
         * Generates the name for the popup based on the client id and request for logouts
         * @param clientId
         * @param request
         */
        generateLogoutPopupName(request) {
            const homeAccountId = request.account && request.account.homeAccountId;
            return `${BrowserConstants.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${homeAccountId}.${this.correlationId}`;
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function getNavigationType() {
        if (typeof window === "undefined" ||
            typeof window.performance === "undefined" ||
            typeof window.performance.getEntriesByType !== "function") {
            return undefined;
        }
        const navigationEntries = window.performance.getEntriesByType("navigation");
        const navigation = navigationEntries.length
            ? navigationEntries[0]
            : undefined;
        return navigation?.type;
    }
    class RedirectClient extends StandardInteractionClient {
        constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, nativeStorageImpl, correlationId, platformAuthHandler) {
            super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthHandler);
            this.nativeStorage = nativeStorageImpl;
        }
        /**
         * Redirects the page to the /authorize endpoint of the IDP
         * @param request
         */
        async acquireToken(request) {
            const validRequest = await invokeAsync(initializeAuthorizationRequest, StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(request, exports.InteractionType.Redirect, this.config, this.browserCrypto, this.browserStorage, this.logger, this.performanceClient, this.correlationId);
            validRequest.platformBroker = isPlatformAuthAllowed(this.config, this.logger, this.correlationId, this.platformAuthProvider, request.authenticationScheme);
            const handleBackButton = (event) => {
                // Clear temporary cache if the back button is clicked during the redirect flow.
                if (event.persisted) {
                    this.logger.verbose("0udvtt", this.correlationId);
                    this.browserStorage.resetRequestCache(this.correlationId);
                    this.eventHandler.emitEvent(EventType.RESTORE_FROM_BFCACHE, this.correlationId, exports.InteractionType.Redirect);
                }
            };
            const redirectStartPage = this.getRedirectStartPage(request.redirectStartPage);
            this.logger.verbosePii("0zao0a", this.correlationId);
            // Cache start page, returns to this page after redirectUri if navigateToLoginRequestUrl is true
            this.browserStorage.setTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, redirectStartPage, true);
            // Clear temporary cache if the back button is clicked during the redirect flow.
            window.addEventListener("pageshow", handleBackButton);
            try {
                if (this.config.system.protocolMode === ProtocolMode.EAR) {
                    await this.executeEarFlow(validRequest);
                }
                else {
                    await this.executeCodeFlow(validRequest);
                }
            }
            catch (e) {
                if (e instanceof AuthError) {
                    e.setCorrelationId(this.correlationId);
                }
                window.removeEventListener("pageshow", handleBackButton);
                throw e;
            }
        }
        /**
         * Executes auth code + PKCE flow
         * @param request
         * @returns
         */
        async executeCodeFlow(request) {
            const correlationId = request.correlationId;
            const serverTelemetryManager = initializeServerTelemetryManager(ApiId.acquireTokenRedirect, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
            const pkceCodes = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
            const redirectRequest = {
                ...request,
                codeChallenge: pkceCodes.challenge,
            };
            this.browserStorage.cacheAuthorizeRequest(redirectRequest, this.correlationId, pkceCodes.verifier);
            try {
                if (redirectRequest.httpMethod === HttpMethod.POST) {
                    return await this.executeCodeFlowWithPost(redirectRequest);
                }
                else {
                    // Initialize the client
                    const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)({
                        serverTelemetryManager,
                        requestAuthority: redirectRequest.authority,
                        requestAzureCloudOptions: redirectRequest.azureCloudOptions,
                        requestExtraQueryParameters: redirectRequest.extraQueryParameters,
                        account: redirectRequest.account,
                    });
                    // Create acquire token url.
                    const navigateUrl = await invokeAsync(getAuthCodeRequestUrl, GetAuthCodeUrl, this.logger, this.performanceClient, request.correlationId)(this.config, authClient.authority, redirectRequest, this.logger, this.performanceClient);
                    // Show the UI once the url has been created. Response will come back in the hash, which will be handled in the handleRedirectCallback function.
                    return await this.initiateAuthRequest(navigateUrl);
                }
            }
            catch (e) {
                if (e instanceof AuthError) {
                    e.setCorrelationId(this.correlationId);
                    serverTelemetryManager.cacheFailedRequest(e);
                }
                throw e;
            }
        }
        /**
         * Executes EAR flow
         * @param request
         */
        async executeEarFlow(request) {
            const { correlationId, authority, azureCloudOptions, extraQueryParameters, account, } = request;
            // Get the frame handle for the silent request
            const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, authority, azureCloudOptions, extraQueryParameters, account);
            const earJwk = await invokeAsync(generateEarKey, GenerateEarKey, this.logger, this.performanceClient, correlationId)();
            const pkceCodes = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
            const redirectRequest = {
                ...request,
                earJwk: earJwk,
                codeChallenge: pkceCodes.challenge,
            };
            this.browserStorage.cacheAuthorizeRequest(redirectRequest, this.correlationId, pkceCodes.verifier);
            const form = await getEARForm(document, this.config, discoveredAuthority, redirectRequest, this.logger, this.performanceClient);
            form.submit();
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    reject(createBrowserAuthError(timedOut, "failed_to_redirect"));
                }, this.config.system.redirectNavigationTimeout);
            });
        }
        /**
         * Executes classic Authorization Code flow with a POST request.
         * @param request
         */
        async executeCodeFlowWithPost(request) {
            const correlationId = request.correlationId;
            // Get the frame handle for the silent request
            const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger);
            this.browserStorage.cacheAuthorizeRequest(request, this.correlationId);
            const form = await getCodeForm(document, this.config, discoveredAuthority, request, this.logger, this.performanceClient);
            form.submit();
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    reject(createBrowserAuthError(timedOut, "failed_to_redirect"));
                }, this.config.system.redirectNavigationTimeout);
            });
        }
        /**
         * Checks if navigateToLoginRequestUrl is set, and:
         * - if true, performs logic to cache and navigate
         * - if false, handles hash string and parses response
         * @param hash {string} url hash
         * @param parentMeasurement {InProgressPerformanceEvent} parent measurement
         * @param request {CommonAuthorizationUrlRequest} request object
         * @param pkceVerifier {string} PKCE verifier
         * @param options {HandleRedirectPromiseOptions} options for handling redirect promise
         */
        async handleRedirectPromise(request, pkceVerifier, parentMeasurement, options) {
            const serverTelemetryManager = initializeServerTelemetryManager(ApiId.handleRedirectPromise, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
            const navigateToLoginRequestUrl = options?.navigateToLoginRequestUrl ?? true;
            try {
                const [serverParams, responseString] = this.getRedirectResponse(options?.hash || "");
                if (!serverParams) {
                    // Not a recognized server response hash or hash not associated with a redirect request
                    this.logger.info("1qmv0q", this.correlationId);
                    this.browserStorage.resetRequestCache(this.correlationId);
                    // Do not instrument "no_server_response" if user clicked back button
                    if (getNavigationType() !== "back_forward") {
                        parentMeasurement.event.errorCode = "no_server_response";
                    }
                    else {
                        this.logger.verbose("1eqegq", this.correlationId);
                    }
                    return null;
                }
                // If navigateToLoginRequestUrl is true, get the url where the redirect request was initiated
                const loginRequestUrl = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, this.correlationId, true) || "";
                const loginRequestUrlNormalized = normalizeUrlForComparison(loginRequestUrl);
                const currentUrlNormalized = normalizeUrlForComparison(window.location.href);
                if (loginRequestUrlNormalized === currentUrlNormalized &&
                    navigateToLoginRequestUrl) {
                    // We are on the page we need to navigate to - handle hash
                    this.logger.verbose("11yred", this.correlationId);
                    if (loginRequestUrl.indexOf("#") > -1) {
                        // Replace current hash with non-msal hash, if present
                        replaceHash(loginRequestUrl);
                    }
                    const handleHashResult = await this.handleResponse(serverParams, request, pkceVerifier, serverTelemetryManager);
                    return handleHashResult;
                }
                else if (!navigateToLoginRequestUrl) {
                    this.logger.verbose("0v4sdv", this.correlationId);
                    return await this.handleResponse(serverParams, request, pkceVerifier, serverTelemetryManager);
                }
                else if (!isInIframe() ||
                    this.config.system.allowRedirectInIframe) {
                    /*
                     * Returned from authority using redirect - need to perform navigation before processing response
                     * Cache the hash to be retrieved after the next redirect
                     */
                    this.browserStorage.setTemporaryCache(TemporaryCacheKeys.URL_HASH, responseString, true);
                    const navigationOptions = {
                        apiId: ApiId.handleRedirectPromise,
                        timeout: this.config.system.redirectNavigationTimeout,
                        noHistory: true,
                    };
                    /**
                     * Default behavior is to redirect to the start page and not process the hash now.
                     * The start page is expected to also call handleRedirectPromise which will process the hash in one of the checks above.
                     */
                    let processHashOnRedirect = true;
                    if (!loginRequestUrl || loginRequestUrl === "null") {
                        // Redirect to home page if login request url is null (real null or the string null)
                        const homepage = getHomepage();
                        // Cache the homepage under ORIGIN_URI to ensure cached hash is processed on homepage
                        this.browserStorage.setTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, homepage, true);
                        this.logger.warning("1dutq1", this.correlationId);
                        processHashOnRedirect =
                            await this.navigationClient.navigateInternal(homepage, navigationOptions);
                    }
                    else {
                        // Navigate to page that initiated the redirect request
                        this.logger.verbose("08jpy1", this.correlationId);
                        processHashOnRedirect =
                            await this.navigationClient.navigateInternal(loginRequestUrl, navigationOptions);
                    }
                    // If navigateInternal implementation returns false, handle the hash now
                    if (!processHashOnRedirect) {
                        return await this.handleResponse(serverParams, request, pkceVerifier, serverTelemetryManager);
                    }
                }
                return null;
            }
            catch (e) {
                if (e instanceof AuthError) {
                    e.setCorrelationId(this.correlationId);
                    serverTelemetryManager.cacheFailedRequest(e);
                }
                throw e;
            }
        }
        /**
         * Gets the response hash for a redirect request
         * Returns null if interactionType in the state value is not "redirect" or the hash does not contain known properties
         * @param hash
         */
        getRedirectResponse(userProvidedResponse) {
            this.logger.verbose("1c5i8m", this.correlationId);
            // Get current location hash from window or cache.
            let responseString = userProvidedResponse;
            if (!responseString) {
                if (this.config.auth.OIDCOptions.responseMode ===
                    ResponseMode$1.QUERY) {
                    responseString = window.location.search;
                }
                else {
                    responseString = window.location.hash;
                }
            }
            let response = getDeserializedResponse(responseString);
            if (response) {
                try {
                    validateInteractionType(response, this.browserCrypto, exports.InteractionType.Redirect);
                }
                catch (e) {
                    if (e instanceof AuthError) {
                        this.logger.error("0bkq6p", this.correlationId);
                    }
                    return [null, ""];
                }
                clearHash(window);
                this.logger.verbose("00uvho", this.correlationId);
                return [response, responseString];
            }
            const cachedHash = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.URL_HASH, this.correlationId, true);
            this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.URL_HASH));
            if (cachedHash) {
                response = getDeserializedResponse(cachedHash);
                if (response) {
                    this.logger.verbose("001671", this.correlationId);
                    return [response, cachedHash];
                }
            }
            return [null, ""];
        }
        /**
         * Checks if hash exists and handles in window.
         * @param hash
         * @param state
         */
        async handleResponse(serverParams, request, codeVerifier, serverTelemetryManager) {
            const state = serverParams.state;
            if (!state) {
                throw createBrowserAuthError(noStateInHash);
            }
            const { authority, azureCloudOptions, extraQueryParameters, account } = request;
            if (serverParams.ear_jwe) {
                const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, request.correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, authority, azureCloudOptions, extraQueryParameters, account);
                return invokeAsync(handleResponseEAR, HandleResponseEar, this.logger, this.performanceClient, request.correlationId)(request, serverParams, ApiId.acquireTokenRedirect, this.config, discoveredAuthority, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
            }
            const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)({ serverTelemetryManager, requestAuthority: request.authority });
            return invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, request.correlationId)(request, serverParams, codeVerifier, ApiId.acquireTokenRedirect, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
        }
        /**
         * Redirects window to given URL.
         * @param urlNavigate
         * @param onRedirectNavigateRequest - onRedirectNavigate callback provided on the request
         */
        async initiateAuthRequest(requestUrl) {
            this.logger.verbose("0yaw2e", this.correlationId);
            // Navigate if valid URL
            if (requestUrl) {
                this.logger.infoPii("1luf83", this.correlationId);
                const navigationOptions = {
                    apiId: ApiId.acquireTokenRedirect,
                    timeout: this.config.system.redirectNavigationTimeout,
                    noHistory: false,
                };
                const onRedirectNavigate = this.config.auth.onRedirectNavigate;
                // If onRedirectNavigate is implemented, invoke it and provide requestUrl
                if (typeof onRedirectNavigate === "function") {
                    this.logger.verbose("1nehvl", this.correlationId);
                    const navigate = onRedirectNavigate(requestUrl);
                    // Returning false from onRedirectNavigate will stop navigation
                    if (navigate !== false) {
                        this.logger.verbose("1a0jxh", this.correlationId);
                        await this.navigationClient.navigateExternal(requestUrl, navigationOptions);
                        return;
                    }
                    else {
                        this.logger.verbose("09k5h5", this.correlationId);
                        return;
                    }
                }
                else {
                    // Navigate window to request URL
                    this.logger.verbose("0klwf7", this.correlationId);
                    await this.navigationClient.navigateExternal(requestUrl, navigationOptions);
                    return;
                }
            }
            else {
                // Throw error if request URL is empty.
                this.logger.info("0rlh4e", this.correlationId);
                throw createBrowserAuthError(emptyNavigateUri);
            }
        }
        /**
         * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
         * Default behaviour is to redirect the user to `window.location.href`.
         * @param logoutRequest
         */
        async logout(logoutRequest) {
            this.logger.verbose("1rkurh", this.correlationId);
            const validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
            const serverTelemetryManager = initializeServerTelemetryManager(ApiId.logout, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
            try {
                this.eventHandler.emitEvent(EventType.LOGOUT_START, this.correlationId, exports.InteractionType.Redirect, logoutRequest);
                // Clear cache on logout
                await clearCacheOnLogout(this.browserStorage, this.browserCrypto, this.logger, this.correlationId, validLogoutRequest.account);
                const navigationOptions = {
                    apiId: ApiId.logout,
                    timeout: this.config.system.redirectNavigationTimeout,
                    noHistory: false,
                };
                const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)({
                    serverTelemetryManager,
                    requestAuthority: logoutRequest && logoutRequest.authority,
                    requestExtraQueryParameters: logoutRequest?.extraQueryParameters,
                    account: (logoutRequest && logoutRequest.account) || undefined,
                });
                if (authClient.authority.protocolMode === ProtocolMode.OIDC) {
                    try {
                        authClient.authority.endSessionEndpoint;
                    }
                    catch {
                        if (validLogoutRequest.account?.homeAccountId) {
                            this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, this.correlationId, exports.InteractionType.Redirect, validLogoutRequest);
                            return;
                        }
                    }
                }
                // Redirect bridge requires "state" param to work properly
                validLogoutRequest.state = setRequestState(this.browserCrypto, validLogoutRequest.state || "", {
                    interactionType: exports.InteractionType.Redirect,
                });
                // Create logout string and navigate user window to logout.
                const logoutUri = authClient.getLogoutUri(validLogoutRequest);
                if (validLogoutRequest.account?.homeAccountId) {
                    this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, this.correlationId, exports.InteractionType.Redirect, validLogoutRequest);
                }
                // Check if onRedirectNavigate is implemented, and invoke it if so
                const onRedirectNavigate = this.config.auth.onRedirectNavigate;
                if (typeof onRedirectNavigate === "function") {
                    const navigate = onRedirectNavigate(logoutUri);
                    if (navigate !== false) {
                        this.logger.verbose("06v57e", this.correlationId);
                        // Ensure interaction is in progress
                        if (!this.browserStorage.getInteractionInProgress()) {
                            this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
                        }
                        await this.navigationClient.navigateExternal(logoutUri, navigationOptions);
                        return;
                    }
                    else {
                        // Ensure interaction is not in progress
                        this.browserStorage.setInteractionInProgress(false);
                        this.logger.verbose("0xqes1", this.correlationId);
                    }
                }
                else {
                    // Ensure interaction is in progress
                    if (!this.browserStorage.getInteractionInProgress()) {
                        this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
                    }
                    await this.navigationClient.navigateExternal(logoutUri, navigationOptions);
                    return;
                }
            }
            catch (e) {
                if (e instanceof AuthError) {
                    e.setCorrelationId(this.correlationId);
                    serverTelemetryManager.cacheFailedRequest(e);
                }
                this.eventHandler.emitEvent(EventType.LOGOUT_FAILURE, this.correlationId, exports.InteractionType.Redirect, null, e);
                this.eventHandler.emitEvent(EventType.LOGOUT_END, this.correlationId, exports.InteractionType.Redirect);
                throw e;
            }
            this.eventHandler.emitEvent(EventType.LOGOUT_END, this.correlationId, exports.InteractionType.Redirect);
        }
        /**
         * Use to get the redirectStartPage either from request or use current window
         * @param requestStartPage
         */
        getRedirectStartPage(requestStartPage) {
            const redirectStartPage = requestStartPage || window.location.href;
            return UrlString.getAbsoluteUrl(redirectStartPage, getCurrentUri());
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Creates a hidden iframe to given URL using user-requested scopes as an id.
     * @param urlNavigate
     * @param userRequestScopes
     */
    async function initiateCodeRequest(requestUrl, performanceClient, logger, correlationId) {
        if (!requestUrl) {
            // Throw error if request URL is empty.
            logger.info("1l7hyp", correlationId);
            throw createBrowserAuthError(emptyNavigateUri);
        }
        return invoke(loadFrameSync, SilentHandlerLoadFrameSync, logger, performanceClient, correlationId)(requestUrl);
    }
    async function initiateCodeFlowWithPost(config, authority, request, logger, performanceClient) {
        const frame = createHiddenIframe();
        if (!frame.contentDocument) {
            throw "No document associated with iframe!";
        }
        const form = await getCodeForm(frame.contentDocument, config, authority, request, logger, performanceClient);
        form.submit();
        return frame;
    }
    async function initiateEarRequest(config, authority, request, logger, performanceClient) {
        const frame = createHiddenIframe();
        if (!frame.contentDocument) {
            throw "No document associated with iframe!";
        }
        const form = await getEARForm(frame.contentDocument, config, authority, request, logger, performanceClient);
        form.submit();
        return frame;
    }
    /**
     * @hidden
     * Loads the iframe synchronously when the navigateTimeFrame is set to `0`
     * @param urlNavigate
     * @param frameName
     * @param logger
     */
    function loadFrameSync(urlNavigate) {
        const frameHandle = createHiddenIframe();
        frameHandle.src = urlNavigate;
        return frameHandle;
    }
    /**
     * @hidden
     * Creates a new hidden iframe or gets an existing one for silent token renewal.
     * @ignore
     */
    function createHiddenIframe() {
        const authFrame = document.createElement("iframe");
        authFrame.className = "msalSilentIframe";
        authFrame.style.visibility = "hidden";
        authFrame.style.position = "absolute";
        authFrame.style.width = authFrame.style.height = "0";
        authFrame.style.border = "0";
        authFrame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms");
        authFrame.setAttribute("allow", "local-network-access *");
        document.body.appendChild(authFrame);
        return authFrame;
    }
    /**
     * @hidden
     * Removes a hidden iframe from `document.body` if it is a direct child.
     * @param iframe - The iframe element to remove.
     */
    function removeHiddenIframe(iframe) {
        if (document.body === iframe.parentNode) {
            document.body.removeChild(iframe);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class SilentIframeClient extends StandardInteractionClient {
        constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, nativeStorageImpl, correlationId, platformAuthProvider) {
            super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthProvider);
            this.apiId = apiId;
            this.nativeStorage = nativeStorageImpl;
        }
        /**
         * Acquires a token silently by opening a hidden iframe to the /authorize endpoint with prompt=none or prompt=no_session
         * @param request
         */
        async acquireToken(request) {
            // Check that we have some SSO data
            if (!request.loginHint &&
                !request.sid &&
                (!request.account || !request.account.username)) {
                this.logger.warning("1kl318", this.correlationId);
            }
            // Check the prompt value
            const inputRequest = { ...request };
            if (inputRequest.prompt) {
                if (inputRequest.prompt !== PromptValue$1.NONE &&
                    inputRequest.prompt !== PromptValue$1.NO_SESSION) {
                    this.logger.warning("0bmctg", this.correlationId);
                    inputRequest.prompt = PromptValue$1.NONE;
                }
            }
            else {
                inputRequest.prompt = PromptValue$1.NONE;
            }
            // Create silent request
            const silentRequest = await invokeAsync(initializeAuthorizationRequest, StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(inputRequest, exports.InteractionType.Silent, this.config, this.browserCrypto, this.browserStorage, this.logger, this.performanceClient, this.correlationId);
            silentRequest.platformBroker = isPlatformAuthAllowed(this.config, this.logger, this.correlationId, this.platformAuthProvider, silentRequest.authenticationScheme);
            preconnect(silentRequest.authority);
            if (this.config.system.protocolMode === ProtocolMode.EAR) {
                return this.executeEarFlow(silentRequest);
            }
            else {
                return this.executeCodeFlow(silentRequest);
            }
        }
        /**
         * Executes auth code + PKCE flow
         * @param request
         * @returns
         */
        async executeCodeFlow(request) {
            let authClient;
            const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
            try {
                // Initialize the client
                authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, request.correlationId)({
                    serverTelemetryManager,
                    requestAuthority: request.authority,
                    requestAzureCloudOptions: request.azureCloudOptions,
                    requestExtraQueryParameters: request.extraQueryParameters,
                    account: request.account,
                });
                return await invokeAsync(this.silentTokenHelper.bind(this), SilentIframeClientTokenHelper, this.logger, this.performanceClient, request.correlationId)(authClient, request);
            }
            catch (e) {
                if (e instanceof AuthError) {
                    e.setCorrelationId(this.correlationId);
                    serverTelemetryManager.cacheFailedRequest(e);
                }
                if (!authClient ||
                    !(e instanceof AuthError) ||
                    e.errorCode !== BrowserConstants.INVALID_GRANT_ERROR) {
                    throw e;
                }
                this.performanceClient.addFields({
                    retryError: e.errorCode,
                }, this.correlationId);
                return await invokeAsync(this.silentTokenHelper.bind(this), SilentIframeClientTokenHelper, this.logger, this.performanceClient, this.correlationId)(authClient, request);
            }
        }
        /**
         * Executes EAR flow
         * @param request
         */
        async executeEarFlow(request) {
            const { correlationId, authority, azureCloudOptions, extraQueryParameters, account, } = request;
            const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, authority, azureCloudOptions, extraQueryParameters, account);
            const earJwk = await invokeAsync(generateEarKey, GenerateEarKey, this.logger, this.performanceClient, correlationId)();
            const pkceCodes = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
            const silentRequest = {
                ...request,
                earJwk: earJwk,
                codeChallenge: pkceCodes.challenge,
            };
            const iframe = await invokeAsync(initiateEarRequest, SilentHandlerInitiateAuthRequest, this.logger, this.performanceClient, correlationId)(this.config, discoveredAuthority, silentRequest, this.logger, this.performanceClient);
            const responseType = this.config.auth.OIDCOptions.responseMode;
            let responseString;
            try {
                responseString = await invokeAsync(waitForBridgeResponse, SilentHandlerMonitorIframeForHash, this.logger, this.performanceClient, correlationId)(this.config.system.iframeBridgeTimeout, this.logger, this.browserCrypto, request, this.performanceClient, this.config.experimental);
            }
            finally {
                invoke(removeHiddenIframe, RemoveHiddenIframe, this.logger, this.performanceClient, correlationId)(iframe);
            }
            const serverParams = invoke(deserializeResponse, DeserializeResponse, this.logger, this.performanceClient, correlationId)(responseString, responseType, this.logger, this.correlationId);
            if (!serverParams.ear_jwe && serverParams.code) {
                // If server doesn't support EAR, they may fallback to auth code flow instead
                const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, correlationId)({
                    serverTelemetryManager: initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger),
                    requestAuthority: request.authority,
                    requestAzureCloudOptions: request.azureCloudOptions,
                    requestExtraQueryParameters: request.extraQueryParameters,
                    account: request.account,
                    authority: discoveredAuthority,
                });
                return invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, correlationId)(silentRequest, serverParams, pkceCodes.verifier, this.apiId, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
            }
            else {
                return invokeAsync(handleResponseEAR, HandleResponseEar, this.logger, this.performanceClient, correlationId)(silentRequest, serverParams, this.apiId, this.config, discoveredAuthority, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
            }
        }
        /**
         * Verifies SSO capability by making an iframe request to /authorize without exchanging the code for tokens.
         * This is useful for verifying SSO capability in the background without the overhead of a full token exchange.
         * @param request - The SSO silent request
         * @returns true if SSO verification was successful with a valid authorization code, false otherwise
         */
        async verifySso(request) {
            const inputRequest = { ...request };
            if (!inputRequest.prompt) {
                inputRequest.prompt = PromptValue$1.NONE;
            }
            // Create silent request
            const silentRequest = await invokeAsync(initializeAuthorizationRequest, StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(inputRequest, exports.InteractionType.Silent, this.config, this.browserCrypto, this.browserStorage, this.logger, this.performanceClient, this.correlationId);
            const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)({
                serverTelemetryManager: initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger),
                requestAuthority: silentRequest.authority,
                requestAzureCloudOptions: silentRequest.azureCloudOptions,
                requestExtraQueryParameters: silentRequest.extraQueryParameters,
                account: silentRequest.account,
            });
            const { serverParams } = await this.silentAuthorizeHelper(authClient, silentRequest);
            const correlationId = silentRequest.correlationId;
            // Validate the response - this checks for errors and validates state
            validateAuthorizationResponse(serverParams, silentRequest.state);
            // Verify a valid authorization code is present
            if (!serverParams.code) {
                this.logger.warning("0y34ti", correlationId);
                return false;
            }
            this.logger.verbose("0kkkcj", correlationId);
            return true;
        }
        /**
         * Currently Unsupported
         */
        logout() {
            // Synchronous so we must reject
            return Promise.reject(createBrowserAuthError(silentLogoutUnsupported));
        }
        /**
         * Helper which acquires an authorization code silently using a hidden iframe from given url
         * using the scopes requested as part of the id, and exchanges the code for a set of OAuth tokens.
         * @param navigateUrl
         * @param userRequestScopes
         */
        async silentTokenHelper(authClient, request) {
            const { serverParams, pkceCodes } = await this.silentAuthorizeHelper(authClient, request);
            return invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, request.correlationId)(request, serverParams, pkceCodes.verifier, this.apiId, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
        }
        /**
         * Shared helper that generates PKCE codes, builds the /authorize URL,
         * loads it in a hidden iframe, waits for the redirect-bridge response,
         * and returns the deserialized server parameters along with the PKCE codes
         * and the request that was sent.
         */
        async silentAuthorizeHelper(authClient, request) {
            const correlationId = request.correlationId;
            const pkceCodes = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
            const silentRequest = {
                ...request,
                codeChallenge: pkceCodes.challenge,
            };
            let iframe;
            if (request.httpMethod === HttpMethod.POST) {
                iframe = await invokeAsync(initiateCodeFlowWithPost, SilentHandlerInitiateAuthRequest, this.logger, this.performanceClient, correlationId)(this.config, authClient.authority, silentRequest, this.logger, this.performanceClient);
            }
            else {
                // Create authorize request url
                const navigateUrl = await invokeAsync(getAuthCodeRequestUrl, GetAuthCodeUrl, this.logger, this.performanceClient, correlationId)(this.config, authClient.authority, silentRequest, this.logger, this.performanceClient);
                // Get the frame handle for the silent request
                iframe = await invokeAsync(initiateCodeRequest, SilentHandlerInitiateAuthRequest, this.logger, this.performanceClient, correlationId)(navigateUrl, this.performanceClient, this.logger, correlationId);
            }
            const responseType = this.config.auth.OIDCOptions.responseMode;
            // Wait for response from the redirect bridge.
            let responseString;
            try {
                responseString = await invokeAsync(waitForBridgeResponse, SilentHandlerMonitorIframeForHash, this.logger, this.performanceClient, correlationId)(this.config.system.iframeBridgeTimeout, this.logger, this.browserCrypto, request, this.performanceClient, this.config.experimental);
            }
            finally {
                invoke(removeHiddenIframe, RemoveHiddenIframe, this.logger, this.performanceClient, correlationId)(iframe);
            }
            const serverParams = invoke(deserializeResponse, DeserializeResponse, this.logger, this.performanceClient, correlationId)(responseString, responseType, this.logger, this.correlationId);
            return { serverParams, pkceCodes, silentRequest };
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class SilentRefreshClient extends StandardInteractionClient {
        /**
         * Exchanges the refresh token for new tokens
         * @param request
         */
        async acquireToken(request) {
            const baseRequest = await invokeAsync(initializeBaseRequest, InitializeBaseRequest, this.logger, this.performanceClient, request.correlationId)(request, this.config, this.performanceClient, this.logger, this.correlationId);
            const silentRequest = {
                ...request,
                ...baseRequest,
            };
            if (request.redirectUri) {
                // Make sure any passed redirectUri is converted to an absolute URL - redirectUri is not a required parameter for refresh token redemption so only include if explicitly provided
                silentRequest.redirectUri = getRedirectUri(request.redirectUri, this.config.auth.redirectUri, this.logger, this.correlationId);
            }
            const serverTelemetryManager = initializeServerTelemetryManager(ApiId.acquireTokenSilent_silentFlow, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
            const refreshTokenClient = await this.createRefreshTokenClient({
                serverTelemetryManager,
                authorityUrl: silentRequest.authority,
                azureCloudOptions: silentRequest.azureCloudOptions,
                account: silentRequest.account,
            });
            // Send request to renew token. Auth module will throw errors if token cannot be renewed.
            return invokeAsync(refreshTokenClient.acquireTokenByRefreshToken.bind(refreshTokenClient), RefreshTokenClientAcquireTokenByRefreshToken, this.logger, this.performanceClient, request.correlationId)(silentRequest, ApiId.acquireTokenSilent_silentFlow).catch((e) => {
                e.setCorrelationId(this.correlationId);
                serverTelemetryManager.cacheFailedRequest(e);
                throw e;
            });
        }
        /**
         * Currently Unsupported
         */
        logout() {
            // Synchronous so we must reject
            return Promise.reject(createBrowserAuthError(silentLogoutUnsupported));
        }
        /**
         * Creates a Refresh Client with the given authority, or the default authority.
         * @param params {
         *         serverTelemetryManager: ServerTelemetryManager;
         *         authorityUrl?: string;
         *         azureCloudOptions?: AzureCloudOptions;
         *         extraQueryParams?: StringDict;
         *         account?: AccountInfo;
         *        }
         */
        async createRefreshTokenClient(params) {
            // Create auth module.
            const clientConfig = await invokeAsync(this.getClientConfiguration.bind(this), StandardInteractionClientGetClientConfiguration, this.logger, this.performanceClient, this.correlationId)({
                serverTelemetryManager: params.serverTelemetryManager,
                requestAuthority: params.authorityUrl,
                requestAzureCloudOptions: params.azureCloudOptions,
                requestExtraQueryParameters: params.extraQueryParameters,
                account: params.account,
            });
            return new RefreshTokenClient(clientConfig, this.performanceClient);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class HybridSpaAuthorizationCodeClient extends AuthorizationCodeClient {
        constructor(config, performanceClient) {
            super(config, performanceClient);
            this.includeRedirectUri = false;
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class SilentAuthCodeClient extends StandardInteractionClient {
        constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, correlationId, platformAuthProvider) {
            super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthProvider);
            this.apiId = apiId;
        }
        /**
         * Acquires a token silently by redeeming an authorization code against the /token endpoint
         * @param request
         */
        async acquireToken(request) {
            // Auth code payload is required
            if (!request.code) {
                throw createBrowserAuthError(authCodeRequired);
            }
            // Create silent request
            const silentRequest = await invokeAsync(initializeAuthorizationRequest, StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(request, exports.InteractionType.Silent, this.config, this.browserCrypto, this.browserStorage, this.logger, this.performanceClient, 
            /*
             * correlationId is optional in request payload, while this.correlationId is always instantiated as request.correlationId || createGuid().
             * Each auth request creates a new instance of *Client so we can safely use this.correlationId.
             */
            this.correlationId);
            const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger);
            try {
                // Create auth code request (PKCE not needed)
                const authCodeRequest = {
                    ...silentRequest,
                    code: request.code,
                };
                // Initialize the client
                const clientConfig = await invokeAsync(this.getClientConfiguration.bind(this), StandardInteractionClientGetClientConfiguration, this.logger, this.performanceClient, this.correlationId)({
                    serverTelemetryManager,
                    requestAuthority: silentRequest.authority,
                    requestAzureCloudOptions: silentRequest.azureCloudOptions,
                    requestExtraQueryParameters: silentRequest.extraQueryParameters,
                    account: silentRequest.account,
                });
                const authClient = new HybridSpaAuthorizationCodeClient(clientConfig, this.performanceClient);
                this.logger.verbose("1uic5e", this.correlationId);
                // Create silent handler
                const interactionHandler = new InteractionHandler(authClient, this.browserStorage, authCodeRequest, this.logger, this.performanceClient);
                // Handle auth code parameters from request
                return await invokeAsync(interactionHandler.handleCodeResponseFromServer.bind(interactionHandler), HandleCodeResponseFromServer, this.logger, this.performanceClient, this.correlationId)({
                    code: request.code,
                    msgraph_host: request.msGraphHost,
                    cloud_graph_host_name: request.cloudGraphHostName,
                    cloud_instance_host_name: request.cloudInstanceHostName,
                }, silentRequest, this.apiId, false);
            }
            catch (e) {
                if (e instanceof AuthError) {
                    e.setCorrelationId(this.correlationId);
                    serverTelemetryManager.cacheFailedRequest(e);
                }
                throw e;
            }
        }
        /**
         * Currently Unsupported
         */
        logout() {
            // Synchronous so we must reject
            return Promise.reject(createBrowserAuthError(silentLogoutUnsupported));
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Get network information for telemetry purposes. This is only supported in Chromium-based browsers.
     * @returns Network connection information, or an empty object if not available.
     */
    function getNetworkInfo() {
        if (typeof window === "undefined" || !window.navigator) {
            return {};
        }
        const connection = "connection" in window.navigator
            ? window.navigator.connection
            : undefined;
        return {
            effectiveType: connection?.effectiveType,
            rtt: connection?.rtt,
        };
    }
    function collectInstanceStats(currentClientId, performanceEvent, logger, correlationId) {
        const frameInstances = 
        // @ts-ignore
        window.msal?.clientIds || [];
        const msalInstanceCount = frameInstances.length;
        const sameClientIdInstanceCount = frameInstances.filter((i) => i === currentClientId).length;
        if (sameClientIdInstanceCount > 1) {
            logger.warning("1e88vg", correlationId);
        }
        performanceEvent.add({
            msalInstanceCount: msalInstanceCount,
            sameClientIdInstanceCount: sameClientIdInstanceCount,
        });
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function preflightCheck(initialized, performanceEvent, config, request) {
        try {
            preflightCheck$1(initialized);
            enforceResourceParameter(config.auth.isMcp, request);
        }
        catch (e) {
            performanceEvent.end({ success: false }, e, request.account);
            throw e;
        }
    }
    class StandardController {
        /**
         * @constructor
         * Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
         *
         * Important attributes in the Configuration object for auth are:
         * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
         * - authority: the authority URL for your application.
         * - redirect_uri: the uri of your application registered in the portal.
         *
         * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
         * It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
         * If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
         * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
         * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
         * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
         *
         * In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
         * Full B2C functionality will be available in this library in future versions.
         *
         * @param configuration Object for the MSAL PublicClientApplication instance
         */
        constructor(operatingContext) {
            this.operatingContext = operatingContext;
            this.isBrowserEnvironment =
                this.operatingContext.isBrowserEnvironment();
            // Set the configuration.
            this.config = operatingContext.getConfig();
            this.initialized = false;
            // Initialize logger
            this.logger = this.operatingContext.getLogger();
            // Initialize the network module class.
            this.networkClient = this.config.system.networkClient;
            // Initialize the navigation client class.
            this.navigationClient = this.config.system.navigationClient;
            // Initialize redirectResponse Map
            this.redirectResponse = new Map();
            // Initial hybrid spa map
            this.hybridAuthCodeResponses = new Map();
            // Initialize performance client
            this.performanceClient = this.config.telemetry.client;
            // Initialize the crypto class.
            this.browserCrypto = this.isBrowserEnvironment
                ? new CryptoOps(this.logger, this.performanceClient)
                : DEFAULT_CRYPTO_IMPLEMENTATION;
            this.eventHandler = new EventHandler(this.logger);
            // Initialize the browser storage class.
            this.browserStorage = this.isBrowserEnvironment
                ? new BrowserCacheManager(this.config.auth.clientId, this.config.cache, this.browserCrypto, this.logger, this.performanceClient, this.eventHandler, buildStaticAuthorityOptions(this.config.auth))
                : DEFAULT_BROWSER_CACHE_MANAGER(this.config.auth.clientId, this.logger, this.performanceClient, this.eventHandler);
            // initialize in memory storage for native flows
            const nativeCacheOptions = {
                cacheLocation: BrowserCacheLocation.MemoryStorage,
                cacheRetentionDays: 5,
            };
            this.nativeInternalStorage = new BrowserCacheManager(this.config.auth.clientId, nativeCacheOptions, this.browserCrypto, this.logger, this.performanceClient, this.eventHandler);
            this.activeSilentTokenRequests = new Map();
            // Register listener functions
            this.trackStateChange = this.trackStateChange.bind(this);
            // Register listener functions
            this.trackStateChangeWithMeasurement =
                this.trackStateChangeWithMeasurement.bind(this);
        }
        static async createController(operatingContext, request) {
            const controller = new StandardController(operatingContext);
            await controller.initialize(request);
            return controller;
        }
        trackStateChange(correlationId, event) {
            if (!correlationId) {
                return;
            }
            if (event.type === "visibilitychange") {
                this.logger.info("16v6hv", correlationId);
                this.performanceClient.incrementFields({ visibilityChangeCount: 1 }, correlationId);
            }
            else if (event.type === "online") {
                this.logger.info("0zirfd", correlationId);
                this.performanceClient.incrementFields({ onlineStatusChangeCount: 1 }, correlationId);
            }
            else if (event.type === "offline") {
                this.logger.info("1xk9ef", correlationId);
                this.performanceClient.incrementFields({ onlineStatusChangeCount: 1 }, correlationId);
            }
        }
        /**
         * Initializer function to perform async startup tasks such as connecting to WAM extension
         * @param request {?InitializeApplicationRequest} correlation id
         */
        async initialize(request) {
            const correlationId = this.getRequestCorrelationId(request);
            this.logger.trace("1f7joy", correlationId);
            if (this.initialized) {
                this.logger.info("061m5x", correlationId);
                return;
            }
            if (!this.isBrowserEnvironment) {
                this.logger.info("19fvpi", correlationId);
                this.initialized = true;
                this.eventHandler.emitEvent(EventType.INITIALIZE_END, correlationId);
                return;
            }
            const allowPlatformBroker = this.config.system.allowPlatformBroker;
            const initMeasurement = this.performanceClient.startMeasurement(InitializeClientApplication, correlationId);
            this.eventHandler.emitEvent(EventType.INITIALIZE_START, correlationId);
            // Broker applications are initialized twice, so we avoid double-counting it
            this.logMultipleInstances(initMeasurement, correlationId);
            initMeasurement.add({ isMcp: this.config.auth.isMcp });
            await invokeAsync(this.browserStorage.initialize.bind(this.browserStorage), InitializeCache, this.logger, this.performanceClient, correlationId)(correlationId);
            if (allowPlatformBroker) {
                try {
                    // check if platform authentication is available via DOM or browser extension and create relevant handlers
                    this.platformAuthProvider = await getPlatformAuthProvider(this.logger, this.performanceClient, correlationId, this.config.system.nativeBrokerHandshakeTimeout);
                }
                catch (e) {
                    this.logger.verbose(e, correlationId);
                }
            }
            if (this.config.cache.cacheLocation ===
                BrowserCacheLocation.LocalStorage) {
                this.eventHandler.subscribeCrossTab();
            }
            !this.config.system.navigatePopups &&
                (await this.preGeneratePkceCodes(correlationId));
            this.initialized = true;
            this.eventHandler.emitEvent(EventType.INITIALIZE_END, correlationId);
            initMeasurement.end({
                allowPlatformBroker: allowPlatformBroker,
                success: true,
            });
        }
        // #region Redirect Flow
        /**
         * Event handler function which allows users to fire events after the PublicClientApplication object
         * has loaded during redirect flows. This should be invoked on all page loads involved in redirect
         * auth flows.
         * @param hash Hash to process. Defaults to the current value of window.location.hash. Only needs to be provided explicitly if the response to be handled is not contained in the current value.
         * @param options Object containing optional configuration for redirect promise handling.
         * @returns Token response or null. If the return value is null, then no auth redirect was detected.
         */
        async handleRedirectPromise(options) {
            this.logger.verbose("02l8bm", "");
            // Block token acquisition before initialize has been called
            blockAPICallsBeforeInitialize(this.initialized);
            if (this.isBrowserEnvironment) {
                /**
                 * Store the promise on the PublicClientApplication instance if this is the first invocation of handleRedirectPromise,
                 * otherwise return the promise from the first invocation. Prevents race conditions when handleRedirectPromise is called
                 * several times concurrently.
                 */
                const redirectResponseKey = options?.hash || "";
                let response = this.redirectResponse.get(redirectResponseKey);
                if (typeof response === "undefined") {
                    response = this.handleRedirectPromiseInternal(options);
                    this.redirectResponse.set(redirectResponseKey, response);
                    this.logger.verbose("1wn9kp", "");
                }
                else {
                    this.logger.verbose("0w0gm3", "");
                }
                return response;
            }
            this.logger.verbose("12xi63", "");
            return null;
        }
        /**
         * The internal details of handleRedirectPromise. This is separated out to a helper to allow handleRedirectPromise to memoize requests
         * @param hash
         * @returns
         */
        async handleRedirectPromiseInternal(options) {
            if (!this.browserStorage.isInteractionInProgress(true)) {
                this.logger.info("0le6uv", "");
                return null;
            }
            const interactionType = this.browserStorage.getInteractionInProgress()?.type;
            if (interactionType === INTERACTION_TYPE.SIGNOUT) {
                this.logger.verbose("1ywcv2", "");
                this.browserStorage.setInteractionInProgress(false);
                return Promise.resolve(null);
            }
            const loggedInAccounts = this.getAllAccounts();
            const platformBrokerRequest = this.browserStorage.getCachedNativeRequest();
            const useNative = platformBrokerRequest && !options?.hash;
            let rootMeasurement;
            let redirectResponse;
            let cachedRedirectRequest;
            try {
                if (useNative && this.platformAuthProvider) {
                    const correlationId = platformBrokerRequest?.correlationId || "";
                    this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_START, correlationId, exports.InteractionType.Redirect);
                    rootMeasurement = this.performanceClient.startMeasurement(AcquireTokenRedirect, correlationId);
                    this.logger.trace("12v7is", correlationId);
                    rootMeasurement.add({
                        isPlatformBrokerRequest: true,
                    });
                    const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.handleRedirectPromise, this.performanceClient, this.platformAuthProvider, platformBrokerRequest.accountId, this.nativeInternalStorage, platformBrokerRequest.correlationId);
                    redirectResponse = invokeAsync(nativeClient.handleRedirectPromise.bind(nativeClient), HandleNativeRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)();
                }
                else {
                    const [standardRequest, codeVerifier] = this.browserStorage.getCachedRequest("");
                    cachedRedirectRequest = standardRequest;
                    const correlationId = standardRequest.correlationId;
                    this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_START, correlationId, exports.InteractionType.Redirect);
                    // Reset rootMeasurement now that we have correlationId
                    rootMeasurement = this.performanceClient.startMeasurement(AcquireTokenRedirect, correlationId);
                    this.logger.trace("0znzs5", correlationId);
                    const redirectClient = this.createRedirectClient(correlationId);
                    redirectResponse = invokeAsync(redirectClient.handleRedirectPromise.bind(redirectClient), HandleRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)(standardRequest, codeVerifier, rootMeasurement, options);
                }
            }
            catch (e) {
                this.browserStorage.resetRequestCache("");
                throw e;
            }
            return redirectResponse
                .then((result) => {
                if (result) {
                    this.browserStorage.resetRequestCache(result.correlationId);
                    this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, result.correlationId, exports.InteractionType.Redirect, result);
                    this.logger.verbose("0ui8f5", result.correlationId);
                    // Emit login event if number of accounts change
                    const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
                    if (isLoggingIn) {
                        this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, result.correlationId, exports.InteractionType.Redirect, result.account);
                        this.logger.verbose("16im3l", result.correlationId);
                    }
                    rootMeasurement.end({
                        success: true,
                    }, undefined, result.account);
                    // Fire-and-forget SSO capability verification in background
                    this.verifySsoCapability(cachedRedirectRequest, exports.InteractionType.Redirect);
                }
                else {
                    /*
                     * Instrument an event only if an error code is set. Otherwise, discard it when the redirect response
                     * is empty and the error code is missing.
                     */
                    if (rootMeasurement.event.errorCode) {
                        rootMeasurement.end({ success: false }, undefined);
                    }
                    else {
                        rootMeasurement.discard();
                    }
                }
                this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, rootMeasurement.event.correlationId, exports.InteractionType.Redirect);
                return result;
            })
                .catch((e) => {
                this.browserStorage.resetRequestCache(rootMeasurement.event.correlationId);
                const eventError = e;
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, rootMeasurement.event.correlationId, exports.InteractionType.Redirect, null, eventError);
                this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, rootMeasurement.event.correlationId, exports.InteractionType.Redirect);
                rootMeasurement.end({
                    success: false,
                }, eventError);
                throw e;
            });
        }
        /**
         * Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint. This function redirects
         * the page, so any code that follows this function will not execute.
         *
         * IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
         * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
         *
         * @param request
         */
        async acquireTokenRedirect(request) {
            // Preflight request
            const correlationId = this.getRequestCorrelationId(request);
            this.logger.verbose("0os66p", correlationId);
            const atrMeasurement = this.performanceClient.startMeasurement(AcquireTokenPreRedirect, correlationId);
            atrMeasurement.add({
                scenarioId: request.scenarioId,
            });
            const configOnRedirectNavigateCb = this.config.auth.onRedirectNavigate;
            this.config.auth.onRedirectNavigate = (url) => {
                const navigate = typeof configOnRedirectNavigateCb === "function"
                    ? configOnRedirectNavigateCb(url)
                    : undefined;
                atrMeasurement.add({
                    navigateCallbackResult: navigate !== false,
                });
                atrMeasurement.event =
                    atrMeasurement.end({ success: true }, undefined, request.account) || atrMeasurement.event;
                return navigate;
            };
            try {
                redirectPreflightCheck(this.initialized, this.config);
                enforceResourceParameter(this.config.auth.isMcp, request);
                this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNIN);
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, exports.InteractionType.Redirect, request);
                let result;
                if (this.platformAuthProvider &&
                    this.canUsePlatformBroker(request)) {
                    const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenRedirect, this.performanceClient, this.platformAuthProvider, this.getNativeAccountId(request), this.nativeInternalStorage, correlationId);
                    result = invokeAsync(nativeClient.acquireTokenRedirect.bind(nativeClient), NativeInteractionClientAcquireTokenRedirect, this.logger, this.performanceClient, correlationId)(request, atrMeasurement).catch((e) => {
                        atrMeasurement.add({
                            brokerErrorName: e.name,
                            brokerErrorCode: e.errorCode,
                        });
                        if (e instanceof NativeAuthError &&
                            isFatalNativeAuthError(e)) {
                            this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
                            const redirectClient = this.createRedirectClient(correlationId);
                            return redirectClient.acquireToken(request);
                        }
                        else if (e instanceof InteractionRequiredAuthError) {
                            this.logger.verbose("1ipyz4", correlationId);
                            const redirectClient = this.createRedirectClient(correlationId);
                            return redirectClient.acquireToken(request);
                        }
                        throw e;
                    });
                }
                else {
                    const redirectClient = this.createRedirectClient(correlationId);
                    result = redirectClient.acquireToken(request);
                }
                return await result;
            }
            catch (e) {
                this.browserStorage.resetRequestCache(correlationId);
                /*
                 * Pre-redirect event completes before navigation occurs.
                 * Timed out navigation needs to be instrumented separately as a post-redirect event.
                 */
                if (atrMeasurement.event.status === 2) {
                    this.performanceClient
                        .startMeasurement(AcquireTokenRedirect, correlationId)
                        .end({ success: false }, e, request.account);
                }
                else {
                    atrMeasurement.end({ success: false }, e, request.account);
                }
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, exports.InteractionType.Redirect, null, e);
                throw e;
            }
        }
        // #endregion
        // #region Popup Flow
        /**
         * Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
         *
         * @param request
         *
         * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
         */
        acquireTokenPopup(request) {
            const correlationId = this.getRequestCorrelationId(request);
            const atPopupMeasurement = this.performanceClient.startMeasurement(AcquireTokenPopup, correlationId);
            atPopupMeasurement.add({
                scenarioId: request.scenarioId,
            });
            try {
                this.logger.verbose("0ch87b", correlationId);
                preflightCheck(this.initialized, atPopupMeasurement, this.config, request);
                this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNIN, request.overrideInteractionInProgress, correlationId);
            }
            catch (e) {
                // Since this function is syncronous we need to reject
                return Promise.reject(e);
            }
            // If logged in, emit acquire token events
            const loggedInAccounts = this.getAllAccounts();
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, exports.InteractionType.Popup, request);
            let result;
            const pkce = this.getPreGeneratedPkceCodes(correlationId);
            if (this.canUsePlatformBroker(request)) {
                atPopupMeasurement.add({
                    isPlatformBrokerRequest: true,
                });
                result = this.acquireTokenNative({
                    ...request,
                    correlationId,
                }, ApiId.acquireTokenPopup)
                    .then((response) => {
                    atPopupMeasurement.end({
                        success: true,
                        isNativeBroker: true,
                    }, undefined, response.account);
                    return response;
                })
                    .catch((e) => {
                    atPopupMeasurement.add({
                        brokerErrorName: e.name,
                        brokerErrorCode: e.errorCode,
                    });
                    if (e instanceof NativeAuthError &&
                        isFatalNativeAuthError(e)) {
                        this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
                        const popupClient = this.createPopupClient(correlationId);
                        return popupClient.acquireToken(request, pkce);
                    }
                    else if (e instanceof InteractionRequiredAuthError) {
                        this.logger.verbose("0yy5fw", correlationId);
                        const popupClient = this.createPopupClient(correlationId);
                        return popupClient.acquireToken(request, pkce);
                    }
                    throw e;
                });
            }
            else {
                const popupClient = this.createPopupClient(correlationId);
                result = popupClient.acquireToken(request, pkce);
            }
            return result
                .then((result) => {
                /*
                 *  If logged in, emit acquire token events
                 */
                const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, exports.InteractionType.Popup, result);
                if (isLoggingIn) {
                    this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, correlationId, exports.InteractionType.Popup, result.account);
                }
                atPopupMeasurement.end({
                    success: true,
                    accessTokenSize: result.accessToken.length,
                    idTokenSize: result.idToken.length,
                }, undefined, result.account);
                // SSO capability verification in background
                this.verifySsoCapability(request, exports.InteractionType.Popup);
                return result;
            })
                .catch((e) => {
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, exports.InteractionType.Popup, null, e);
                atPopupMeasurement.end({
                    success: false,
                }, e, request.account);
                // Since this function is syncronous we need to reject
                return Promise.reject(e);
            })
                .finally(async () => {
                this.browserStorage.setInteractionInProgress(false);
                if (!this.config.system.navigatePopups) {
                    await this.preGeneratePkceCodes(correlationId);
                }
            });
        }
        trackStateChangeWithMeasurement(event) {
            const measurement = this.ssoSilentMeasurement ||
                this.acquireTokenByCodeAsyncMeasurement;
            if (!measurement) {
                return;
            }
            if (event.type === "visibilitychange") {
                this.logger.info("0yzimq", measurement.event.correlationId);
                measurement.increment({
                    visibilityChangeCount: 1,
                });
            }
            else if (event.type === "online") {
                this.logger.info("1caf53", measurement.event.correlationId);
                measurement.increment({
                    onlineStatusChangeCount: 1,
                });
            }
            else if (event.type === "offline") {
                this.logger.info("0fdyk7", measurement.event.correlationId);
                measurement.increment({
                    onlineStatusChangeCount: 1,
                });
            }
        }
        addStateChangeListeners(listener) {
            document.addEventListener("visibilitychange", listener);
            window.addEventListener("online", listener);
            window.addEventListener("offline", listener);
        }
        removeStateChangeListeners(listener) {
            document.removeEventListener("visibilitychange", listener);
            window.removeEventListener("online", listener);
            window.removeEventListener("offline", listener);
        }
        /**
         * Reads the cached ssoCapable value from localStorage.
         * @returns The cached ssoCapable boolean value, or undefined if not cached or expired.
         */
        getCachedSsoCapable() {
            try {
                const cachedValue = window.localStorage.getItem(SSO_CAPABLE);
                if (cachedValue) {
                    const parsed = JSON.parse(cachedValue);
                    if (parsed &&
                        typeof parsed.ssoCapable === "boolean" &&
                        parsed.expiresOn &&
                        Date.now() < parsed.expiresOn) {
                        return parsed.ssoCapable;
                    }
                }
            }
            catch {
                // If parsing fails, return undefined
            }
            return undefined;
        }
        /**
         * SSO capability verification in the background.
         * This method makes an iframe request to /authorize to verify SSO capability without calling /token.
         * This method does not block the caller and tracks telemetry for success/failure.
         * This method only executes if verifySSO is set to true in the auth configuration.
         * The result is cached in localStorage with a 24-hour TTL; the SSO verification call
         * is only attempted when the cached value is absent or expired.
         * @param request - The original request used for the authentication flow
         * @param interactionType - The interactionType of the AT operation for logging purposes
         */
        verifySsoCapability(request, interactionType) {
            // Check if SSO capability verification is enabled
            if (!this.config.auth.verifySSO) {
                return;
            }
            // Check TTL: derive ssoCapable state from localStorage and skip if not expired
            const ssoCacheKey = SSO_CAPABLE;
            const SSO_CAPABLE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
            const cachedSsoCapable = this.getCachedSsoCapable();
            if (cachedSsoCapable !== undefined) {
                this.logger.verbose("13poou", "");
                return;
            }
            const correlationId = createNewGuid();
            const ssoCapableMeasurement = this.performanceClient.startMeasurement(SsoCapable, correlationId);
            ssoCapableMeasurement.add({
                "ext.interactionType": interactionType,
            });
            this.logger.verbose("0pbr0i", correlationId);
            /*
             * Use setTimeout to ensure this runs in a separate macrotask after the current call stack completes
             * This ensures the result is returned to the caller before the SSO verification starts and doesn't affect performance
             */
            setTimeout(() => {
                const ssoVerificationRequest = {
                    ...request,
                    correlationId: correlationId,
                };
                const silentIframeClient = this.createSilentIframeClient(correlationId);
                silentIframeClient
                    .verifySso(ssoVerificationRequest)
                    .then((result) => {
                    this.logger.verbose("1gd1iv", correlationId);
                    // TBD to add profileTelemetry later in localStorage with 24h TTL
                    try {
                        const cacheEntry = JSON.stringify({
                            ssoCapable: result,
                            expiresOn: Date.now() + SSO_CAPABLE_TTL_MS,
                        });
                        window.localStorage.setItem(ssoCacheKey, cacheEntry);
                    }
                    catch {
                        this.logger.warning("18lmoj", correlationId);
                    }
                    ssoCapableMeasurement.end({
                        fromCache: false,
                        success: result,
                    }, undefined);
                })
                    .catch((error) => {
                    this.logger.warning("05g83w", correlationId);
                    // reset the cache
                    try {
                        window.localStorage.removeItem(ssoCacheKey);
                    }
                    catch {
                        this.logger.warning("0nlf9q", correlationId);
                    }
                    ssoCapableMeasurement.end({
                        fromCache: false,
                        success: false,
                    }, error);
                });
            }, 0);
        }
        // #endregion
        // #region Silent Flow
        /**
         * This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
         * - Any browser using a form of Intelligent Tracking Prevention
         * - If there is not an established session with the service
         *
         * In these cases, the request must be done inside a popup or full frame redirect.
         *
         * For the cases where interaction is required, you cannot send a request with prompt=none.
         *
         * If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
         * you session on the server still exists.
         * @param request {@link SsoSilentRequest}
         *
         * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
         */
        async ssoSilent(request) {
            const correlationId = this.getRequestCorrelationId(request);
            const validRequest = {
                ...request,
                correlationId: correlationId,
            };
            this.ssoSilentMeasurement = this.performanceClient.startMeasurement(SsoSilent, correlationId);
            this.ssoSilentMeasurement?.add({
                scenarioId: request.scenarioId,
                ssoCapable: this.getCachedSsoCapable(),
            });
            preflightCheck(this.initialized, this.ssoSilentMeasurement, this.config, validRequest);
            this.ssoSilentMeasurement?.increment({
                visibilityChangeCount: 0,
                onlineStatusChangeCount: 0,
            });
            this.addStateChangeListeners(this.trackStateChangeWithMeasurement);
            const loggedInAccounts = this.getAllAccounts();
            this.logger.verbose("0w1b45", correlationId);
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, exports.InteractionType.Silent, validRequest);
            let result;
            if (this.canUsePlatformBroker(validRequest)) {
                this.ssoSilentMeasurement?.add({
                    isPlatformBrokerRequest: true,
                });
                result = this.acquireTokenNative(validRequest, ApiId.ssoSilent).catch((e) => {
                    this.ssoSilentMeasurement?.add({
                        brokerErrorName: e.name,
                        brokerErrorCode: e.errorCode,
                    });
                    // If native token acquisition fails for availability reasons fallback to standard flow
                    if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
                        this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
                        const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
                        return silentIframeClient.acquireToken(validRequest);
                    }
                    throw e;
                });
            }
            else {
                const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
                result = silentIframeClient.acquireToken(validRequest);
            }
            return result
                .then((response) => {
                const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, exports.InteractionType.Silent, response);
                if (isLoggingIn) {
                    this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, correlationId, exports.InteractionType.Silent, response.account);
                }
                this.ssoSilentMeasurement?.end({
                    success: true,
                    isNativeBroker: response.fromPlatformBroker,
                    accessTokenSize: response.accessToken.length,
                    idTokenSize: response.idToken.length,
                }, undefined, response.account);
                return response;
            })
                .catch((e) => {
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, exports.InteractionType.Silent, null, e);
                this.ssoSilentMeasurement?.end({
                    success: false,
                }, e, request.account);
                throw e;
            })
                .finally(() => {
                this.removeStateChangeListeners(this.trackStateChangeWithMeasurement);
            });
        }
        /**
         * This function redeems an authorization code (passed as code) from the eSTS token endpoint.
         * This authorization code should be acquired server-side using a confidential client to acquire a spa_code.
         * This API is not indended for normal authorization code acquisition and redemption.
         *
         * Redemption of this authorization code will not require PKCE, as it was acquired by a confidential client.
         *
         * @param request {@link AuthorizationCodeRequest}
         * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
         */
        async acquireTokenByCode(request) {
            const correlationId = this.getRequestCorrelationId(request);
            this.logger.trace("0ch6ga", correlationId);
            const atbcMeasurement = this.performanceClient.startMeasurement(AcquireTokenByCode, correlationId);
            preflightCheck(this.initialized, atbcMeasurement, this.config, request);
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, exports.InteractionType.Silent, request);
            atbcMeasurement.add({ scenarioId: request.scenarioId });
            try {
                if (request.code && request.nativeAccountId) {
                    // Throw error in case server returns both spa_code and spa_accountid in exchange for auth code.
                    throw createBrowserAuthError(spaCodeAndNativeAccountIdPresent);
                }
                else if (request.code) {
                    const hybridAuthCode = request.code;
                    let response = this.hybridAuthCodeResponses.get(hybridAuthCode);
                    if (!response) {
                        this.logger.verbose("06eh73", correlationId);
                        response = this.acquireTokenByCodeAsync({
                            ...request,
                            correlationId,
                        })
                            .then((result) => {
                            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, exports.InteractionType.Silent, result);
                            this.hybridAuthCodeResponses.delete(hybridAuthCode);
                            atbcMeasurement.end({
                                success: true,
                                accessTokenSize: result.accessToken.length,
                                idTokenSize: result.idToken.length,
                            }, undefined, result.account);
                            return result;
                        })
                            .catch((error) => {
                            this.hybridAuthCodeResponses.delete(hybridAuthCode);
                            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, exports.InteractionType.Silent, null, error);
                            atbcMeasurement.end({
                                success: false,
                            }, error);
                            throw error;
                        });
                        this.hybridAuthCodeResponses.set(hybridAuthCode, response);
                    }
                    else {
                        this.logger.verbose("0qgp28", correlationId);
                        atbcMeasurement.discard();
                    }
                    return await response;
                }
                else if (request.nativeAccountId) {
                    if (this.canUsePlatformBroker(request, request.nativeAccountId)) {
                        atbcMeasurement.add({
                            isPlatformBrokerRequest: true,
                        });
                        const result = await this.acquireTokenNative({
                            ...request,
                            correlationId,
                        }, ApiId.acquireTokenByCode, request.nativeAccountId).catch((e) => {
                            atbcMeasurement.add({
                                brokerErrorName: e.name,
                                brokerErrorCode: e.errorCode,
                            });
                            // If native token acquisition fails for availability reasons fallback to standard flow
                            if (e instanceof NativeAuthError &&
                                isFatalNativeAuthError(e)) {
                                this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
                            }
                            throw e;
                        });
                        atbcMeasurement.end({
                            success: true,
                        }, undefined, result.account);
                        return result;
                    }
                    else {
                        throw createBrowserAuthError(unableToAcquireTokenFromNativePlatform);
                    }
                }
                else {
                    throw createBrowserAuthError(authCodeOrNativeAccountIdRequired);
                }
            }
            catch (e) {
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, exports.InteractionType.Silent, null, e);
                atbcMeasurement.end({
                    success: false,
                }, e);
                throw e;
            }
        }
        /**
         * Creates a SilentAuthCodeClient to redeem an authorization code.
         * @param request
         * @returns Result of the operation to redeem the authorization code
         */
        async acquireTokenByCodeAsync(request) {
            const correlationId = this.getRequestCorrelationId(request);
            this.logger.trace("10d9hy", correlationId);
            this.acquireTokenByCodeAsyncMeasurement =
                this.performanceClient.startMeasurement(AcquireTokenByCodeAsync, correlationId);
            this.acquireTokenByCodeAsyncMeasurement?.increment({
                visibilityChangeCount: 0,
                onlineStatusChangeCount: 0,
            });
            this.addStateChangeListeners(this.trackStateChangeWithMeasurement);
            const silentAuthCodeClient = this.createSilentAuthCodeClient(correlationId);
            const silentTokenResult = await silentAuthCodeClient
                .acquireToken(request)
                .then((response) => {
                this.acquireTokenByCodeAsyncMeasurement?.end({
                    success: true,
                    fromCache: response.fromCache,
                });
                return response;
            })
                .catch((tokenRenewalError) => {
                this.acquireTokenByCodeAsyncMeasurement?.end({
                    success: false,
                }, tokenRenewalError);
                throw tokenRenewalError;
            })
                .finally(() => {
                this.removeStateChangeListeners(this.trackStateChangeWithMeasurement);
            });
            return silentTokenResult;
        }
        /**
         * Attempt to acquire an access token from the cache
         * @param silentCacheClient SilentCacheClient
         * @param commonRequest CommonSilentFlowRequest
         * @param silentRequest SilentRequest
         * @returns A promise that, when resolved, returns the access token
         */
        async acquireTokenFromCache(commonRequest, cacheLookupPolicy) {
            switch (cacheLookupPolicy) {
                case CacheLookupPolicy.Default:
                case CacheLookupPolicy.AccessToken:
                case CacheLookupPolicy.AccessTokenAndRefreshToken:
                    const silentCacheClient = this.createSilentCacheClient(commonRequest.correlationId);
                    return invokeAsync(silentCacheClient.acquireToken.bind(silentCacheClient), SilentCacheClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
                default:
                    throw createClientAuthError(tokenRefreshRequired);
            }
        }
        /**
         * Attempt to acquire an access token via a refresh token
         * @param commonRequest CommonSilentFlowRequest
         * @param cacheLookupPolicy CacheLookupPolicy
         * @returns A promise that, when resolved, returns the access token
         */
        async acquireTokenByRefreshToken(commonRequest, cacheLookupPolicy) {
            switch (cacheLookupPolicy) {
                case CacheLookupPolicy.Default:
                case CacheLookupPolicy.AccessTokenAndRefreshToken:
                case CacheLookupPolicy.RefreshToken:
                case CacheLookupPolicy.RefreshTokenAndNetwork:
                    const silentRefreshClient = this.createSilentRefreshClient(commonRequest.correlationId);
                    return invokeAsync(silentRefreshClient.acquireToken.bind(silentRefreshClient), SilentRefreshClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
                default:
                    throw createClientAuthError(tokenRefreshRequired);
            }
        }
        /**
         * Attempt to acquire an access token via an iframe
         * @param request CommonSilentFlowRequest
         * @returns A promise that, when resolved, returns the access token
         */
        async acquireTokenBySilentIframe(request) {
            const silentIframeClient = this.createSilentIframeClient(request.correlationId);
            return invokeAsync(silentIframeClient.acquireToken.bind(silentIframeClient), SilentIframeClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(request);
        }
        // #endregion
        // #region Logout
        /**
         * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
         * Default behaviour is to redirect the user to `window.location.href`.
         * @param logoutRequest
         */
        async logoutRedirect(logoutRequest) {
            const correlationId = this.getRequestCorrelationId(logoutRequest);
            redirectPreflightCheck(this.initialized, this.config);
            this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
            const redirectClient = this.createRedirectClient(correlationId);
            return redirectClient.logout(logoutRequest);
        }
        /**
         * Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
         * @param logoutRequest
         */
        logoutPopup(logoutRequest) {
            try {
                const correlationId = this.getRequestCorrelationId(logoutRequest);
                preflightCheck$1(this.initialized);
                this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
                const popupClient = this.createPopupClient(correlationId);
                return popupClient.logout(logoutRequest).finally(() => {
                    this.browserStorage.setInteractionInProgress(false);
                });
            }
            catch (e) {
                // Since this function is syncronous we need to reject
                return Promise.reject(e);
            }
        }
        /**
         * Creates a cache interaction client to clear broswer cache.
         * @param logoutRequest
         */
        async clearCache(logoutRequest) {
            if (!this.isBrowserEnvironment) {
                return;
            }
            const correlationId = this.getRequestCorrelationId(logoutRequest);
            const cacheClient = this.createSilentCacheClient(correlationId);
            return cacheClient.logout(logoutRequest);
        }
        // #endregion
        // #region Account APIs
        /**
         * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
         * @param accountFilter - (Optional) filter to narrow down the accounts returned
         * @returns Array of AccountInfo objects in cache
         */
        getAllAccounts(accountFilter) {
            return getAllAccounts(this.logger, this.browserStorage, this.isBrowserEnvironment, this.getRequestCorrelationId(), accountFilter);
        }
        /**
         * Returns the first account found in the cache that matches the account filter passed in.
         * @param accountFilter
         * @returns The first account found in the cache matching the provided filter or null if no account could be found.
         */
        getAccount(accountFilter) {
            return getAccount(accountFilter, this.logger, this.browserStorage, this.getRequestCorrelationId());
        }
        /**
         * Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
         * @param account
         */
        setActiveAccount(account) {
            setActiveAccount(account, this.browserStorage, this.getRequestCorrelationId());
        }
        /**
         * Gets the currently active account
         */
        getActiveAccount() {
            return getActiveAccount(this.browserStorage, this.getRequestCorrelationId());
        }
        // #endregion
        /**
         * Hydrates the cache with the tokens from an AuthenticationResult
         * @param result
         * @param request
         * @returns
         */
        async hydrateCache(result, request) {
            this.logger.verbose("16jycr", result.correlationId);
            // Account gets saved to browser storage regardless of native or not
            const accountEntity = createAccountEntityFromAccountInfo(result.account, result.cloudGraphHostName, result.msGraphHost);
            await this.browserStorage.setAccount(accountEntity, result.correlationId, isKmsi(result.idTokenClaims), ApiId.hydrateCache);
            if (result.fromPlatformBroker) {
                this.logger.verbose("1fxyu8", result.correlationId);
                // Tokens from native broker are stored in-memory
                return this.nativeInternalStorage.hydrateCache(result, request);
            }
            else {
                return this.browserStorage.hydrateCache(result, request);
            }
        }
        // #region Helpers
        /**
         * Acquire a token from native device (e.g. WAM)
         * @param request
         */
        async acquireTokenNative(request, apiId, accountId, cacheLookupPolicy) {
            const correlationId = this.getRequestCorrelationId(request);
            this.logger.trace("0b9y3p", correlationId);
            if (!this.platformAuthProvider) {
                throw createBrowserAuthError(nativeConnectionNotEstablished);
            }
            const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, apiId, this.performanceClient, this.platformAuthProvider, accountId || this.getNativeAccountId(request), this.nativeInternalStorage, correlationId);
            return invokeAsync(nativeClient.acquireToken.bind(nativeClient), NativeInteractionClientAcquireToken, this.logger, this.performanceClient, correlationId)(request, cacheLookupPolicy);
        }
        /**
         * Returns boolean indicating if this request can use the platform broker
         * @param request
         */
        canUsePlatformBroker(request, accountId) {
            const correlationId = this.getRequestCorrelationId(request);
            this.logger.trace("1n9lbl", correlationId);
            if (!this.platformAuthProvider) {
                this.logger.trace("0vnu11", correlationId);
                return false;
            }
            if (!isPlatformAuthAllowed(this.config, this.logger, correlationId, this.platformAuthProvider, request.authenticationScheme)) {
                this.logger.trace("0yoy1g", correlationId);
                return false;
            }
            if (request.prompt) {
                switch (request.prompt) {
                    case PromptValue$1.NONE:
                    case PromptValue$1.CONSENT:
                    case PromptValue$1.LOGIN:
                        this.logger.trace("0vdv8e", correlationId);
                        break;
                    default:
                        this.logger.trace("0pdzw6", correlationId);
                        return false;
                }
            }
            if (!accountId && !this.getNativeAccountId(request)) {
                this.logger.trace("16lbtk", correlationId);
                return false;
            }
            return true;
        }
        /**
         * Get the native accountId from the account
         * @param request
         * @returns
         */
        getNativeAccountId(request) {
            const account = request.account ||
                this.getAccount({
                    loginHint: request.loginHint,
                    sid: request.sid,
                }) ||
                this.getActiveAccount();
            return (account && account.nativeAccountId) || "";
        }
        /**
         * Returns new instance of the Popup Interaction Client
         * @param correlationId
         */
        createPopupClient(correlationId) {
            return new PopupClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider);
        }
        /**
         * Returns new instance of the Redirect Interaction Client
         * @param correlationId
         */
        createRedirectClient(correlationId) {
            return new RedirectClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider);
        }
        /**
         * Returns new instance of the Silent Iframe Interaction Client
         * @param correlationId
         */
        createSilentIframeClient(correlationId) {
            return new SilentIframeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.ssoSilent, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider);
        }
        /**
         * Returns new instance of the Silent Cache Interaction Client
         */
        createSilentCacheClient(correlationId) {
            return new SilentCacheClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, correlationId, this.platformAuthProvider);
        }
        /**
         * Returns new instance of the Silent Refresh Interaction Client
         */
        createSilentRefreshClient(correlationId) {
            return new SilentRefreshClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, correlationId, this.platformAuthProvider);
        }
        /**
         * Returns new instance of the Silent AuthCode Interaction Client
         */
        createSilentAuthCodeClient(correlationId) {
            return new SilentAuthCodeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenByCode, this.performanceClient, correlationId, this.platformAuthProvider);
        }
        /**
         * Adds event callbacks to array
         * @param callback
         */
        addEventCallback(callback, eventTypes) {
            return this.eventHandler.addEventCallback(callback, eventTypes);
        }
        /**
         * Removes callback with provided id from callback array
         * @param callbackId
         */
        removeEventCallback(callbackId) {
            this.eventHandler.removeEventCallback(callbackId);
        }
        /**
         * Registers a callback to receive performance events.
         *
         * @param {PerformanceCallbackFunction} callback
         * @returns {string}
         */
        addPerformanceCallback(callback) {
            blockNonBrowserEnvironment();
            return this.performanceClient.addPerformanceCallback(callback);
        }
        /**
         * Removes a callback registered with addPerformanceCallback.
         *
         * @param {string} callbackId
         * @returns {boolean}
         */
        removePerformanceCallback(callbackId) {
            return this.performanceClient.removePerformanceCallback(callbackId);
        }
        /**
         * Returns the logger instance
         */
        getLogger() {
            return this.logger;
        }
        /**
         * Replaces the default logger set in configurations with new Logger with new configurations
         * @param logger Logger instance
         */
        setLogger(logger) {
            this.logger = logger;
        }
        /**
         * Called by wrapper libraries (Angular & React) to set SKU and Version passed down to telemetry, logger, etc.
         * @param sku
         * @param version
         */
        initializeWrapperLibrary(sku, version) {
            // Validate the SKU passed in is one we expect
            this.browserStorage.setWrapperMetadata(sku, version);
        }
        /**
         * Sets navigation client
         * @param navigationClient
         */
        setNavigationClient(navigationClient) {
            this.navigationClient = navigationClient;
        }
        /**
         * Returns the configuration object
         */
        getConfiguration() {
            return this.config;
        }
        /**
         * Returns the performance client
         */
        getPerformanceClient() {
            return this.performanceClient;
        }
        /**
         * Returns the browser env indicator
         */
        isBrowserEnv() {
            return this.isBrowserEnvironment;
        }
        /**
         * Generates a correlation id for a request if none is provided.
         *
         * @protected
         * @param {?Partial<BaseAuthRequest>} [request]
         * @returns {string}
         */
        getRequestCorrelationId(request) {
            if (request?.correlationId) {
                return request.correlationId;
            }
            if (this.isBrowserEnvironment) {
                return createNewGuid();
            }
            /*
             * Included for fallback for non-browser environments,
             * and to ensure this method always returns a string.
             */
            return "";
        }
        // #endregion
        /**
         * Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so
         * any code that follows this function will not execute.
         *
         * IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
         * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
         *
         * @param request
         */
        async loginRedirect(request) {
            const correlationId = this.getRequestCorrelationId(request);
            this.logger.verbose("0lz9hf", correlationId);
            return this.acquireTokenRedirect({
                correlationId,
                ...(request || DEFAULT_REQUEST),
            });
        }
        /**
         * Use when initiating the login process via opening a popup window in the user's browser
         *
         * @param request
         *
         * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
         */
        loginPopup(request) {
            const correlationId = this.getRequestCorrelationId(request);
            this.logger.verbose("0qw7v5", correlationId);
            return this.acquireTokenPopup({
                correlationId,
                ...(request || DEFAULT_REQUEST),
            });
        }
        /**
         * Silently acquire an access token for a given set of scopes. Returns currently processing promise if parallel requests are made.
         *
         * @param {@link (SilentRequest:type)}
         * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
         */
        async acquireTokenSilent(request) {
            const correlationId = this.getRequestCorrelationId(request);
            const atsMeasurement = this.performanceClient.startMeasurement(AcquireTokenSilent, correlationId);
            atsMeasurement.add({
                cacheLookupPolicy: request.cacheLookupPolicy,
                scenarioId: request.scenarioId,
                ssoCapable: this.getCachedSsoCapable(),
            });
            preflightCheck(this.initialized, atsMeasurement, this.config, request);
            this.logger.verbose("0x1c4s", correlationId);
            const account = request.account || this.getActiveAccount();
            if (!account) {
                throw createBrowserAuthError(noAccountError);
            }
            return this.acquireTokenSilentDeduped(request, account, correlationId)
                .then((result) => {
                atsMeasurement.end({
                    success: true,
                    fromCache: result.fromCache,
                    accessTokenSize: result.accessToken.length,
                    idTokenSize: result.idToken.length,
                }, undefined, result.account);
                return {
                    ...result,
                    state: request.state,
                    correlationId: correlationId, // Ensures PWB scenarios can correctly match request to response
                };
            })
                .catch((error) => {
                if (error instanceof AuthError) {
                    // Ensures PWB scenarios can correctly match request to response
                    error.setCorrelationId(correlationId);
                }
                atsMeasurement.end({
                    success: false,
                }, error, account);
                throw error;
            });
        }
        /**
         * Checks if identical request is already in flight and returns reference to the existing promise or fires off a new one if this is the first
         * @param request
         * @param account
         * @param correlationId
         * @returns
         */
        async acquireTokenSilentDeduped(request, account, correlationId) {
            const thumbprint = getRequestThumbprint(this.config.auth.clientId, {
                ...request,
                authority: request.authority || this.config.auth.authority}, account.homeAccountId);
            const silentRequestKey = JSON.stringify(thumbprint);
            const inProgressRequest = this.activeSilentTokenRequests.get(silentRequestKey);
            if (typeof inProgressRequest === "undefined") {
                this.logger.verbose("0fcjbk", correlationId);
                this.performanceClient.addFields({ deduped: false }, correlationId);
                const activeRequest = invokeAsync(this.acquireTokenSilentAsync.bind(this), AcquireTokenSilentAsync, this.logger, this.performanceClient, correlationId)({
                    ...request,
                    correlationId,
                }, account);
                this.activeSilentTokenRequests.set(silentRequestKey, activeRequest);
                return activeRequest.finally(() => {
                    this.activeSilentTokenRequests.delete(silentRequestKey);
                });
            }
            else {
                this.logger.verbose("1yq7nb", correlationId);
                this.performanceClient.addFields({ deduped: true }, correlationId);
                return inProgressRequest;
            }
        }
        /**
         * Silently acquire an access token for a given set of scopes. Will use cached token if available, otherwise will attempt to acquire a new token from the network via refresh token.
         * @param {@link (SilentRequest:type)}
         * @param {@link (AccountInfo:type)}
         * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse}
         */
        async acquireTokenSilentAsync(request, account) {
            const trackStateChange = (event) => this.trackStateChange(request.correlationId, event);
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, request.correlationId, exports.InteractionType.Silent, request);
            if (request.correlationId) {
                this.performanceClient.incrementFields({ visibilityChangeCount: 0, onlineStatusChangeCount: 0 }, request.correlationId);
            }
            this.addStateChangeListeners(trackStateChange);
            const silentRequest = await invokeAsync(initializeSilentRequest, InitializeSilentRequest, this.logger, this.performanceClient, request.correlationId)(request, account, this.config, this.performanceClient, this.logger);
            const cacheLookupPolicy = request.cacheLookupPolicy || CacheLookupPolicy.Default;
            const result = this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy).catch(async (refreshTokenError) => {
                const shouldTryToResolveSilently = checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy);
                if (shouldTryToResolveSilently) {
                    const silentRefreshReason = `${refreshTokenError.errorCode}${refreshTokenError.subError
                    ? `|${refreshTokenError.subError}`
                    : ""}`;
                    this.performanceClient.addFields({ silentRefreshReason }, request.correlationId);
                    if (!this.activeIframeRequest) {
                        let _resolve;
                        // Always set the active request tracker immediately after checking it to prevent races
                        this.activeIframeRequest = [
                            new Promise((resolve) => {
                                _resolve = resolve;
                            }),
                            silentRequest.correlationId,
                        ];
                        this.logger.verbose("0rh08z", silentRequest.correlationId);
                        return invokeAsync(this.acquireTokenBySilentIframe.bind(this), AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest)
                            .then((iframeResult) => {
                            _resolve(true);
                            return iframeResult;
                        })
                            .catch((e) => {
                            _resolve(false);
                            throw e;
                        })
                            .finally(() => {
                            this.activeIframeRequest = undefined;
                        });
                    }
                    else if (cacheLookupPolicy !== CacheLookupPolicy.Skip) {
                        const [activePromise, activeCorrelationId] = this.activeIframeRequest;
                        this.logger.verbose("1w8fso", silentRequest.correlationId);
                        const awaitConcurrentIframeMeasure = this.performanceClient.startMeasurement(AwaitConcurrentIframe, silentRequest.correlationId);
                        awaitConcurrentIframeMeasure.add({
                            awaitIframeCorrelationId: activeCorrelationId,
                        });
                        const activePromiseResult = await activePromise;
                        awaitConcurrentIframeMeasure.end({
                            success: activePromiseResult,
                        });
                        if (activePromiseResult) {
                            this.logger.verbose("0ywzzi", silentRequest.correlationId);
                            // Retry cache lookup and/or RT exchange after iframe completes
                            return this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy);
                        }
                        else {
                            this.logger.info("17y14q", silentRequest.correlationId);
                            // If previous iframe request failed, it's unlikely to succeed this time. Throw original error.
                            throw refreshTokenError;
                        }
                    }
                    else {
                        // Cache policy set to skip and another iframe request is already in progress
                        this.logger.warning("1bd4p8", silentRequest.correlationId);
                        return invokeAsync(this.acquireTokenBySilentIframe.bind(this), AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest);
                    }
                }
                else {
                    // Error cannot be silently resolved or iframe renewal is not allowed, interaction required
                    throw refreshTokenError;
                }
            });
            return result
                .then((response) => {
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, request.correlationId, exports.InteractionType.Silent, response);
                if (request.correlationId) {
                    this.performanceClient.addFields({
                        fromCache: response.fromCache,
                        isNativeBroker: response.fromPlatformBroker,
                    }, request.correlationId);
                }
                return response;
            })
                .catch((tokenRenewalError) => {
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, request.correlationId, exports.InteractionType.Silent, null, tokenRenewalError);
                throw tokenRenewalError;
            })
                .finally(() => {
                this.removeStateChangeListeners(trackStateChange);
            });
        }
        /**
         * AcquireTokenSilent without the iframe fallback. This is used to enable the correct fallbacks in cases where there's a potential for multiple silent requests to be made in parallel and prevent those requests from making concurrent iframe requests.
         * @param silentRequest
         * @param cacheLookupPolicy
         * @returns
         */
        async acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy) {
            // if the cache policy is set to access_token only, we should not be hitting the native layer yet
            if (isPlatformAuthAllowed(this.config, this.logger, silentRequest.correlationId, this.platformAuthProvider, silentRequest.authenticationScheme) &&
                silentRequest.account.nativeAccountId) {
                this.logger.verbose("0sczo4", silentRequest.correlationId);
                this.performanceClient.addFields({ isPlatformBrokerRequest: true }, silentRequest.correlationId);
                return this.acquireTokenNative(silentRequest, ApiId.acquireTokenSilent_silentFlow, silentRequest.account.nativeAccountId, cacheLookupPolicy).catch(async (e) => {
                    this.performanceClient.addFields({
                        brokerErrorName: e.name,
                        brokerErrorCode: e.errorCode,
                    }, silentRequest.correlationId);
                    // If native token acquisition fails for availability reasons fallback to web flow
                    if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
                        this.logger.verbose("07rkmb", silentRequest.correlationId);
                        this.platformAuthProvider = undefined; // Prevent future requests from continuing to attempt
                        // Cache will not contain tokens, given that previous WAM requests succeeded. Skip cache and RT renewal and go straight to iframe renewal
                        throw createClientAuthError(tokenRefreshRequired);
                    }
                    throw e;
                });
            }
            else {
                this.logger.verbose("0ox81t", silentRequest.correlationId);
                // add logs to identify embedded cache retrieval
                if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
                    this.logger.verbose("0fvwxe", silentRequest.correlationId);
                }
                return invokeAsync(this.acquireTokenFromCache.bind(this), AcquireTokenFromCache, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy).catch((cacheError) => {
                    if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
                        throw cacheError;
                    }
                    this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_NETWORK_START, silentRequest.correlationId, exports.InteractionType.Silent, silentRequest);
                    return invokeAsync(this.acquireTokenByRefreshToken.bind(this), AcquireTokenByRefreshToken, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy);
                });
            }
        }
        /**
         * Pre-generates PKCE codes and stores it in local variable
         * @param correlationId
         */
        async preGeneratePkceCodes(correlationId) {
            this.logger.verbose("1x6uj6", correlationId);
            this.pkceCode = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
            return Promise.resolve();
        }
        /**
         * Provides pre-generated PKCE codes, if any
         * @param correlationId
         */
        getPreGeneratedPkceCodes(correlationId) {
            const res = this.pkceCode ? { ...this.pkceCode } : undefined;
            this.pkceCode = undefined;
            if (res) {
                this.logger.verbose("12js1o", correlationId);
            }
            else {
                this.logger.verbose("1oe9ci", correlationId);
            }
            this.performanceClient.addFields({ usePreGeneratedPkce: !!res }, correlationId);
            return res;
        }
        logMultipleInstances(performanceEvent, correlationId) {
            const clientId = this.config.auth.clientId;
            if (!window)
                return;
            // @ts-ignore
            window.msal = window.msal || {};
            // @ts-ignore
            window.msal.clientIds = window.msal.clientIds || [];
            // @ts-ignore
            const clientIds = window.msal.clientIds;
            if (clientIds.length > 0) {
                this.logger.verbose("1qtz3l", correlationId);
            }
            // @ts-ignore
            window.msal.clientIds.push(clientId);
            collectInstanceStats(clientId, performanceEvent, this.logger, correlationId);
        }
    }
    /**
     * Determines whether an error thrown by the refresh token endpoint can be resolved without interaction
     * @param refreshTokenError
     * @param silentRequest
     * @param cacheLookupPolicy
     * @returns
     */
    function checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy) {
        const noInteractionRequired = !(refreshTokenError instanceof InteractionRequiredAuthError &&
            // For refresh token errors, bad_token does not always require interaction (silently resolvable)
            refreshTokenError.subError !==
                badToken);
        // Errors that result when the refresh token needs to be replaced
        const refreshTokenRefreshRequired = refreshTokenError.errorCode === BrowserConstants.INVALID_GRANT_ERROR ||
            refreshTokenError.errorCode ===
                tokenRefreshRequired;
        // Errors that may be resolved before falling back to interaction (through iframe renewal)
        const isSilentlyResolvable = (noInteractionRequired && refreshTokenRefreshRequired) ||
            refreshTokenError.errorCode ===
                noTokensFound ||
            refreshTokenError.errorCode ===
                refreshTokenExpired;
        // Only these policies allow for an iframe renewal attempt
        const tryIframeRenewal = iFrameRenewalPolicies.includes(cacheLookupPolicy);
        return isSilentlyResolvable && tryIframeRenewal;
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Base class for operating context
     * Operating contexts are contexts in which MSAL.js is being run
     * More than one operating context may be available at a time
     * It's important from a logging and telemetry point of view for us to be able to identify the operating context.
     * For example: Some operating contexts will pre-cache tokens impacting performance telemetry
     */
    class BaseOperatingContext {
        static loggerCallback(level, message) {
            switch (level) {
                case exports.LogLevel.Error:
                    // eslint-disable-next-line no-console
                    console.error(message);
                    return;
                case exports.LogLevel.Info:
                    // eslint-disable-next-line no-console
                    console.info(message);
                    return;
                case exports.LogLevel.Verbose:
                    // eslint-disable-next-line no-console
                    console.debug(message);
                    return;
                case exports.LogLevel.Warning:
                    // eslint-disable-next-line no-console
                    console.warn(message);
                    return;
                default:
                    // eslint-disable-next-line no-console
                    console.log(message);
                    return;
            }
        }
        constructor(config) {
            /*
             * If loaded in an environment where window is not available,
             * set internal flag to false so that further requests fail.
             * This is to support server-side rendering environments.
             */
            this.browserEnvironment = typeof window !== "undefined";
            this.config = buildConfiguration(config, this.browserEnvironment);
            let sessionStorage;
            try {
                sessionStorage = window[BrowserCacheLocation.SessionStorage];
                // Mute errors if it's a non-browser environment or cookies are blocked.
            }
            catch (e) { }
            const logLevelKey = sessionStorage?.getItem(LOG_LEVEL_CACHE_KEY);
            const piiLoggingKey = sessionStorage
                ?.getItem(LOG_PII_CACHE_KEY)
                ?.toLowerCase();
            const piiLoggingEnabled = piiLoggingKey === "true"
                ? true
                : piiLoggingKey === "false"
                    ? false
                    : undefined;
            const loggerOptions = { ...this.config.system.loggerOptions };
            const logLevel = logLevelKey && Object.keys(exports.LogLevel).includes(logLevelKey)
                ? exports.LogLevel[logLevelKey]
                : undefined;
            if (logLevel) {
                loggerOptions.loggerCallback = BaseOperatingContext.loggerCallback;
                loggerOptions.logLevel = logLevel;
            }
            if (piiLoggingEnabled !== undefined) {
                loggerOptions.piiLoggingEnabled = piiLoggingEnabled;
            }
            this.logger = new Logger(loggerOptions, name, version);
            this.available = false;
        }
        /**
         * Return the MSAL config
         * @returns BrowserConfiguration
         */
        getConfig() {
            return this.config;
        }
        /**
         * Returns the MSAL Logger
         * @returns Logger
         */
        getLogger() {
            return this.logger;
        }
        isAvailable() {
            return this.available;
        }
        isBrowserEnvironment() {
            return this.browserEnvironment;
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class StandardOperatingContext extends BaseOperatingContext {
        /**
         * Return the module name.  Intended for use with import() to enable dynamic import
         * of the implementation associated with this operating context
         * @returns
         */
        getModuleName() {
            return StandardOperatingContext.MODULE_NAME;
        }
        /**
         * Returns the unique identifier for this operating context
         * @returns string
         */
        getId() {
            return StandardOperatingContext.ID;
        }
        /**
         * Checks whether the operating context is available.
         * Confirms that the code is running a browser rather.  This is required.
         * @returns Promise<boolean> indicating whether this operating context is currently available.
         */
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        async initialize(correlationId) {
            this.available = typeof window !== "undefined";
            return this.available;
            /*
             * NOTE: The standard context is available as long as there is a window.  If/when we split out WAM from Browser
             * We can move the current contents of the initialize method to here and verify that the WAM extension is available
             */
        }
    }
    /*
     * TODO: Once we have determine the bundling code return here to specify the name of the bundle
     * containing the implementation for this operating context
     */
    StandardOperatingContext.MODULE_NAME = "";
    /**
     * Unique identifier for the operating context
     */
    StandardOperatingContext.ID = "StandardOperatingContext";
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    function isBridgeError(error) {
        return error.status !== undefined;
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const BridgeStatusCode = {
        UserInteractionRequired: "USER_INTERACTION_REQUIRED",
        UserCancel: "USER_CANCEL",
        NoNetwork: "NO_NETWORK",
        TransientError: "TRANSIENT_ERROR",
        PersistentError: "PERSISTENT_ERROR",
        Disabled: "DISABLED",
        AccountUnavailable: "ACCOUNT_UNAVAILABLE",
        NestedAppAuthUnavailable: "NESTED_APP_AUTH_UNAVAILABLE", // NAA is unavailable in the current context, can retry with standard browser based auth
    };
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class NestedAppAuthAdapter {
        constructor(clientId, clientCapabilities, crypto, logger) {
            this.clientId = clientId;
            this.clientCapabilities = clientCapabilities;
            this.crypto = crypto;
            this.logger = logger;
        }
        toNaaTokenRequest(request) {
            let extraParams;
            if (request.extraQueryParameters === undefined) {
                extraParams = new Map();
            }
            else {
                extraParams = new Map(Object.entries(request.extraQueryParameters));
            }
            const correlationId = request.correlationId || this.crypto.createNewGuid();
            const claims = addClientCapabilitiesToClaims$1(request.claims, this.clientCapabilities);
            const scopes = request.scopes || OIDC_DEFAULT_SCOPES$1;
            const tokenRequest = {
                platformBrokerId: request.account?.homeAccountId,
                clientId: this.clientId,
                authority: request.authority,
                resource: request.resource,
                scope: scopes.join(" "),
                correlationId,
                claims: !StringUtils.isEmptyObj(claims) ? claims : undefined,
                state: request.state,
                authenticationScheme: request.authenticationScheme ||
                    AuthenticationScheme$1.BEARER,
                extraParameters: extraParams,
            };
            return tokenRequest;
        }
        fromNaaTokenResponse(request, response, reqTimestamp) {
            if (!response.token.id_token || !response.token.access_token) {
                throw createClientAuthError(nullOrEmptyToken);
            }
            // Request timestamp and AuthResult expires_in are in seconds, converting to Date for AuthenticationResult
            const expiresOn = toDateFromSeconds(reqTimestamp + (response.token.expires_in || 0));
            const idTokenClaims = extractTokenClaims(response.token.id_token, this.crypto.base64Decode);
            const account = this.fromNaaAccountInfo(response.account, response.token.id_token, idTokenClaims);
            const scopes = response.token.scope || request.scope;
            const authenticationResult = {
                authority: response.token.authority || account.environment,
                uniqueId: account.localAccountId,
                tenantId: account.tenantId,
                scopes: scopes.split(" "),
                account,
                idToken: response.token.id_token,
                idTokenClaims,
                accessToken: response.token.access_token,
                fromCache: false,
                expiresOn: expiresOn,
                tokenType: request.authenticationScheme ||
                    AuthenticationScheme$1.BEARER,
                correlationId: request.correlationId,
                extExpiresOn: expiresOn,
                state: request.state,
            };
            return authenticationResult;
        }
        /*
         *  export type AccountInfo = {
         *     homeAccountId: string;
         *     environment: string;
         *     tenantId: string;
         *     username: string;
         *     localAccountId: string;
         *     name?: string;
         *     idToken?: string;
         *     idTokenClaims?: TokenClaims & {
         *         [key: string]:
         *             | string
         *             | number
         *             | string[]
         *             | object
         *             | undefined
         *             | unknown;
         *     };
         *     nativeAccountId?: string;
         *     authorityType?: string;
         * };
         */
        fromNaaAccountInfo(fromAccount, idToken, idTokenClaims) {
            const effectiveIdTokenClaims = idTokenClaims || fromAccount.idTokenClaims;
            const localAccountId = fromAccount.localAccountId ||
                effectiveIdTokenClaims?.oid ||
                effectiveIdTokenClaims?.sub ||
                "";
            /*
             * In B2C scenarios tid may not be present, use getTenantIdFromIdTokenClaims
             * which handles tid, tfp (modern B2C), and acr (legacy B2C) claims
             */
            const tenantId = fromAccount.tenantId ||
                getTenantIdFromIdTokenClaims(effectiveIdTokenClaims) ||
                "";
            const homeAccountId = fromAccount.homeAccountId || `${localAccountId}.${tenantId}`;
            // Validate environment - required field
            const environment = fromAccount.environment;
            if (!environment) {
                throw createClientAuthError(invalidCacheEnvironment);
            }
            /*
             * In B2C scenarios the emails claim is used instead of preferred_username and it is an array.
             * In most cases it will contain a single email. This field should not be relied upon if a custom
             * policy is configured to return more than 1 email.
             */
            const preferredUsername = effectiveIdTokenClaims?.preferred_username ||
                effectiveIdTokenClaims?.upn;
            const email = effectiveIdTokenClaims?.emails?.[0] || null;
            const username = fromAccount.username || preferredUsername || email || "";
            const name = fromAccount.name || effectiveIdTokenClaims?.name || "";
            const loginHint = fromAccount.loginHint || effectiveIdTokenClaims?.login_hint;
            const tenantProfiles = new Map();
            const tenantProfile = buildTenantProfile(homeAccountId, localAccountId, tenantId, effectiveIdTokenClaims);
            tenantProfiles.set(tenantId, tenantProfile);
            const account = {
                homeAccountId,
                environment,
                tenantId,
                username,
                localAccountId,
                name,
                loginHint,
                idToken: idToken,
                idTokenClaims: effectiveIdTokenClaims,
                tenantProfiles,
            };
            return account;
        }
        /**
         *
         * @param error BridgeError
         * @returns AuthError, ClientAuthError, ClientConfigurationError, ServerError, InteractionRequiredError
         */
        fromBridgeError(error) {
            if (isBridgeError(error)) {
                switch (error.status) {
                    case BridgeStatusCode.UserCancel:
                        return new ClientAuthError(userCanceled);
                    case BridgeStatusCode.NoNetwork:
                        return new ClientAuthError(noNetworkConnectivity$1);
                    case BridgeStatusCode.AccountUnavailable:
                        return new ClientAuthError(noAccountFound);
                    case BridgeStatusCode.Disabled:
                        return new ClientAuthError(nestedAppAuthBridgeDisabled);
                    case BridgeStatusCode.NestedAppAuthUnavailable:
                        return new ClientAuthError(error.code ||
                            nestedAppAuthBridgeDisabled, error.description);
                    case BridgeStatusCode.TransientError:
                    case BridgeStatusCode.PersistentError:
                        return new ServerError(error.code, error.description);
                    case BridgeStatusCode.UserInteractionRequired:
                        return new InteractionRequiredAuthError(error.code, error.description);
                    default:
                        return new AuthError(error.code, error.description);
                }
            }
            else {
                return new AuthError("unknown_error", "An unknown error occurred");
            }
        }
        /**
         * Returns an AuthenticationResult from the given cache items
         *
         * @param account
         * @param idToken
         * @param accessToken
         * @param reqTimestamp
         * @returns
         */
        toAuthenticationResultFromCache(account, idToken, accessToken, request, correlationId) {
            if (!idToken || !accessToken) {
                throw createClientAuthError(nullOrEmptyToken);
            }
            const idTokenClaims = extractTokenClaims(idToken.secret, this.crypto.base64Decode);
            const scopes = accessToken.target || request.scopes.join(" ");
            const authenticationResult = {
                authority: accessToken.environment || account.environment,
                uniqueId: account.localAccountId,
                tenantId: account.tenantId,
                scopes: scopes.split(" "),
                account,
                idToken: idToken.secret,
                idTokenClaims: idTokenClaims || {},
                accessToken: accessToken.secret,
                fromCache: true,
                expiresOn: toDateFromSeconds(accessToken.expiresOn),
                extExpiresOn: toDateFromSeconds(accessToken.extendedExpiresOn),
                tokenType: request.authenticationScheme ||
                    AuthenticationScheme$1.BEARER,
                correlationId,
                state: request.state,
            };
            return authenticationResult;
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class NestedAppAuthError extends AuthError {
        constructor(errorCode, errorMessage) {
            super(errorCode, errorMessage);
            Object.setPrototypeOf(this, NestedAppAuthError.prototype);
            this.name = "NestedAppAuthError";
        }
        static createUnsupportedError() {
            return new NestedAppAuthError(unsupportedMethod);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class NestedAppAuthController {
        constructor(operatingContext) {
            this.operatingContext = operatingContext;
            const proxy = this.operatingContext.getBridgeProxy();
            if (proxy !== undefined) {
                this.bridgeProxy = proxy;
            }
            else {
                throw new Error("unexpected: bridgeProxy is undefined");
            }
            // Set the configuration.
            this.config = operatingContext.getConfig();
            // Initialize logger
            this.logger = this.operatingContext.getLogger();
            // Initialize performance client
            this.performanceClient = this.config.telemetry.client;
            // Initialize the crypto class.
            this.browserCrypto = operatingContext.isBrowserEnvironment()
                ? new CryptoOps(this.logger, this.performanceClient, true)
                : DEFAULT_CRYPTO_IMPLEMENTATION;
            this.eventHandler = new EventHandler(this.logger);
            // Initialize the browser storage class.
            this.browserStorage = this.operatingContext.isBrowserEnvironment()
                ? new BrowserCacheManager(this.config.auth.clientId, this.config.cache, this.browserCrypto, this.logger, this.performanceClient, this.eventHandler, buildStaticAuthorityOptions(this.config.auth))
                : DEFAULT_BROWSER_CACHE_MANAGER(this.config.auth.clientId, this.logger, this.performanceClient, this.eventHandler);
            this.nestedAppAuthAdapter = new NestedAppAuthAdapter(this.config.auth.clientId, this.config.auth.clientCapabilities, this.browserCrypto, this.logger);
            // Set the active account if available
            const accountContext = this.bridgeProxy.getAccountContext();
            this.currentAccountContext = accountContext ? accountContext : null;
        }
        /**
         * Factory function to create a new instance of NestedAppAuthController
         * @param operatingContext
         * @returns Promise<IController>
         */
        static async createController(operatingContext) {
            const controller = new NestedAppAuthController(operatingContext);
            return Promise.resolve(controller);
        }
        /**
         * Specific implementation of initialize function for NestedAppAuthController
         * @returns
         */
        async initialize(request, 
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        isBroker) {
            const initCorrelationId = request?.correlationId || createNewGuid();
            await this.browserStorage.initialize(initCorrelationId);
            return Promise.resolve();
        }
        /**
         * Validate the incoming request and add correlationId if not present
         * @param request
         * @returns
         */
        ensureValidRequest(request) {
            if (request?.correlationId) {
                return request;
            }
            return {
                ...request,
                correlationId: this.browserCrypto.createNewGuid(),
            };
        }
        /**
         * Internal implementation of acquireTokenInteractive flow
         * @param request
         * @returns
         */
        async acquireTokenInteractive(request) {
            const validRequest = this.ensureValidRequest(request);
            const correlationId = validRequest.correlationId || createNewGuid();
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, exports.InteractionType.Popup, validRequest);
            const atPopupMeasurement = this.performanceClient.startMeasurement(AcquireTokenPopup, correlationId);
            atPopupMeasurement.add({ nestedAppAuthRequest: true });
            try {
                enforceResourceParameter(this.config.auth.isMcp, validRequest);
                const naaRequest = this.nestedAppAuthAdapter.toNaaTokenRequest(validRequest);
                const reqTimestamp = nowSeconds();
                const response = await this.bridgeProxy.getTokenInteractive(naaRequest);
                const result = {
                    ...this.nestedAppAuthAdapter.fromNaaTokenResponse(naaRequest, response, reqTimestamp),
                };
                // cache the tokens in the response
                try {
                    // cache hydration can fail in JS Runtime scenario that doesn't support full crypto API
                    await this.hydrateCache(result, request);
                }
                catch (error) {
                    this.logger.warningPii("1mwr91", correlationId);
                }
                // cache the account context in memory after successful token fetch
                this.currentAccountContext = {
                    homeAccountId: result.account.homeAccountId,
                    environment: result.account.environment,
                    tenantId: result.account.tenantId,
                };
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, exports.InteractionType.Popup, result);
                atPopupMeasurement.add({
                    accessTokenSize: result.accessToken.length,
                    idTokenSize: result.idToken.length,
                });
                atPopupMeasurement.end({
                    success: true,
                    requestId: result.requestId,
                }, undefined, result.account);
                return result;
            }
            catch (e) {
                const error = e instanceof AuthError
                    ? e
                    : this.nestedAppAuthAdapter.fromBridgeError(e);
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, exports.InteractionType.Popup, null, e);
                atPopupMeasurement.end({
                    success: false,
                }, e, request.account);
                throw error;
            }
        }
        /**
         * Internal implementation of acquireTokenSilent flow
         * @param request
         * @returns
         */
        async acquireTokenSilentInternal(request) {
            const validRequest = this.ensureValidRequest(request);
            const correlationId = validRequest.correlationId || createNewGuid();
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, exports.InteractionType.Silent, validRequest);
            // Look for tokens in the cache first
            const result = await this.acquireTokenFromCache(validRequest);
            if (result) {
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, exports.InteractionType.Silent, result);
                return result;
            }
            // proceed with acquiring tokens via the host
            const ssoSilentMeasurement = this.performanceClient.startMeasurement(SsoSilent, correlationId);
            ssoSilentMeasurement.increment({
                visibilityChangeCount: 0,
            });
            ssoSilentMeasurement.add({
                nestedAppAuthRequest: true,
            });
            try {
                enforceResourceParameter(this.config.auth.isMcp, validRequest);
                const naaRequest = this.nestedAppAuthAdapter.toNaaTokenRequest(validRequest);
                naaRequest.forceRefresh = validRequest.forceRefresh;
                const reqTimestamp = nowSeconds();
                const response = await this.bridgeProxy.getTokenSilent(naaRequest);
                const result = this.nestedAppAuthAdapter.fromNaaTokenResponse(naaRequest, response, reqTimestamp);
                // cache the tokens in the response
                try {
                    // cache hydration can fail in JS Runtime scenario that doesn't support full crypto API
                    await this.hydrateCache(result, request);
                }
                catch (error) {
                    this.logger.warningPii("1mwr91", correlationId);
                }
                // cache the account context in memory after successful token fetch
                this.currentAccountContext = {
                    homeAccountId: result.account.homeAccountId,
                    environment: result.account.environment,
                    tenantId: result.account.tenantId,
                };
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, exports.InteractionType.Silent, result);
                ssoSilentMeasurement?.add({
                    accessTokenSize: result.accessToken.length,
                    idTokenSize: result.idToken.length,
                });
                ssoSilentMeasurement?.end({
                    success: true,
                    requestId: result.requestId,
                }, undefined, result.account);
                return result;
            }
            catch (e) {
                const error = e instanceof AuthError
                    ? e
                    : this.nestedAppAuthAdapter.fromBridgeError(e);
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, exports.InteractionType.Silent, null, e);
                ssoSilentMeasurement?.end({
                    success: false,
                }, e, request.account);
                throw error;
            }
        }
        /**
         * acquires tokens from cache
         * @param request
         * @returns
         */
        async acquireTokenFromCache(request) {
            const correlationId = request.correlationId || createNewGuid();
            const atsMeasurement = this.performanceClient.startMeasurement(AcquireTokenSilent, correlationId);
            atsMeasurement?.add({
                nestedAppAuthRequest: true,
            });
            // if the request has claims, we cannot look up in the cache
            if (request.claims) {
                this.logger.verbose("11t57w", correlationId);
                return null;
            }
            // if the request has forceRefresh, we cannot look up in the cache
            if (request.forceRefresh) {
                this.logger.verbose("1ovnmo", correlationId);
                return null;
            }
            // respect cache lookup policy
            let result = null;
            if (!request.cacheLookupPolicy) {
                request.cacheLookupPolicy = CacheLookupPolicy.Default;
            }
            switch (request.cacheLookupPolicy) {
                case CacheLookupPolicy.Default:
                case CacheLookupPolicy.AccessToken:
                case CacheLookupPolicy.AccessTokenAndRefreshToken:
                    result = await this.acquireTokenFromCacheInternal(request);
                    break;
                default:
                    return null;
            }
            if (result) {
                this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, exports.InteractionType.Silent, result);
                atsMeasurement.add({
                    accessTokenSize: result.accessToken.length,
                    idTokenSize: result.idToken.length,
                });
                atsMeasurement.end({
                    success: true,
                }, undefined, result.account);
                return result;
            }
            this.logger.warning("1yb4fi", correlationId);
            this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, exports.InteractionType.Silent, null);
            atsMeasurement.end({
                success: false,
            }, undefined, request.account);
            return null;
        }
        /**
         *
         * @param request
         * @returns
         */
        async acquireTokenFromCacheInternal(request) {
            // always prioritize the account context from the bridge
            const accountContext = this.bridgeProxy.getAccountContext() || this.currentAccountContext;
            const correlationId = request.correlationId || createNewGuid();
            let currentAccount = null;
            if (accountContext) {
                currentAccount = getAccount(accountContext, this.logger, this.browserStorage, correlationId);
            }
            // fall back to brokering if no cached account is found
            if (!currentAccount) {
                this.logger.verbose("10qnr0", correlationId);
                return Promise.resolve(null);
            }
            this.logger.verbose("1u7hux", correlationId);
            const authRequest = {
                ...request,
                correlationId: correlationId,
                authority: request.authority || currentAccount.environment,
                scopes: request.scopes?.length
                    ? request.scopes
                    : [...OIDC_DEFAULT_SCOPES$1],
            };
            // fetch access token and check for expiry
            const tokenKeys = this.browserStorage.getTokenKeys();
            const cachedAccessToken = this.browserStorage.getAccessToken(currentAccount, authRequest, tokenKeys, currentAccount.tenantId);
            // If there is no access token, log it and return null
            if (!cachedAccessToken) {
                this.logger.verbose("03vm49", correlationId);
                return Promise.resolve(null);
            }
            else if (wasClockTurnedBack(cachedAccessToken.cachedAt) ||
                isTokenExpired(cachedAccessToken.expiresOn, this.config.system.tokenRenewalOffsetSeconds)) {
                this.logger.verbose("18egye", correlationId);
                return Promise.resolve(null);
            }
            else if (authRequest.resource) {
                const requestedResource = authRequest.resource;
                const cachedResource = cachedAccessToken.resource;
                if (!cachedResource || cachedResource !== requestedResource) {
                    this.logger.verbose("0qraxd", correlationId);
                    return Promise.resolve(null);
                }
            }
            const cachedIdToken = this.browserStorage.getIdToken(currentAccount, authRequest.correlationId, tokenKeys, currentAccount.tenantId);
            if (!cachedIdToken) {
                this.logger.verbose("0d68kd", correlationId);
                return Promise.resolve(null);
            }
            return this.nestedAppAuthAdapter.toAuthenticationResultFromCache(currentAccount, cachedIdToken, cachedAccessToken, authRequest, authRequest.correlationId);
        }
        /**
         * acquireTokenPopup flow implementation
         * @param request
         * @returns
         */
        async acquireTokenPopup(request) {
            return this.acquireTokenInteractive(request);
        }
        /**
         * acquireTokenRedirect flow is not supported in nested app auth
         * @param request
         */
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        acquireTokenRedirect(request) {
            throw NestedAppAuthError.createUnsupportedError();
        }
        /**
         * acquireTokenSilent flow implementation
         * @param silentRequest
         * @returns
         */
        async acquireTokenSilent(silentRequest) {
            return this.acquireTokenSilentInternal(silentRequest);
        }
        /**
         * Hybrid flow is not currently supported in nested app auth
         * @param request
         */
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        acquireTokenByCode(request // eslint-disable-line @typescript-eslint/no-unused-vars
        ) {
            throw NestedAppAuthError.createUnsupportedError();
        }
        /**
         * Adds event callbacks to array
         * @param callback
         * @param eventTypes
         */
        addEventCallback(callback, eventTypes) {
            return this.eventHandler.addEventCallback(callback, eventTypes);
        }
        /**
         * Removes callback with provided id from callback array
         * @param callbackId
         */
        removeEventCallback(callbackId) {
            this.eventHandler.removeEventCallback(callbackId);
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        addPerformanceCallback(callback) {
            throw NestedAppAuthError.createUnsupportedError();
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        removePerformanceCallback(callbackId) {
            throw NestedAppAuthError.createUnsupportedError();
        }
        // #region Account APIs
        /**
         * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
         * @param accountFilter - (Optional) filter to narrow down the accounts returned
         * @returns Array of AccountInfo objects in cache
         */
        getAllAccounts(accountFilter) {
            return getAllAccounts(this.logger, this.browserStorage, this.isBrowserEnv(), createNewGuid(), accountFilter);
        }
        /**
         * Returns the first account found in the cache that matches the account filter passed in.
         * @param accountFilter
         * @returns The first account found in the cache matching the provided filter or null if no account could be found.
         */
        getAccount(accountFilter) {
            return getAccount(accountFilter, this.logger, this.browserStorage, createNewGuid());
        }
        /**
         * Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
         * @param account
         */
        setActiveAccount(account) {
            /*
             * StandardController uses this to allow the developer to set the active account
             * in the nested app auth scenario the active account is controlled by the app hosting the nested app
             */
            return setActiveAccount(account, this.browserStorage, createNewGuid());
        }
        /**
         * Gets the currently active account
         */
        getActiveAccount() {
            return getActiveAccount(this.browserStorage, createNewGuid());
        }
        // #endregion
        handleRedirectPromise(options // eslint-disable-line @typescript-eslint/no-unused-vars
        ) {
            return Promise.resolve(null);
        }
        loginPopup(request // eslint-disable-line @typescript-eslint/no-unused-vars
        ) {
            return this.acquireTokenInteractive(request || DEFAULT_REQUEST);
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        loginRedirect(request) {
            throw NestedAppAuthError.createUnsupportedError();
        }
        logoutRedirect(logoutRequest // eslint-disable-line @typescript-eslint/no-unused-vars
        ) {
            throw NestedAppAuthError.createUnsupportedError();
        }
        logoutPopup(logoutRequest // eslint-disable-line @typescript-eslint/no-unused-vars
        ) {
            throw NestedAppAuthError.createUnsupportedError();
        }
        ssoSilent(
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        request) {
            return this.acquireTokenSilentInternal(request);
        }
        /**
         * Returns the logger instance
         */
        getLogger() {
            return this.logger;
        }
        /**
         * Replaces the default logger set in configurations with new Logger with new configurations
         * @param logger Logger instance
         */
        setLogger(logger) {
            this.logger = logger;
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        initializeWrapperLibrary(sku, version) {
            /*
             * Standard controller uses this to set the sku and version of the wrapper library in the storage
             * we do nothing here
             */
            return;
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        setNavigationClient(navigationClient) {
            this.logger.warning("1k8729", "");
        }
        getConfiguration() {
            return this.config;
        }
        isBrowserEnv() {
            return this.operatingContext.isBrowserEnvironment();
        }
        getBrowserCrypto() {
            return this.browserCrypto;
        }
        getPerformanceClient() {
            throw NestedAppAuthError.createUnsupportedError();
        }
        getRedirectResponse() {
            throw NestedAppAuthError.createUnsupportedError();
        }
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        async clearCache(logoutRequest) {
            throw NestedAppAuthError.createUnsupportedError();
        }
        async hydrateCache(result, request) {
            this.logger.verbose("16jycr", result.correlationId);
            const accountEntity = createAccountEntityFromAccountInfo(result.account, result.cloudGraphHostName, result.msGraphHost);
            await this.browserStorage.setAccount(accountEntity, result.correlationId, isKmsi(result.idTokenClaims), ApiId.hydrateCache);
            return this.browserStorage.hydrateCache(result, request);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * BridgeProxy
     * Provides a proxy for accessing a bridge to a host app and/or
     * platform broker
     */
    class BridgeProxy {
        /**
         * initializeNestedAppAuthBridge - Initializes the bridge to the host app
         * @returns a promise that resolves to an InitializeBridgeResponse or rejects with an Error
         * @remarks This method will be called by the create factory method
         * @remarks If the bridge is not available, this method will throw an error
         */
        static async initializeNestedAppAuthBridge() {
            if (window === undefined) {
                throw new Error("window is undefined");
            }
            if (window.nestedAppAuthBridge === undefined) {
                throw new Error("window.nestedAppAuthBridge is undefined");
            }
            try {
                window.nestedAppAuthBridge.addEventListener("message", (response) => {
                    const responsePayload = typeof response === "string" ? response : response.data;
                    const responseEnvelope = JSON.parse(responsePayload);
                    const request = BridgeProxy.bridgeRequests.find((element) => element.requestId === responseEnvelope.requestId);
                    if (request !== undefined) {
                        BridgeProxy.bridgeRequests.splice(BridgeProxy.bridgeRequests.indexOf(request), 1);
                        if (responseEnvelope.success) {
                            request.resolve(responseEnvelope);
                        }
                        else {
                            request.reject(responseEnvelope.error);
                        }
                    }
                });
                const bridgeResponse = await new Promise((resolve, reject) => {
                    const message = BridgeProxy.buildRequest("GetInitContext");
                    const request = {
                        requestId: message.requestId,
                        method: message.method,
                        resolve: resolve,
                        reject: reject,
                    };
                    BridgeProxy.bridgeRequests.push(request);
                    window.nestedAppAuthBridge.postMessage(JSON.stringify(message));
                });
                return BridgeProxy.validateBridgeResultOrThrow(bridgeResponse.initContext);
            }
            catch (error) {
                window.console.log(error);
                throw error;
            }
        }
        /**
         * getTokenInteractive - Attempts to get a token interactively from the bridge
         * @param request A token request
         * @returns a promise that resolves to an auth result or rejects with a BridgeError
         */
        getTokenInteractive(request) {
            return this.getToken("GetTokenPopup", request);
        }
        /**
         * getTokenSilent Attempts to get a token silently from the bridge
         * @param request A token request
         * @returns a promise that resolves to an auth result or rejects with a BridgeError
         */
        getTokenSilent(request) {
            return this.getToken("GetToken", request);
        }
        async getToken(requestType, request) {
            const result = await this.sendRequest(requestType, {
                tokenParams: request,
            });
            return {
                token: BridgeProxy.validateBridgeResultOrThrow(result.token),
                account: BridgeProxy.validateBridgeResultOrThrow(result.account),
            };
        }
        getHostCapabilities() {
            return this.capabilities ?? null;
        }
        getAccountContext() {
            return this.accountContext ? this.accountContext : null;
        }
        static buildRequest(method, requestParams) {
            return {
                messageType: "NestedAppAuthRequest",
                method: method,
                requestId: createNewGuid(),
                sendTime: Date.now(),
                clientLibrary: BrowserConstants.MSAL_SKU,
                clientLibraryVersion: version,
                ...requestParams,
            };
        }
        /**
         * A method used to send a request to the bridge
         * @param request A token request
         * @returns a promise that resolves to a response of provided type or rejects with a BridgeError
         */
        sendRequest(method, requestParams) {
            const message = BridgeProxy.buildRequest(method, requestParams);
            const promise = new Promise((resolve, reject) => {
                const request = {
                    requestId: message.requestId,
                    method: message.method,
                    resolve: resolve,
                    reject: reject,
                };
                BridgeProxy.bridgeRequests.push(request);
                window.nestedAppAuthBridge.postMessage(JSON.stringify(message));
            });
            return promise;
        }
        static validateBridgeResultOrThrow(input) {
            if (input === undefined) {
                const bridgeError = {
                    status: BridgeStatusCode.NestedAppAuthUnavailable,
                };
                throw bridgeError;
            }
            return input;
        }
        /**
         * Private constructor for BridgeProxy
         * @param sdkName The name of the SDK being used to make requests on behalf of the app
         * @param sdkVersion The version of the SDK being used to make requests on behalf of the app
         * @param capabilities The capabilities of the bridge / SDK / platform broker
         */
        constructor(sdkName, sdkVersion, accountContext, capabilities) {
            this.sdkName = sdkName;
            this.sdkVersion = sdkVersion;
            this.accountContext = accountContext;
            this.capabilities = capabilities;
        }
        /**
         * Factory method for creating an implementation of IBridgeProxy
         * @returns A promise that resolves to a BridgeProxy implementation
         */
        static async create() {
            const response = await BridgeProxy.initializeNestedAppAuthBridge();
            return new BridgeProxy(response.sdkName, response.sdkVersion, response.accountContext, response.capabilities);
        }
    }
    BridgeProxy.bridgeRequests = [];
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class NestedAppOperatingContext extends BaseOperatingContext {
        constructor() {
            super(...arguments);
            this.bridgeProxy = undefined;
            this.accountContext = null;
        }
        /**
         * Return the module name.  Intended for use with import() to enable dynamic import
         * of the implementation associated with this operating context
         * @returns
         */
        getModuleName() {
            return NestedAppOperatingContext.MODULE_NAME;
        }
        /**
         * Returns the unique identifier for this operating context
         * @returns string
         */
        getId() {
            return NestedAppOperatingContext.ID;
        }
        /**
         * Returns the current BridgeProxy
         * @returns IBridgeProxy | undefined
         */
        getBridgeProxy() {
            return this.bridgeProxy;
        }
        /**
         * Checks whether the operating context is available.
         * Confirms that the code is running a browser rather.  This is required.
         * @param correlationId
         * @returns Promise<boolean> indicating whether this operating context is currently available.
         */
        async initialize(correlationId) {
            const cid = correlationId || "";
            try {
                if (typeof window !== "undefined") {
                    if (typeof window.__initializeNestedAppAuth === "function") {
                        await window.__initializeNestedAppAuth();
                    }
                    const bridgeProxy = await BridgeProxy.create();
                    /*
                     * Because we want single sign on we expect the host app to provide the account context
                     * with a min set of params that can be used to identify the account
                     * this.account = nestedApp.getAccountByFilter(bridgeProxy.getAccountContext());
                     */
                    this.accountContext = bridgeProxy.getAccountContext();
                    this.bridgeProxy = bridgeProxy;
                    this.available = bridgeProxy !== undefined;
                }
            }
            catch (ex) {
                this.logger.infoPii("1mdxyj", cid);
            }
            this.logger.info("12jy9a", cid);
            return this.available;
        }
    }
    /*
     * TODO: Once we have determine the bundling code return here to specify the name of the bundle
     * containing the implementation for this operating context
     */
    NestedAppOperatingContext.MODULE_NAME = "";
    /**
     * Unique identifier for the operating context
     */
    NestedAppOperatingContext.ID = "NestedAppOperatingContext";
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * The PublicClientApplication class is the object exposed by the library to perform authentication and authorization functions in Single Page Applications
     * to obtain JWT tokens as described in the OAuth 2.0 Authorization Code Flow with PKCE specification.
     */
    class PublicClientApplication {
        /**
         * @constructor
         * Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
         *
         * Important attributes in the Configuration object for auth are:
         * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
         * - authority: the authority URL for your application.
         * - redirect_uri: the uri of your application registered in the portal.
         *
         * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
         * It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
         * If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
         * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
         * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
         * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
         *
         * In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
         * Full B2C functionality will be available in this library in future versions.
         *
         * @param configuration Object for the MSAL PublicClientApplication instance
         * @param IController Optional parameter to explictly set the controller. (Will be removed when we remove public constructor)
         */
        constructor(configuration, controller) {
            this.controller =
                controller ||
                    new StandardController(new StandardOperatingContext(configuration));
        }
        /**
         * Initializer function to perform async startup tasks such as connecting to WAM extension
         * @param request {?InitializeApplicationRequest}
         */
        async initialize(request) {
            return this.controller.initialize(request);
        }
        /**
         * Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
         *
         * @param request
         *
         * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
         */
        async acquireTokenPopup(request) {
            return this.controller.acquireTokenPopup(request);
        }
        /**
         * Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint. This function redirects
         * the page, so any code that follows this function will not execute.
         *
         * IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
         * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
         *
         * @param request
         */
        acquireTokenRedirect(request) {
            return this.controller.acquireTokenRedirect(request);
        }
        /**
         * Silently acquire an access token for a given set of scopes. Returns currently processing promise if parallel requests are made.
         *
         * @param {@link (SilentRequest:type)}
         * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthenticationResult} object
         */
        acquireTokenSilent(silentRequest) {
            return this.controller.acquireTokenSilent(silentRequest);
        }
        /**
         * This function redeems an authorization code (passed as code) from the eSTS token endpoint.
         * This authorization code should be acquired server-side using a confidential client to acquire a spa_code.
         * This API is not indended for normal authorization code acquisition and redemption.
         *
         * Redemption of this authorization code will not require PKCE, as it was acquired by a confidential client.
         *
         * @param request {@link AuthorizationCodeRequest}
         * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
         */
        acquireTokenByCode(request) {
            return this.controller.acquireTokenByCode(request);
        }
        /**
         * Adds event callbacks to array
         * @param callback
         * @param eventTypes
         */
        addEventCallback(callback, eventTypes) {
            return this.controller.addEventCallback(callback, eventTypes);
        }
        /**
         * Removes callback with provided id from callback array
         * @param callbackId
         */
        removeEventCallback(callbackId) {
            return this.controller.removeEventCallback(callbackId);
        }
        /**
         * Registers a callback to receive performance events.
         *
         * @param {PerformanceCallbackFunction} callback
         * @returns {string}
         */
        addPerformanceCallback(callback) {
            return this.controller.addPerformanceCallback(callback);
        }
        /**
         * Removes a callback registered with addPerformanceCallback.
         *
         * @param {string} callbackId
         * @returns {boolean}
         */
        removePerformanceCallback(callbackId) {
            return this.controller.removePerformanceCallback(callbackId);
        }
        /**
         * Returns the first account found in the cache that matches the account filter passed in.
         * @param accountFilter
         * @returns The first account found in the cache matching the provided filter or null if no account could be found.
         */
        getAccount(accountFilter) {
            return this.controller.getAccount(accountFilter);
        }
        /**
         * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
         * @param accountFilter - (Optional) filter to narrow down the accounts returned
         * @returns Array of AccountInfo objects in cache
         */
        getAllAccounts(accountFilter) {
            return this.controller.getAllAccounts(accountFilter);
        }
        /**
         * Event handler function which allows users to fire events after the PublicClientApplication object
         * has loaded during redirect flows. This should be invoked on all page loads involved in redirect
         * auth flows.
         * @param hash Hash to process. Defaults to the current value of window.location.hash. Only needs to be provided explicitly if the response to be handled is not contained in the current value.
         * @param options Object containing optional configuration for redirect promise handling.
         * @returns Token response or null. If the return value is null, then no auth redirect was detected.
         */
        handleRedirectPromise(options) {
            return this.controller.handleRedirectPromise(options);
        }
        /**
         * Use when initiating the login process via opening a popup window in the user's browser
         *
         * @param request
         *
         * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
         */
        loginPopup(request) {
            return this.controller.loginPopup(request);
        }
        /**
         * Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so
         * any code that follows this function will not execute.
         *
         * IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
         * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
         *
         * @param request
         */
        loginRedirect(request) {
            return this.controller.loginRedirect(request);
        }
        /**
         * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
         * Default behaviour is to redirect the user to `window.location.href`.
         * @param logoutRequest
         */
        logoutRedirect(logoutRequest) {
            return this.controller.logoutRedirect(logoutRequest);
        }
        /**
         * Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
         * @param logoutRequest
         */
        logoutPopup(logoutRequest) {
            return this.controller.logoutPopup(logoutRequest);
        }
        /**
         * This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
         * - Any browser using a form of Intelligent Tracking Prevention
         * - If there is not an established session with the service
         *
         * In these cases, the request must be done inside a popup or full frame redirect.
         *
         * For the cases where interaction is required, you cannot send a request with prompt=none.
         *
         * If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
         * you session on the server still exists.
         * @param request {@link SsoSilentRequest}
         *
         * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
         */
        ssoSilent(request) {
            return this.controller.ssoSilent(request);
        }
        /**
         * Returns the logger instance
         */
        getLogger() {
            return this.controller.getLogger();
        }
        /**
         * Replaces the default logger set in configurations with new Logger with new configurations
         * @param logger Logger instance
         */
        setLogger(logger) {
            this.controller.setLogger(logger);
        }
        /**
         * Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
         * @param account
         */
        setActiveAccount(account) {
            this.controller.setActiveAccount(account);
        }
        /**
         * Gets the currently active account
         */
        getActiveAccount() {
            return this.controller.getActiveAccount();
        }
        /**
         * Called by wrapper libraries (Angular & React) to set SKU and Version passed down to telemetry, logger, etc.
         * @param sku
         * @param version
         */
        initializeWrapperLibrary(sku, version) {
            return this.controller.initializeWrapperLibrary(sku, version);
        }
        /**
         * Sets navigation client
         * @param navigationClient
         */
        setNavigationClient(navigationClient) {
            this.controller.setNavigationClient(navigationClient);
        }
        /**
         * Returns the configuration object
         * @internal
         */
        getConfiguration() {
            return this.controller.getConfiguration();
        }
        /**
         * Hydrates cache with the tokens and account in the AuthenticationResult object
         * @param result
         * @param request - The request object that was used to obtain the AuthenticationResult
         * @returns
         */
        async hydrateCache(result, request) {
            return this.controller.hydrateCache(result, request);
        }
        /**
         * Clears tokens and account from the browser cache.
         * @param logoutRequest
         */
        clearCache(logoutRequest) {
            return this.controller.clearCache(logoutRequest);
        }
    }
    /**
     * creates NestedAppAuthController and passes it to the PublicClientApplication,
     * falls back to StandardController if NestedAppAuthController is not available
     *
     * @param configuration
     * @param correlationId
     * @param pcaFactory
     * @returns IPublicClientApplication
     *
     */
    async function createNestablePublicClientApplication(configuration, correlationId, pcaFactory) {
        const nestedAppAuth = new NestedAppOperatingContext(configuration);
        await nestedAppAuth.initialize(correlationId);
        if (nestedAppAuth.isAvailable()) {
            const cid = correlationId || createNewGuid();
            const controller = new NestedAppAuthController(nestedAppAuth);
            const nestablePCA = pcaFactory
                ? pcaFactory(configuration, controller)
                : new PublicClientApplication(configuration, controller);
            await nestablePCA.initialize({ correlationId: cid });
            return nestablePCA;
        }
        return createStandardPublicClientApplication(configuration);
    }
    /**
     * creates PublicClientApplication using StandardController
     *
     * @param configuration
     * @returns IPublicClientApplication
     *
     */
    async function createStandardPublicClientApplication(configuration) {
        const pca = new PublicClientApplication(configuration);
        await pca.initialize();
        return pca;
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    const stubbedPublicClientApplication = {
        initialize: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        acquireTokenPopup: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        acquireTokenRedirect: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        acquireTokenSilent: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        acquireTokenByCode: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        getAllAccounts: () => {
            return [];
        },
        getAccount: () => {
            return null;
        },
        handleRedirectPromise: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        loginPopup: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        loginRedirect: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        logoutRedirect: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        logoutPopup: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        ssoSilent: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        addEventCallback: () => {
            return null;
        },
        removeEventCallback: () => {
            return;
        },
        addPerformanceCallback: () => {
            return "";
        },
        removePerformanceCallback: () => {
            return false;
        },
        getLogger: () => {
            throw createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled);
        },
        setLogger: () => {
            return;
        },
        setActiveAccount: () => {
            return;
        },
        getActiveAccount: () => {
            return null;
        },
        initializeWrapperLibrary: () => {
            return;
        },
        setNavigationClient: () => {
            return;
        },
        getConfiguration: () => {
            throw createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled);
        },
        hydrateCache: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
        clearCache: () => {
            return Promise.reject(createBrowserConfigurationAuthError(stubbedPublicClientApplicationCalled));
        },
    };
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * API to load tokens to msal-browser cache.
     * @param config - Object to configure the MSAL app.
     * @param request - Silent request containing authority, scopes, and account.
     * @param response - External token response to load into the cache.
     * @param options - Options controlling how tokens are loaded into the cache.
     * @param performanceClient - Optional performance client used for telemetry measurements.
     * @returns `AuthenticationResult` for the response that was loaded.
     */
    async function loadExternalTokens(config, request, response, options, performanceClient = new StubPerformanceClient()) {
        blockNonBrowserEnvironment();
        const browserConfig = buildConfiguration(config, true);
        const correlationId = request.correlationId || createNewGuid();
        const rootMeasurement = performanceClient.startMeasurement(LoadExternalTokens, correlationId);
        try {
            const idTokenClaims = response.id_token
                ? extractTokenClaims(response.id_token, base64Decode)
                : undefined;
            const kmsi = isKmsi(idTokenClaims || {});
            const authorityOptions = {
                protocolMode: browserConfig.system.protocolMode,
                knownAuthorities: browserConfig.auth.knownAuthorities,
                cloudDiscoveryMetadata: browserConfig.auth.cloudDiscoveryMetadata,
                authorityMetadata: browserConfig.auth.authorityMetadata,
            };
            const logger = new Logger(browserConfig.system.loggerOptions || {});
            const cryptoOps = new CryptoOps(logger, browserConfig.telemetry.client);
            const storage = new BrowserCacheManager(browserConfig.auth.clientId, browserConfig.cache, cryptoOps, logger, browserConfig.telemetry.client, new EventHandler(logger), buildStaticAuthorityOptions(browserConfig.auth));
            const authorityString = request.authority || browserConfig.auth.authority;
            const authority = await createDiscoveredInstance(Authority.generateAuthority(authorityString, request.azureCloudOptions), browserConfig.system.networkClient, storage, authorityOptions, logger, correlationId, performanceClient);
            const cacheRecordAccount = await invokeAsync(loadAccount, LoadAccount, logger, performanceClient, correlationId)(request, options.clientInfo || response.client_info || "", correlationId, storage, logger, cryptoOps, authority, idTokenClaims, performanceClient);
            const idToken = await invokeAsync(loadIdToken, LoadIdToken, logger, performanceClient, correlationId)(response, cacheRecordAccount.homeAccountId, cacheRecordAccount.environment, cacheRecordAccount.realm, kmsi, correlationId, storage, logger, config.auth.clientId);
            const accessToken = await invokeAsync(loadAccessToken, LoadAccessToken, logger, performanceClient, correlationId)(request, response, cacheRecordAccount.homeAccountId, cacheRecordAccount.environment, cacheRecordAccount.realm, kmsi, options, correlationId, storage, logger, config.auth.clientId);
            const refreshToken = await invokeAsync(loadRefreshToken, LoadRefreshToken, logger, performanceClient, correlationId)(response, cacheRecordAccount.homeAccountId, cacheRecordAccount.environment, kmsi, correlationId, storage, logger, config.auth.clientId, performanceClient);
            rootMeasurement.end({ success: true }, undefined, getAccountInfo(cacheRecordAccount));
            return generateAuthenticationResult(request, {
                account: cacheRecordAccount,
                idToken,
                accessToken,
                refreshToken,
            }, authority, idTokenClaims);
        }
        catch (error) {
            rootMeasurement.end({ success: false }, error);
            throw error;
        }
    }
    /**
     * Helper function to load account to msal-browser cache
     * @param idToken
     * @param environment
     * @param clientInfo
     * @param authorityType
     * @param requestHomeAccountId
     * @returns `AccountEntity`
     */
    async function loadAccount(request, clientInfo, correlationId, storage, logger, cryptoObj, authority, idTokenClaims, performanceClient) {
        logger.verbose("0ke46k", correlationId);
        if (request.account) {
            const accountEntity = createAccountEntityFromAccountInfo(request.account);
            await storage.setAccount(accountEntity, correlationId, isKmsi(idTokenClaims || {}), ApiId.loadExternalTokens);
            return accountEntity;
        }
        else if (!clientInfo && !idTokenClaims) {
            logger.error("0hzcn4", correlationId);
            throw createBrowserAuthError(unableToLoadToken);
        }
        const homeAccountId = generateHomeAccountId(clientInfo, authority.authorityType, logger, cryptoObj, correlationId, idTokenClaims);
        const claimsTenantId = idTokenClaims?.tid;
        const cachedAccount = buildAccountToCache(storage, authority, homeAccountId, base64Decode, correlationId, idTokenClaims, clientInfo, authority.getPreferredCache(), claimsTenantId, undefined, // authCodePayload
        undefined, // nativeAccountId
        logger, performanceClient);
        await storage.setAccount(cachedAccount, correlationId, isKmsi(idTokenClaims || {}), ApiId.loadExternalTokens);
        return cachedAccount;
    }
    /**
     * Helper function to load id tokens to msal-browser cache
     * @param idToken
     * @param homeAccountId
     * @param environment
     * @param tenantId
     * @returns `IdTokenEntity`
     */
    async function loadIdToken(response, homeAccountId, environment, tenantId, kmsi, correlationId, storage, logger, clientId) {
        if (!response.id_token) {
            logger.verbose("1pm7g1", correlationId);
            return null;
        }
        logger.verbose("168lyi", correlationId);
        const idTokenEntity = createIdTokenEntity(homeAccountId, environment, response.id_token, clientId, tenantId);
        await storage.setIdTokenCredential(idTokenEntity, correlationId, kmsi);
        return idTokenEntity;
    }
    /**
     * Helper function to load access tokens to msal-browser cache
     * @param request
     * @param response
     * @param homeAccountId
     * @param environment
     * @param tenantId
     * @returns `AccessTokenEntity`
     */
    async function loadAccessToken(request, response, homeAccountId, environment, tenantId, kmsi, options, correlationId, storage, logger, clientId) {
        if (!response.access_token) {
            logger.verbose("1ckp9e", correlationId);
            return null;
        }
        else if (!response.expires_in) {
            logger.error("15mzx8", correlationId);
            return null;
        }
        else if (!response.scope && (!request.scopes || !request.scopes.length)) {
            logger.error("1h7xse", correlationId);
            return null;
        }
        logger.verbose("01kmxb", correlationId);
        const scopes = response.scope
            ? ScopeSet.fromString(response.scope)
            : new ScopeSet(request.scopes);
        const expiresOn = options.expiresOn || response.expires_in + nowSeconds();
        const extendedExpiresOn = options.extendedExpiresOn ||
            (response.ext_expires_in || response.expires_in) +
                nowSeconds();
        const accessTokenEntity = createAccessTokenEntity(homeAccountId, environment, response.access_token, clientId, tenantId, scopes.printScopes(), expiresOn, extendedExpiresOn, base64Decode);
        await storage.setAccessTokenCredential(accessTokenEntity, correlationId, kmsi);
        return accessTokenEntity;
    }
    /**
     * Helper function to load refresh tokens to msal-browser cache
     * @param request
     * @param response
     * @param homeAccountId
     * @param environment
     * @returns `RefreshTokenEntity`
     */
    async function loadRefreshToken(response, homeAccountId, environment, kmsi, correlationId, storage, logger, clientId, performanceClient) {
        if (!response.refresh_token) {
            logger.verbose("1l7um5", correlationId);
            return null;
        }
        const expiresOn = response.refresh_token_expires_in
            ? response.refresh_token_expires_in + nowSeconds()
            : undefined;
        performanceClient.addFields({
            extRtExpiresOnSeconds: expiresOn,
        }, correlationId);
        logger.verbose("0qy8ev", correlationId);
        const refreshTokenEntity = createRefreshTokenEntity(homeAccountId, environment, response.refresh_token, clientId, response.foci, undefined, // userAssertionHash
        expiresOn);
        await storage.setRefreshTokenCredential(refreshTokenEntity, correlationId, kmsi);
        return refreshTokenEntity;
    }
    /**
     * Helper function to generate an `AuthenticationResult` for the result.
     * @param request
     * @param idTokenObj
     * @param cacheRecord
     * @param authority
     * @returns `AuthenticationResult`
     */
    function generateAuthenticationResult(request, cacheRecord, authority, idTokenClaims) {
        let accessToken = "";
        let responseScopes = [];
        let expiresOn = null;
        let extExpiresOn;
        if (cacheRecord?.accessToken) {
            accessToken = cacheRecord.accessToken.secret;
            responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target).asArray();
            // Access token expiresOn stored in seconds, converting to Date for AuthenticationResult
            expiresOn = toDateFromSeconds(cacheRecord.accessToken.expiresOn);
            extExpiresOn = toDateFromSeconds(cacheRecord.accessToken.extendedExpiresOn);
        }
        const accountEntity = cacheRecord.account;
        return {
            authority: authority.canonicalAuthority,
            uniqueId: cacheRecord.account.localAccountId,
            tenantId: cacheRecord.account.realm,
            scopes: responseScopes,
            account: getAccountInfo(accountEntity),
            idToken: cacheRecord.idToken?.secret || "",
            idTokenClaims: idTokenClaims || {},
            accessToken: accessToken,
            fromCache: true,
            expiresOn: expiresOn,
            correlationId: request.correlationId || "",
            requestId: "",
            extExpiresOn: extExpiresOn,
            familyId: cacheRecord.refreshToken?.familyId || "",
            tokenType: cacheRecord?.accessToken?.tokenType || "",
            state: request.state || "",
            cloudGraphHostName: accountEntity.cloudGraphHostName || "",
            msGraphHost: accountEntity.msGraphHost || "",
            fromPlatformBroker: false,
        };
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class EventMessageUtils {
        /**
         * Gets interaction status from event message
         * @param message
         * @param currentStatus
         */
        static getInteractionStatusFromEvent(message, currentStatus) {
            switch (message.eventType) {
                case EventType.ACQUIRE_TOKEN_START:
                    if (message.interactionType === exports.InteractionType.Redirect ||
                        message.interactionType === exports.InteractionType.Popup) {
                        return InteractionStatus.AcquireToken;
                    }
                    break;
                case EventType.HANDLE_REDIRECT_START:
                    return InteractionStatus.HandleRedirect;
                case EventType.LOGOUT_START:
                    return InteractionStatus.Logout;
                case EventType.LOGOUT_END:
                    if (currentStatus &&
                        currentStatus !== InteractionStatus.Logout) {
                        // Prevent this event from clearing any status other than logout
                        break;
                    }
                    return InteractionStatus.None;
                case EventType.HANDLE_REDIRECT_END:
                    if (currentStatus &&
                        currentStatus !== InteractionStatus.HandleRedirect) {
                        // Prevent this event from clearing any status other than handleRedirect
                        break;
                    }
                    return InteractionStatus.None;
                case EventType.ACQUIRE_TOKEN_SUCCESS:
                case EventType.ACQUIRE_TOKEN_FAILURE:
                case EventType.RESTORE_FROM_BFCACHE:
                    if (message.interactionType === exports.InteractionType.Redirect ||
                        message.interactionType === exports.InteractionType.Popup) {
                        if (currentStatus &&
                            currentStatus !== InteractionStatus.AcquireToken) {
                            // Prevent this event from clearing any status other than acquireToken
                            break;
                        }
                        return InteractionStatus.None;
                    }
                    break;
            }
            return null;
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class SignedHttpRequest {
        constructor(shrParameters, shrOptions) {
            const loggerOptions = (shrOptions && shrOptions.loggerOptions) || {};
            this.logger = new Logger(loggerOptions, name, version);
            this.cryptoOps = new CryptoOps(this.logger);
            this.popTokenGenerator = new PopTokenGenerator(this.cryptoOps, new StubPerformanceClient());
            this.shrParameters = shrParameters;
        }
        /**
         * Generates and caches a keypair for the given request options.
         * @returns Public key digest, which should be sent to the token issuer.
         */
        async generatePublicKeyThumbprint() {
            const { kid } = await this.popTokenGenerator.generateKid(this.shrParameters);
            return kid;
        }
        /**
         * Generates a signed http request for the given payload with the given key.
         * @param payload Payload to sign (e.g. access token)
         * @param publicKeyThumbprint Public key digest (from generatePublicKeyThumbprint API)
         * @param claims Additional claims to include/override in the signed JWT
         * @returns Pop token signed with the corresponding private key
         */
        async signRequest(payload, publicKeyThumbprint, claims) {
            return this.popTokenGenerator.signPayload(payload, publicKeyThumbprint, this.shrParameters, claims);
        }
        /**
         * Removes cached keys from browser for given public key thumbprint
         * @param publicKeyThumbprint Public key digest (from generatePublicKeyThumbprint API)
         * @param correlationId
         * @returns If keys are properly deleted
         */
        async removeKeys(publicKeyThumbprint, correlationId) {
            return this.cryptoOps.removeTokenBindingKey(publicKeyThumbprint, correlationId);
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * Returns browser performance measurement module if session flag is enabled. Returns undefined otherwise.
     */
    function getPerfMeasurementModule() {
        let sessionStorage;
        try {
            sessionStorage = window[BrowserCacheLocation.SessionStorage];
            const perfEnabled = sessionStorage?.getItem(BROWSER_PERF_ENABLED_KEY);
            if (Number(perfEnabled) === 1) {
                return Promise.resolve().then(function () { return BrowserPerformanceMeasurement$1; });
            }
            // Mute errors if it's a non-browser environment or cookies are blocked.
        }
        catch (e) { }
        return undefined;
    }
    /**
     * Returns boolean, indicating whether browser supports window.performance.now() function.
     */
    function supportsBrowserPerformanceNow() {
        return (typeof window !== "undefined" &&
            typeof window.performance !== "undefined" &&
            typeof window.performance.now === "function");
    }
    /**
     * Returns event duration in milliseconds using window performance API if available. Returns undefined otherwise.
     * @param startTime {DOMHighResTimeStamp | undefined}
     * @returns {number | undefined}
     */
    function getPerfDurationMs(startTime) {
        if (!startTime || !supportsBrowserPerformanceNow()) {
            return undefined;
        }
        return Math.round(window.performance.now() - startTime);
    }
    class BrowserPerformanceClient extends PerformanceClient {
        constructor(configuration, intFields) {
            super(configuration.auth.clientId, configuration.auth.authority || `${DEFAULT_AUTHORITY}`, new Logger(configuration.system?.loggerOptions || {}, name, version), name, version, configuration.telemetry?.application || {
                appName: "",
                appVersion: "",
            }, intFields);
        }
        generateId() {
            return createNewGuid();
        }
        getPageVisibility() {
            return document.visibilityState?.toString() || null;
        }
        getOnlineStatus() {
            return typeof navigator !== "undefined" ? navigator.onLine : null;
        }
        deleteIncompleteSubMeasurements(inProgressEvent) {
            void getPerfMeasurementModule()?.then((module) => {
                const rootEvent = this.eventsByCorrelationId.get(inProgressEvent.event.correlationId);
                const isRootEvent = rootEvent &&
                    rootEvent.eventId === inProgressEvent.event.eventId;
                const incompleteMeasurements = [];
                if (isRootEvent && rootEvent?.incompleteSubMeasurements) {
                    rootEvent.incompleteSubMeasurements.forEach((subMeasurement) => {
                        incompleteMeasurements.push({ ...subMeasurement });
                    });
                }
                // Clean up remaining marks for incomplete sub-measurements
                module.BrowserPerformanceMeasurement.flushMeasurements(inProgressEvent.event.correlationId, incompleteMeasurements);
            });
        }
        /**
         * Starts measuring performance for a given operation. Returns a function that should be used to end the measurement.
         * Also captures browser page visibilityState.
         *
         * @param {PerformanceEvents} measureName
         * @param {?string} [correlationId]
         * @returns {((event?: Partial<PerformanceEvent>) => PerformanceEvent| null)}
         */
        startMeasurement(measureName, correlationId) {
            // Capture page visibilityState and then invoke start/end measurement
            const startPageVisibility = this.getPageVisibility();
            const startOnlineStatus = this.getOnlineStatus();
            const inProgressEvent = super.startMeasurement(measureName, correlationId);
            const startTime = supportsBrowserPerformanceNow()
                ? window.performance.now()
                : undefined;
            const browserMeasurement = getPerfMeasurementModule()?.then((module) => {
                return new module.BrowserPerformanceMeasurement(measureName, inProgressEvent.event.correlationId);
            });
            void browserMeasurement?.then((measurement) => measurement.startMeasurement());
            return {
                ...inProgressEvent,
                end: (event, error, account) => {
                    const networkInfo = getNetworkInfo();
                    const res = inProgressEvent.end({
                        ...event,
                        startPageVisibility,
                        startOnlineStatus,
                        endPageVisibility: this.getPageVisibility(),
                        durationMs: getPerfDurationMs(startTime),
                        networkEffectiveType: networkInfo.effectiveType,
                        networkRtt: networkInfo.rtt,
                    }, error, account);
                    void browserMeasurement?.then((measurement) => measurement.endMeasurement());
                    this.deleteIncompleteSubMeasurements(inProgressEvent);
                    return res;
                },
                discard: () => {
                    inProgressEvent.discard();
                    void browserMeasurement?.then((measurement) => measurement.flushMeasurement());
                    this.deleteIncompleteSubMeasurements(inProgressEvent);
                },
            };
        }
    }
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    class BrowserPerformanceMeasurement {
        constructor(name, correlationId) {
            this.correlationId = correlationId;
            this.measureName = BrowserPerformanceMeasurement.makeMeasureName(name, correlationId);
            this.startMark = BrowserPerformanceMeasurement.makeStartMark(name, correlationId);
            this.endMark = BrowserPerformanceMeasurement.makeEndMark(name, correlationId);
        }
        static makeMeasureName(name, correlationId) {
            return `msal.measure.${name}.${correlationId}`;
        }
        static makeStartMark(name, correlationId) {
            return `msal.start.${name}.${correlationId}`;
        }
        static makeEndMark(name, correlationId) {
            return `msal.end.${name}.${correlationId}`;
        }
        static supportsBrowserPerformance() {
            return (typeof window !== "undefined" &&
                typeof window.performance !== "undefined" &&
                typeof window.performance.mark === "function" &&
                typeof window.performance.measure === "function" &&
                typeof window.performance.clearMarks === "function" &&
                typeof window.performance.clearMeasures === "function" &&
                typeof window.performance.getEntriesByName === "function");
        }
        /**
         * Flush browser marks and measurements.
         * @param {string} correlationId
         * @param {SubMeasurement} measurements
         */
        static flushMeasurements(correlationId, measurements) {
            if (BrowserPerformanceMeasurement.supportsBrowserPerformance()) {
                try {
                    measurements.forEach((measurement) => {
                        const measureName = BrowserPerformanceMeasurement.makeMeasureName(measurement.name, correlationId);
                        const entriesForMeasurement = window.performance.getEntriesByName(measureName, "measure");
                        if (entriesForMeasurement.length > 0) {
                            window.performance.clearMeasures(measureName);
                            window.performance.clearMarks(BrowserPerformanceMeasurement.makeStartMark(measureName, correlationId));
                            window.performance.clearMarks(BrowserPerformanceMeasurement.makeEndMark(measureName, correlationId));
                        }
                    });
                }
                catch (e) {
                    // Silently catch and return null
                }
            }
        }
        startMeasurement() {
            if (BrowserPerformanceMeasurement.supportsBrowserPerformance()) {
                try {
                    window.performance.mark(this.startMark);
                }
                catch (e) {
                    // Silently catch
                }
            }
        }
        endMeasurement() {
            if (BrowserPerformanceMeasurement.supportsBrowserPerformance()) {
                try {
                    window.performance.mark(this.endMark);
                    window.performance.measure(this.measureName, this.startMark, this.endMark);
                }
                catch (e) {
                    // Silently catch
                }
            }
        }
        flushMeasurement() {
            if (BrowserPerformanceMeasurement.supportsBrowserPerformance()) {
                try {
                    const entriesForMeasurement = window.performance.getEntriesByName(this.measureName, "measure");
                    if (entriesForMeasurement.length > 0) {
                        const durationMs = entriesForMeasurement[0].duration;
                        window.performance.clearMeasures(this.measureName);
                        window.performance.clearMarks(this.startMark);
                        window.performance.clearMarks(this.endMark);
                        return durationMs;
                    }
                }
                catch (e) {
                    // Silently catch and return null
                }
            }
            return null;
        }
    }
 
    var BrowserPerformanceMeasurement$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        BrowserPerformanceMeasurement: BrowserPerformanceMeasurement
    });
 
    /*
     * Copyright (c) Microsoft Corporation. All rights reserved.
     * Licensed under the MIT License.
     */
    /**
     * @packageDocumentation
     * @module @azure/msal-browser
     */
    // Common constants
    const AuthenticationScheme = AuthenticationScheme$1;
    const ResponseMode = ResponseMode$1;
    const PromptValue = PromptValue$1;
    const JsonWebTokenTypes = JsonWebTokenTypes$1;
    const OIDC_DEFAULT_SCOPES = OIDC_DEFAULT_SCOPES$1;
 
    exports.ApiId = ApiId;
    exports.AuthError = AuthError;
    exports.AuthErrorCodes = AuthErrorCodes;
    exports.AuthenticationHeaderParser = AuthenticationHeaderParser;
    exports.AuthenticationScheme = AuthenticationScheme;
    exports.AzureCloudInstance = AzureCloudInstance;
    exports.BrowserAuthError = BrowserAuthError;
    exports.BrowserAuthErrorCodes = BrowserAuthErrorCodes;
    exports.BrowserCacheLocation = BrowserCacheLocation;
    exports.BrowserConfigurationAuthError = BrowserConfigurationAuthError;
    exports.BrowserConfigurationAuthErrorCodes = BrowserConfigurationAuthErrorCodes;
    exports.BrowserPerformanceClient = BrowserPerformanceClient;
    exports.BrowserPerformanceMeasurement = BrowserPerformanceMeasurement;
    exports.BrowserRootPerformanceEvents = BrowserRootPerformanceEvents;
    exports.BrowserUtils = BrowserUtils;
    exports.CacheLookupPolicy = CacheLookupPolicy;
    exports.ClientAuthError = ClientAuthError;
    exports.ClientAuthErrorCodes = ClientAuthErrorCodes;
    exports.ClientConfigurationError = ClientConfigurationError;
    exports.ClientConfigurationErrorCodes = ClientConfigurationErrorCodes;
    exports.DEFAULT_IFRAME_TIMEOUT_MS = DEFAULT_IFRAME_TIMEOUT_MS;
    exports.EventHandler = EventHandler;
    exports.EventMessageUtils = EventMessageUtils;
    exports.EventType = EventType;
    exports.InteractionRequiredAuthError = InteractionRequiredAuthError;
    exports.InteractionRequiredAuthErrorCodes = InteractionRequiredAuthErrorCodes;
    exports.InteractionStatus = InteractionStatus;
    exports.JsonWebTokenTypes = JsonWebTokenTypes;
    exports.LocalStorage = LocalStorage;
    exports.Logger = Logger;
    exports.MemoryStorage = MemoryStorage;
    exports.NavigationClient = NavigationClient;
    exports.OIDC_DEFAULT_SCOPES = OIDC_DEFAULT_SCOPES;
    exports.PromptValue = PromptValue;
    exports.ProtocolMode = ProtocolMode;
    exports.PublicClientApplication = PublicClientApplication;
    exports.ResponseMode = ResponseMode;
    exports.ServerError = ServerError;
    exports.SessionStorage = SessionStorage;
    exports.SignedHttpRequest = SignedHttpRequest;
    exports.StubPerformanceClient = StubPerformanceClient;
    exports.WrapperSKU = WrapperSKU;
    exports.createNestablePublicClientApplication = createNestablePublicClientApplication;
    exports.createStandardPublicClientApplication = createStandardPublicClientApplication;
    exports.enforceResourceParameter = enforceResourceParameter;
    exports.isPlatformBrokerAvailable = isPlatformBrokerAvailable;
    exports.loadExternalTokens = loadExternalTokens;
    exports.stubbedPublicClientApplication = stubbedPublicClientApplication;
    exports.version = version;
 
}));
//# sourceMappingURL=msal-browser.js.map