summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/ExtensionCommon.sys.mjs
blob: c06cf37a6abba9601230ca8c2da40de9b5e017a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * This module contains utilities and base classes for logic which is
 * common between the parent and child process, and in particular
 * between ExtensionParent.sys.mjs and ExtensionChild.sys.mjs.
 */

import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";

import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";

/** @type {Lazy} */
const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  ConsoleAPI: "resource://gre/modules/Console.sys.mjs",
  PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
  SchemaRoot: "resource://gre/modules/Schemas.sys.mjs",
  Schemas: "resource://gre/modules/Schemas.sys.mjs",
});

XPCOMUtils.defineLazyServiceGetter(
  lazy,
  "styleSheetService",
  "@mozilla.org/content/style-sheet-service;1",
  "nsIStyleSheetService"
);

const ScriptError = Components.Constructor(
  "@mozilla.org/scripterror;1",
  "nsIScriptError",
  "initWithWindowID"
);

import { ExtensionUtils } from "resource://gre/modules/ExtensionUtils.sys.mjs";

var {
  DefaultMap,
  DefaultWeakMap,
  ExtensionError,
  filterStack,
  getInnerWindowID,
  getUniqueId,
} = ExtensionUtils;

function getConsole() {
  return new lazy.ConsoleAPI({
    maxLogLevelPref: "extensions.webextensions.log.level",
    prefix: "WebExtensions",
  });
}

// Run a function and report exceptions.
function runSafeSyncWithoutClone(f, ...args) {
  try {
    return f(...args);
  } catch (e) {
    // This method is called with `this` unbound and it doesn't have
    // access to a BaseContext instance and so we can't check if `e`
    // is an instance of the extension context's Error constructor
    // (like we do in BaseContext applySafeWithoutClone method).
    dump(
      `Extension error: ${e} ${e?.fileName} ${
        e?.lineNumber
      }\n[[Exception stack\n${
        e?.stack ? filterStack(e) : undefined
      }Current stack\n${filterStack(Error())}]]\n`
    );
    Cu.reportError(e);
  }
}

// Return true if the given value is an instance of the given
// native type.
function instanceOf(value, type) {
  return (
    value &&
    typeof value === "object" &&
    ChromeUtils.getClassName(value) === type
  );
}

/**
 * Convert any of several different representations of a date/time to a Date object.
 * Accepts several formats:
 * a Date object, an ISO8601 string, or a number of milliseconds since the epoch as
 * either a number or a string.
 *
 * @param {Date|string|number} date
 *      The date to convert.
 * @returns {Date}
 *      A Date object
 */
function normalizeTime(date) {
  // Of all the formats we accept the "number of milliseconds since the epoch as a string"
  // is an outlier, everything else can just be passed directly to the Date constructor.
  return new Date(
    typeof date == "string" && /^\d+$/.test(date) ? parseInt(date, 10) : date
  );
}

function withHandlingUserInput(window, callable) {
  let handle = window.windowUtils.setHandlingUserInput(true);
  try {
    return callable();
  } finally {
    handle.destruct();
  }
}

/**
 * Defines a lazy getter for the given property on the given object. The
 * first time the property is accessed, the return value of the getter
 * is defined on the current `this` object with the given property name.
 * Importantly, this means that a lazy getter defined on an object
 * prototype will be invoked separately for each object instance that
 * it's accessed on.
 *
 * Note: for better type inference, prefer redefineGetter() below.
 *
 * @param {object} object
 *        The prototype object on which to define the getter.
 * @param {string | symbol} prop
 *        The property name for which to define the getter.
 * @param {callback} getter
 *        The function to call in order to generate the final property
 *        value.
 */
function defineLazyGetter(object, prop, getter) {
  Object.defineProperty(object, prop, {
    enumerable: true,
    configurable: true,
    get() {
      return redefineGetter(this, prop, getter.call(this), true);
    },
    set(value) {
      redefineGetter(this, prop, value, true);
    },
  });
}

/**
 * A more type-inference friendly version of defineLazyGetter() above.
 * Call it from a real getter (and setter) for your class or object.
 * On first run, it will redefine the property with the final value.
 *
 * @template Value
 * @param {object} object
 * @param {string | symbol} key
 * @param {Value} value
 * @returns {Value}
 */
function redefineGetter(object, key, value, writable = false) {
  Object.defineProperty(object, key, {
    enumerable: true,
    configurable: true,
    writable,
    value,
  });
  return value;
}

function checkLoadURI(uri, principal, options) {
  let ssm = Services.scriptSecurityManager;

  let flags = ssm.STANDARD;
  if (!options.allowScript) {
    flags |= ssm.DISALLOW_SCRIPT;
  }
  if (!options.allowInheritsPrincipal) {
    flags |= ssm.DISALLOW_INHERIT_PRINCIPAL;
  }
  if (options.dontReportErrors) {
    flags |= ssm.DONT_REPORT_ERRORS;
  }

  try {
    ssm.checkLoadURIWithPrincipal(principal, uri, flags);
  } catch (e) {
    return false;
  }
  return true;
}

function checkLoadURL(url, principal, options) {
  try {
    return checkLoadURI(Services.io.newURI(url), principal, options);
  } catch (e) {
    return false; // newURI threw.
  }
}

function makeWidgetId(id) {
  id = id.toLowerCase();
  // FIXME: This allows for collisions.
  return id.replace(/[^a-z0-9_-]/g, "_");
}

/**
 * A sentinel class to indicate that an array of values should be
 * treated as an array when used as a promise resolution value, but as a
 * spread expression (...args) when passed to a callback.
 */
class SpreadArgs extends Array {
  constructor(args) {
    super();
    this.push(...args);
  }
}

/**
 * Like SpreadArgs, but also indicates that the array values already
 * belong to the target compartment, and should not be cloned before
 * being passed.
 *
 * The `unwrappedValues` property contains an Array object which belongs
 * to the target compartment, and contains the same unwrapped values
 * passed the NoCloneSpreadArgs constructor.
 */
class NoCloneSpreadArgs {
  constructor(args) {
    this.unwrappedValues = args;
  }

  [Symbol.iterator]() {
    return this.unwrappedValues[Symbol.iterator]();
  }
}

const LISTENERS = Symbol("listeners");
const ONCE_MAP = Symbol("onceMap");

export class EventEmitter {
  constructor() {
    this[LISTENERS] = new Map();
    this[ONCE_MAP] = new WeakMap();
  }

  /**
   * Checks whether there is some listener for the given event.
   *
   * @param {string} event
   *       The name of the event to listen for.
   * @returns {boolean}
   */
  has(event) {
    return this[LISTENERS].has(event);
  }

  /**
   * Adds the given function as a listener for the given event.
   *
   * The listener function may optionally return a Promise which
   * resolves when it has completed all operations which event
   * dispatchers may need to block on.
   *
   * @param {string} event
   *       The name of the event to listen for.
   * @param {function(string, ...any): any} listener
   *        The listener to call when events are emitted.
   */
  on(event, listener) {
    let listeners = this[LISTENERS].get(event);
    if (!listeners) {
      listeners = new Set();
      this[LISTENERS].set(event, listeners);
    }

    listeners.add(listener);
  }

  /**
   * Removes the given function as a listener for the given event.
   *
   * @param {string} event
   *       The name of the event to stop listening for.
   * @param {function(string, ...any): any} listener
   *        The listener function to remove.
   */
  off(event, listener) {
    let set = this[LISTENERS].get(event);
    if (set) {
      set.delete(listener);
      set.delete(this[ONCE_MAP].get(listener));
      if (!set.size) {
        this[LISTENERS].delete(event);
      }
    }
  }

  /**
   * Adds the given function as a listener for the given event once.
   *
   * @param {string} event
   *       The name of the event to listen for.
   * @param {function(string, ...any): any} listener
   *        The listener to call when events are emitted.
   */
  once(event, listener) {
    let wrapper = (event, ...args) => {
      this.off(event, wrapper);
      this[ONCE_MAP].delete(listener);

      return listener(event, ...args);
    };
    this[ONCE_MAP].set(listener, wrapper);

    this.on(event, wrapper);
  }

  /**
   * Triggers all listeners for the given event. If any listeners return
   * a value, returns a promise which resolves when all returned
   * promises have resolved. Otherwise, returns undefined.
   *
   * @param {string} event
   *       The name of the event to emit.
   * @param {any} args
   *        Arbitrary arguments to pass to the listener functions, after
   *        the event name.
   * @returns {Promise?}
   */
  emit(event, ...args) {
    let listeners = this[LISTENERS].get(event);

    if (listeners) {
      let promises = [];

      for (let listener of listeners) {
        try {
          let result = listener(event, ...args);
          if (result !== undefined) {
            promises.push(result);
          }
        } catch (e) {
          Cu.reportError(e);
        }
      }

      if (promises.length) {
        return Promise.all(promises);
      }
    }
  }
}

/**
 * Base class for WebExtension APIs.  Each API creates a new class
 * that inherits from this class, the derived class is instantiated
 * once for each extension that uses the API.
 */
export class ExtensionAPI extends EventEmitter {
  constructor(extension) {
    super();

    this.extension = extension;

    extension.once("shutdown", (what, isAppShutdown) => {
      if (this.onShutdown) {
        this.onShutdown(isAppShutdown);
      }
      this.extension = null;
    });
  }

  destroy() {}

  /** @param {string} _entryName */
  onManifestEntry(_entryName) {}

  /** @param {boolean} _isAppShutdown */
  onShutdown(_isAppShutdown) {}

  /** @param {BaseContext} _context */
  getAPI(_context) {
    throw new Error("Not Implemented");
  }

  /** @param {string} _id */
  static onDisable(_id) {}

  /** @param {string} _id */
  static onUninstall(_id) {}

  /**
   * @param {string} _id
   * @param {object} _manifest
   */
  static onUpdate(_id, _manifest) {}
}

/**
 * Subclass to add APIs commonly used with persistent events.
 * If a namespace uses events, it should use this subclass.
 *
 * this.apiNamespace = class extends ExtensionAPIPersistent {};
 */
class ExtensionAPIPersistent extends ExtensionAPI {
  /** @type {Record<string, callback>} */
  PERSISTENT_EVENTS;

  /**
   * Check for event entry.
   *
   * @param {string} event The event name e.g. onStateChanged
   * @returns {boolean}
   */
  hasEventRegistrar(event) {
    return (
      this.PERSISTENT_EVENTS && Object.hasOwn(this.PERSISTENT_EVENTS, event)
    );
  }

  /**
   * Get the event registration fuction
   *
   * @param {string} event The event name e.g. onStateChanged
   * @returns {Function} register is used to start the listener
   *                     register returns an object containing
   *                     a convert and unregister function.
   */
  getEventRegistrar(event) {
    if (this.hasEventRegistrar(event)) {
      return this.PERSISTENT_EVENTS[event].bind(this);
    }
  }

  /**
   * Used when instantiating an EventManager instance to register the listener.
   *
   * @param {object}      options         Options used for event registration
   * @param {BaseContext} options.context Extension Context passed when creating an EventManager instance.
   * @param {string}      options.event   The eAPI vent name.
   * @param {Function}    options.fire    The function passed to the listener to fire the event.
   * @param {Array<any>}  params          An optional array of parameters received along with the
   *                                      addListener request.
   * @returns {Function}                  The unregister function used in the EventManager.
   */
  registerEventListener(options, params) {
    const apiRegistar = this.getEventRegistrar(options.event);
    return apiRegistar?.(options, params).unregister;
  }

  /**
   * Used to prime a listener for when the background script is not running.
   *
   * @param {string} event The event name e.g. onStateChanged or captiveURL.onChange.
   * @param {Function} fire The function passed to the listener to fire the event.
   * @param {Array} params Params passed to the event listener.
   * @param {boolean} isInStartup unused here but passed for subclass use.
   * @returns {object} the unregister and convert functions used in the EventManager.
   */
  primeListener(event, fire, params, isInStartup) {
    const apiRegistar = this.getEventRegistrar(event);
    return apiRegistar?.({ fire, isInStartup }, params);
  }
}

/**
 * This class contains the information we have about an individual
 * extension.  It is never instantiated directly, instead subclasses
 * for each type of process extend this class and add members that are
 * relevant for that process.
 *
 * @abstract
 */
export class BaseContext {
  /** @type {boolean} */
  isTopContext;
  /** @type {string} */
  viewType;

  constructor(envType, extension) {
    this.envType = envType;
    this.onClose = new Set();
    this.checkedLastError = false;
    this._lastError = null;
    this.contextId = getUniqueId();
    this.unloaded = false;
    this.extension = extension;
    this.manifestVersion = extension.manifestVersion;
    this.jsonSandbox = null;
    this.active = true;
    this.incognito = null;
    this.messageManager = null;
    this.contentWindow = null;
    this.innerWindowID = 0;

    // These two properties are assigned in ContentScriptContextChild subclass
    // to keep a copy of the content script sandbox Error and Promise globals
    // (which are used by the WebExtensions internals) before any extension
    // content script code had any chance to redefine them.
    this.cloneScopeError = null;
    this.cloneScopePromise = null;
  }

  get isProxyContextParent() {
    return false;
  }

  get Error() {
    // Return the copy stored in the context instance (when the context is an instance of
    // ContentScriptContextChild or the global from extension page window otherwise).
    return this.cloneScopeError || this.cloneScope.Error;
  }

  get Promise() {
    // Return the copy stored in the context instance (when the context is an instance of
    // ContentScriptContextChild or the global from extension page window otherwise).
    return this.cloneScopePromise || this.cloneScope.Promise;
  }

  get privateBrowsingAllowed() {
    return this.extension.privateBrowsingAllowed;
  }

  get isBackgroundContext() {
    if (this.viewType === "background") {
      if (this.isProxyContextParent) {
        return !!this.isTopContext; // Set in ExtensionPageContextParent.
      }
      const { contentWindow } = this;
      return !!contentWindow && contentWindow.top === contentWindow;
    }
    return this.viewType === "background_worker";
  }

  /**
   * Whether the extension context is using the WebIDL bindings for the
   * WebExtensions APIs.
   * To be overridden in subclasses (e.g. WorkerContextChild) and to be
   * optionally used in ExtensionAPI classes to customize the behavior of the
   * API when the calls to the extension API are originated from the WebIDL
   * bindings.
   */
  get useWebIDLBindings() {
    return false;
  }

  canAccessWindow(window) {
    return this.extension.canAccessWindow(window);
  }

  canAccessContainer(userContextId) {
    return this.extension.canAccessContainer(userContextId);
  }

  /**
   * Opens a conduit linked to this context, populating related address fields.
   * Only available in child contexts with an associated contentWindow.
   *
   * @type {ConduitGen}
   */
  openConduit(subject, address) {
    let wgc = this.contentWindow.windowGlobalChild;
    let conduit = wgc.getActor("Conduits").openConduit(subject, {
      id: subject.id || getUniqueId(),
      extensionId: this.extension.id,
      envType: this.envType,
      ...address,
    });
    this.callOnClose(conduit);
    conduit.setCloseCallback(() => {
      this.forgetOnClose(conduit);
    });
    return conduit;
  }

  setContentWindow(contentWindow) {
    if (!this.canAccessWindow(contentWindow)) {
      throw new Error(
        "BaseContext attempted to load when extension is not allowed due to incognito settings."
      );
    }

    this.innerWindowID = getInnerWindowID(contentWindow);
    this.messageManager = contentWindow.docShell.messageManager;

    if (this.incognito == null) {
      this.incognito =
        lazy.PrivateBrowsingUtils.isContentWindowPrivate(contentWindow);
    }

    let wgc = contentWindow.windowGlobalChild;
    Object.defineProperty(this, "active", {
      configurable: true,
      enumerable: true,
      get: () => wgc.isCurrentGlobal && !wgc.windowContext.isInBFCache,
    });
    Object.defineProperty(this, "contentWindow", {
      configurable: true,
      enumerable: true,
      get: () => (this.active ? wgc.browsingContext.window : null),
    });
    this.callOnClose({
      close: () => {
        // Allow other "close" handlers to use these properties, until the next tick.
        Promise.resolve().then(() => {
          Object.defineProperty(this, "contentWindow", { value: null });
          Object.defineProperty(this, "active", { value: false });
          wgc = null;
        });
      },
    });
  }

  // All child contexts must implement logActivity.  This is handled if the child
  // context subclasses ExtensionBaseContextChild.  ProxyContextParent overrides
  // this with a noop for parent contexts.
  logActivity(_type, _name, _data) {
    throw new Error(`Not implemented for ${this.envType}`);
  }

  /** @type {object} */
  get cloneScope() {
    throw new Error("Not implemented");
  }

  /** @type {nsIPrincipal} */
  get principal() {
    throw new Error("Not implemented");
  }

  runSafe(callback, ...args) {
    return this.applySafe(callback, args);
  }

  runSafeWithoutClone(callback, ...args) {
    return this.applySafeWithoutClone(callback, args);
  }

  applySafe(callback, args, caller) {
    if (this.unloaded) {
      Cu.reportError("context.runSafe called after context unloaded", caller);
    } else if (!this.active) {
      Cu.reportError(
        "context.runSafe called while context is inactive",
        caller
      );
    } else {
      try {
        let { cloneScope } = this;
        args = args.map(arg => Cu.cloneInto(arg, cloneScope));
      } catch (e) {
        Cu.reportError(e);
        dump(
          `runSafe failure: cloning into ${
            this.cloneScope
          }: ${e}\n\n${filterStack(Error())}`
        );
      }

      return this.applySafeWithoutClone(callback, args, caller);
    }
  }

  applySafeWithoutClone(callback, args, caller) {
    if (this.unloaded) {
      Cu.reportError(
        "context.runSafeWithoutClone called after context unloaded",
        caller
      );
    } else if (!this.active) {
      Cu.reportError(
        "context.runSafeWithoutClone called while context is inactive",
        caller
      );
    } else {
      try {
        return Reflect.apply(callback, null, args);
      } catch (e) {
        // An extension listener may as well be throwing an object that isn't
        // an instance of Error, in that case we have to use fallbacks for the
        // error message, fileName, lineNumber and columnNumber properties.
        const isError = e instanceof this.Error;
        let message;
        let fileName;
        let lineNumber;
        let columnNumber;

        if (isError) {
          message = `${e.name}: ${e.message}`;
          lineNumber = e.lineNumber;
          columnNumber = e.columnNumber;
          fileName = e.fileName;
        } else {
          message = `uncaught exception: ${e}`;

          try {
            // TODO(Bug 1810582): the following fallback logic may go away once
            // we introduced a better way to capture and log the exception in
            // the right window and in all cases (included when the extension
            // code is raising undefined or an object that isn't an instance of
            // the Error constructor).
            //
            // Fallbacks for the error location:
            // - the callback location if it is registered directly from the
            //   extension code (and not wrapped by the child/ext-APINAMe.js
            //   implementation, like e.g. browser.storage, browser.devtools.network
            //   are doing and browser.menus).
            // - if the location of the extension callback is not directly
            //   available (e.g. browser.storage onChanged events, and similarly
            //   for browser.devtools.network and browser.menus events):
            //   - the extension page url if the context is an extension page
            //   - the extension base url if the context is a content script
            const cbLoc = Cu.getFunctionSourceLocation(callback);
            fileName = cbLoc.filename;
            lineNumber = cbLoc.lineNumber ?? lineNumber;

            const extBaseUrl = this.extension.baseURI.resolve("/");
            if (fileName.startsWith(extBaseUrl)) {
              fileName = cbLoc.filename;
              lineNumber = cbLoc.lineNumber ?? lineNumber;
            } else {
              fileName = this.contentWindow?.location?.href;
              if (!fileName || !fileName.startsWith(extBaseUrl)) {
                fileName = extBaseUrl;
              }
            }
          } catch {
            // Ignore errors on retrieving the callback source location.
          }
        }

        dump(
          `Extension error: ${message} ${fileName} ${lineNumber}\n[[Exception stack\n${
            isError ? filterStack(e) : undefined
          }Current stack\n${filterStack(Error())}]]\n`
        );

        // If the error is coming from an extension context associated
        // to a window (e.g. an extension page or extension content script).
        //
        // TODO(Bug 1810574): for the background service worker we will need to do
        // something similar, but not tied to the innerWindowID because there
        // wouldn't be one set for extension contexts related to the
        // background service worker.
        //
        // TODO(Bug 1810582): change the error associated to the innerWindowID to also
        // include a full stack from the original error.
        if (!this.isProxyContextParent && this.contentWindow) {
          Services.console.logMessage(
            new ScriptError(
              message,
              fileName,
              null,
              lineNumber,
              columnNumber,
              Ci.nsIScriptError.errorFlag,
              "content javascript",
              this.innerWindowID
            )
          );
        }
        // Also report the original error object (because it also includes
        // the full error stack).
        Cu.reportError(e);
      }
    }
  }

  checkLoadURL(url, options = {}) {
    // As an optimization, f the URL starts with the extension's base URL,
    // don't do any further checks. It's always allowed to load it.
    if (url.startsWith(this.extension.baseURL)) {
      return true;
    }

    return checkLoadURL(url, this.principal, options);
  }

  /**
   * Safely call JSON.stringify() on an object that comes from an
   * extension.
   *
   * @param {[any, callback?, number?]} args for JSON.stringify()
   * @returns {string} The stringified representation of obj
   */
  jsonStringify(...args) {
    if (!this.jsonSandbox) {
      this.jsonSandbox = Cu.Sandbox(this.principal, {
        sameZoneAs: this.cloneScope,
        wantXrays: false,
      });
    }

    return Cu.waiveXrays(this.jsonSandbox.JSON).stringify(...args);
  }

  callOnClose(obj) {
    this.onClose.add(obj);
  }

  forgetOnClose(obj) {
    this.onClose.delete(obj);
  }

  get lastError() {
    this.checkedLastError = true;
    return this._lastError;
  }

  set lastError(val) {
    this.checkedLastError = false;
    this._lastError = val;
  }

  /**
   * Normalizes the given error object for use by the target scope. If
   * the target is an error object which belongs to that scope, it is
   * returned as-is. If it is an ordinary object with a `message`
   * property, it is converted into an error belonging to the target
   * scope. If it is an Error object which does *not* belong to the
   * clone scope, it is reported, and converted to an unexpected
   * exception error.
   *
   * @param {Error|object} error
   * @param {nsIStackFrame?} [caller]
   * @returns {Error}
   */
  normalizeError(error, caller) {
    if (error instanceof this.Error) {
      return error;
    }
    let message, fileName;
    if (error && typeof error === "object") {
      const isPlain = ChromeUtils.getClassName(error) === "Object";
      if (isPlain && error.mozWebExtLocation) {
        caller = error.mozWebExtLocation;
      }
      if (isPlain && caller && (error.mozWebExtLocation || !error.fileName)) {
        caller = Cu.cloneInto(caller, this.cloneScope);
        return ChromeUtils.createError(error.message, caller);
      }

      if (
        isPlain ||
        error instanceof ExtensionError ||
        this.principal.subsumes(Cu.getObjectPrincipal(error))
      ) {
        message = error.message;
        fileName = error.fileName;
      }
    }

    if (!message) {
      Cu.reportError(error);
      message = "An unexpected error occurred";
    }
    return new this.Error(message, fileName);
  }

  /**
   * Sets the value of `.lastError` to `error`, calls the given
   * callback, and reports an error if the value has not been checked
   * when the callback returns.
   *
   * @param {object} error An object with a `message` property. May
   *     optionally be an `Error` object belonging to the target scope.
   * @param {nsIStackFrame?} caller
   *        The optional caller frame which triggered this callback, to be used
   *        in error reporting.
   * @param {Function} callback The callback to call.
   * @returns {*} The return value of callback.
   */
  withLastError(error, caller, callback) {
    this.lastError = this.normalizeError(error);
    try {
      return callback();
    } finally {
      if (!this.checkedLastError) {
        Cu.reportError(`Unchecked lastError value: ${this.lastError}`, caller);
      }
      this.lastError = null;
    }
  }

  /**
   * Captures the most recent stack frame which belongs to the extension.
   *
   * @returns {nsIStackFrame?}
   */
  getCaller() {
    return ChromeUtils.getCallerLocation(this.principal);
  }

  /**
   * Wraps the given promise so it can be safely returned to extension
   * code in this context.
   *
   * If `callback` is provided, however, it is used as a completion
   * function for the promise, and no promise is returned. In this case,
   * the callback is called when the promise resolves or rejects. In the
   * latter case, `lastError` is set to the rejection value, and the
   * callback function must check `browser.runtime.lastError` or
   * `extension.runtime.lastError` in order to prevent it being reported
   * to the console.
   *
   * @param {Promise} promise The promise with which to wrap the
   *     callback. May resolve to a `SpreadArgs` instance, in which case
   *     each element will be used as a separate argument.
   *
   *     Unless the promise object belongs to the cloneScope global, its
   *     resolution value is cloned into cloneScope prior to calling the
   *     `callback` function or resolving the wrapped promise.
   *
   * @param {Function} [callback] The callback function to wrap
   *
   * @returns {Promise|undefined} If callback is null, a promise object
   *     belonging to the target scope. Otherwise, undefined.
   */
  wrapPromise(promise, callback = null) {
    let caller = this.getCaller();
    let applySafe = this.applySafe.bind(this);
    if (Cu.getGlobalForObject(promise) === this.cloneScope) {
      applySafe = this.applySafeWithoutClone.bind(this);
    }

    if (callback) {
      promise.then(
        args => {
          if (this.unloaded) {
            Cu.reportError(`Promise resolved after context unloaded\n`, caller);
          } else if (!this.active) {
            Cu.reportError(
              `Promise resolved while context is inactive\n`,
              caller
            );
          } else if (args instanceof NoCloneSpreadArgs) {
            this.applySafeWithoutClone(callback, args.unwrappedValues, caller);
          } else if (args instanceof SpreadArgs) {
            applySafe(callback, args, caller);
          } else {
            applySafe(callback, [args], caller);
          }
        },
        error => {
          this.withLastError(error, caller, () => {
            if (this.unloaded) {
              Cu.reportError(
                `Promise rejected after context unloaded\n`,
                caller
              );
            } else if (!this.active) {
              Cu.reportError(
                `Promise rejected while context is inactive\n`,
                caller
              );
            } else {
              this.applySafeWithoutClone(callback, [], caller);
            }
          });
        }
      );
    } else {
      return new this.Promise((resolve, reject) => {
        promise.then(
          value => {
            if (this.unloaded) {
              Cu.reportError(
                `Promise resolved after context unloaded\n`,
                caller
              );
            } else if (!this.active) {
              Cu.reportError(
                `Promise resolved while context is inactive\n`,
                caller
              );
            } else if (value instanceof NoCloneSpreadArgs) {
              let values = value.unwrappedValues;
              this.applySafeWithoutClone(
                resolve,
                values.length == 1 ? [values[0]] : [values],
                caller
              );
            } else if (value instanceof SpreadArgs) {
              applySafe(resolve, value.length == 1 ? value : [value], caller);
            } else {
              applySafe(resolve, [value], caller);
            }
          },
          value => {
            if (this.unloaded) {
              Cu.reportError(
                `Promise rejected after context unloaded: ${
                  value && value.message
                }\n`,
                caller
              );
            } else if (!this.active) {
              Cu.reportError(
                `Promise rejected while context is inactive: ${
                  value && value.message
                }\n`,
                caller
              );
            } else {
              this.applySafeWithoutClone(
                reject,
                [this.normalizeError(value, caller)],
                caller
              );
            }
          }
        );
      });
    }
  }

  unload() {
    this.unloaded = true;

    for (let obj of this.onClose) {
      obj.close();
    }
    this.onClose.clear();
  }

  /**
   * A simple proxy for unload(), for use with callOnClose().
   */
  close() {
    this.unload();
  }
}

/**
 * An object that runs the implementation of a schema API. Instantiations of
 * this interfaces are used by Schemas.sys.mjs.
 *
 * @interface
 */
export class SchemaAPIInterface {
  /**
   * Calls this as a function that returns its return value.
   *
   * @abstract
   * @param {Array} _args The parameters for the function.
   * @returns {*} The return value of the invoked function.
   */
  callFunction(_args) {
    throw new Error("Not implemented");
  }

  /**
   * Calls this as a function and ignores its return value.
   *
   * @abstract
   * @param {Array} _args The parameters for the function.
   */
  callFunctionNoReturn(_args) {
    throw new Error("Not implemented");
  }

  /**
   * Calls this as a function that completes asynchronously.
   *
   * @abstract
   * @param {Array} _args The parameters for the function.
   * @param {callback} [_callback] The callback to be called when the function
   *     completes.
   * @param {boolean} [_requireUserInput=false] If true, the function should
   *                  fail if the browser is not currently handling user input.
   * @returns {Promise|undefined} Must be void if `callback` is set, and a
   *     promise otherwise. The promise is resolved when the function completes.
   */
  callAsyncFunction(_args, _callback, _requireUserInput) {
    throw new Error("Not implemented");
  }

  /**
   * Retrieves the value of this as a property.
   *
   * @abstract
   * @returns {*} The value of the property.
   */
  getProperty() {
    throw new Error("Not implemented");
  }

  /**
   * Assigns the value to this as property.
   *
   * @abstract
   * @param {string} _value The new value of the property.
   */
  setProperty(_value) {
    throw new Error("Not implemented");
  }

  /**
   * Registers a `listener` to this as an event.
   *
   * @abstract
   * @param {Function} _listener The callback to be called when the event fires.
   * @param {Array} _args Extra parameters for EventManager.addListener.
   * @see EventManager.addListener
   */
  addListener(_listener, _args) {
    throw new Error("Not implemented");
  }

  /**
   * Checks whether `listener` is listening to this as an event.
   *
   * @abstract
   * @param {Function} _listener The event listener.
   * @returns {boolean} Whether `listener` is registered with this as an event.
   * @see EventManager.hasListener
   */
  hasListener(_listener) {
    throw new Error("Not implemented");
  }

  /**
   * Unregisters `listener` from this as an event.
   *
   * @abstract
   * @param {Function} _listener The event listener.
   * @see EventManager.removeListener
   */
  removeListener(_listener) {
    throw new Error("Not implemented");
  }

  /**
   * Revokes the implementation object, and prevents any further method
   * calls from having external effects.
   *
   * @abstract
   */
  revoke() {
    throw new Error("Not implemented");
  }
}

/**
 * An object that runs a locally implemented API.
 */
class LocalAPIImplementation extends SchemaAPIInterface {
  /**
   * Constructs an implementation of the `name` method or property of `pathObj`.
   *
   * @param {object} pathObj The object containing the member with name `name`.
   * @param {string} name The name of the implemented member.
   * @param {BaseContext} context The context in which the schema is injected.
   */
  constructor(pathObj, name, context) {
    super();
    this.pathObj = pathObj;
    this.name = name;
    this.context = context;
  }

  revoke() {
    if (this.pathObj[this.name][lazy.Schemas.REVOKE]) {
      this.pathObj[this.name][lazy.Schemas.REVOKE]();
    }

    this.pathObj = null;
    this.name = null;
    this.context = null;
  }

  callFunction(args) {
    try {
      return this.pathObj[this.name](...args);
    } catch (e) {
      throw this.context.normalizeError(e);
    }
  }

  callFunctionNoReturn(args) {
    try {
      this.pathObj[this.name](...args);
    } catch (e) {
      throw this.context.normalizeError(e);
    }
  }

  callAsyncFunction(args, callback, requireUserInput) {
    let promise;
    try {
      if (requireUserInput) {
        if (!this.context.contentWindow.windowUtils.isHandlingUserInput) {
          throw new ExtensionError(
            `${this.name} may only be called from a user input handler`
          );
        }
      }
      promise = this.pathObj[this.name](...args) || Promise.resolve();
    } catch (e) {
      promise = Promise.reject(e);
    }
    return this.context.wrapPromise(promise, callback);
  }

  getProperty() {
    return this.pathObj[this.name];
  }

  setProperty(value) {
    this.pathObj[this.name] = value;
  }

  addListener(listener, args) {
    try {
      this.pathObj[this.name].addListener.call(null, listener, ...args);
    } catch (e) {
      throw this.context.normalizeError(e);
    }
  }

  hasListener(listener) {
    return this.pathObj[this.name].hasListener.call(null, listener);
  }

  removeListener(listener) {
    this.pathObj[this.name].removeListener.call(null, listener);
  }
}

// Recursively copy properties from source to dest.
function deepCopy(dest, source) {
  for (let prop in source) {
    let desc = Object.getOwnPropertyDescriptor(source, prop);
    if (typeof desc.value == "object") {
      if (!(prop in dest)) {
        dest[prop] = {};
      }
      deepCopy(dest[prop], source[prop]);
    } else {
      Object.defineProperty(dest, prop, desc);
    }
  }
}

function getChild(map, key) {
  let child = map.children.get(key);
  if (!child) {
    child = {
      modules: new Set(),
      children: new Map(),
    };

    map.children.set(key, child);
  }
  return child;
}

function getPath(map, path) {
  for (let key of path) {
    map = getChild(map, key);
  }
  return map;
}

function mergePaths(dest, source) {
  for (let name of source.modules) {
    dest.modules.add(name);
  }

  for (let [name, child] of source.children.entries()) {
    mergePaths(getChild(dest, name), child);
  }
}

/**
 * Manages loading and accessing a set of APIs for a specific extension
 * context.
 *
 * @param {BaseContext} context
 *        The context to manage APIs for.
 * @param {SchemaAPIManager} apiManager
 *        The API manager holding the APIs to manage.
 * @param {object} root
 *        The root object into which APIs will be injected.
 */
class CanOfAPIs {
  constructor(context, apiManager, root) {
    this.context = context;
    this.scopeName = context.envType;
    this.apiManager = apiManager;
    this.root = root;

    this.apiPaths = new Map();

    this.apis = new Map();
  }

  /**
   * Synchronously loads and initializes an ExtensionAPI instance.
   *
   * @param {string} name
   *        The name of the API to load.
   */
  loadAPI(name) {
    if (this.apis.has(name)) {
      return;
    }

    let { extension } = this.context;

    let api = this.apiManager.getAPI(name, extension, this.scopeName);
    if (!api) {
      return;
    }

    this.apis.set(name, api);

    deepCopy(this.root, api.getAPI(this.context));
  }

  /**
   * Asynchronously loads and initializes an ExtensionAPI instance.
   *
   * @param {string} name
   *        The name of the API to load.
   */
  async asyncLoadAPI(name) {
    if (this.apis.has(name)) {
      return;
    }

    let { extension } = this.context;
    if (!lazy.Schemas.checkPermissions(name, extension)) {
      return;
    }

    let api = await this.apiManager.asyncGetAPI(
      name,
      extension,
      this.scopeName
    );
    // Check again, because async;
    if (this.apis.has(name)) {
      return;
    }

    this.apis.set(name, api);

    deepCopy(this.root, api.getAPI(this.context));
  }

  /**
   * Finds the API at the given path from the root object, and
   * synchronously loads the API that implements it if it has not
   * already been loaded.
   *
   * @param {string} path
   *        The "."-separated path to find.
   * @returns {*}
   */
  findAPIPath(path) {
    if (this.apiPaths.has(path)) {
      return this.apiPaths.get(path);
    }

    let obj = this.root;
    let modules = this.apiManager.modulePaths;

    let parts = path.split(".");
    for (let [i, key] of parts.entries()) {
      if (!obj) {
        return;
      }
      modules = getChild(modules, key);

      for (let name of modules.modules) {
        if (!this.apis.has(name)) {
          this.loadAPI(name);
        }
      }

      if (!(key in obj) && i < parts.length - 1) {
        obj[key] = {};
      }
      obj = obj[key];
    }

    this.apiPaths.set(path, obj);
    return obj;
  }

  /**
   * Finds the API at the given path from the root object, and
   * asynchronously loads the API that implements it if it has not
   * already been loaded.
   *
   * @param {string} path
   *        The "."-separated path to find.
   * @returns {Promise<*>}
   */
  async asyncFindAPIPath(path) {
    if (this.apiPaths.has(path)) {
      return this.apiPaths.get(path);
    }

    let obj = this.root;
    let modules = this.apiManager.modulePaths;

    let parts = path.split(".");
    for (let [i, key] of parts.entries()) {
      if (!obj) {
        return;
      }
      modules = getChild(modules, key);

      for (let name of modules.modules) {
        if (!this.apis.has(name)) {
          await this.asyncLoadAPI(name);
        }
      }

      if (!(key in obj) && i < parts.length - 1) {
        obj[key] = {};
      }

      if (typeof obj[key] === "function") {
        obj = obj[key].bind(obj);
      } else {
        obj = obj[key];
      }
    }

    this.apiPaths.set(path, obj);
    return obj;
  }
}

/**
 * @class APIModule
 * @abstract
 *
 * @property {string} url
 *       The URL of the script which contains the module's
 *       implementation. This script must define a global property
 *       matching the modules name, which must be a class constructor
 *       which inherits from {@link ExtensionAPI}.
 *
 * @property {string} schema
 *       The URL of the JSON schema which describes the module's API.
 *
 * @property {Array<string>} scopes
 *       The list of scope names into which the API may be loaded.
 *
 * @property {Array<string>} manifest
 *       The list of top-level manifest properties which will trigger
 *       the module to be loaded, and its `onManifestEntry` method to be
 *       called.
 *
 * @property {Array<string>} events
 *       The list events which will trigger the module to be loaded, and
 *       its appropriate event handler method to be called. Currently
 *       only accepts "startup".
 *
 * @property {Array<string>} permissions
 *       An optional list of permissions, any of which must be present
 *       in order for the module to load.
 *
 * @property {Array<Array<string>>} paths
 *       A list of paths from the root API object which, when accessed,
 *       will cause the API module to be instantiated and injected.
 */

/**
 * This object loads the ext-*.js scripts that define the extension API.
 *
 * This class instance is shared with the scripts that it loads, so that the
 * ext-*.js scripts and the instantiator can communicate with each other.
 */
class SchemaAPIManager extends EventEmitter {
  /**
   * @param {string} processType
   *     "main" - The main, one and only chrome browser process.
   *     "addon" - An addon process.
   *     "content" - A content process.
   *     "devtools" - A devtools process.
   * @param {import("Schemas.sys.mjs").SchemaInject} [schema]
   */
  constructor(processType, schema) {
    super();
    this.processType = processType;
    this.global = null;
    if (schema) {
      this.schema = schema;
    }

    this.modules = new Map();
    this.modulePaths = { children: new Map(), modules: new Set() };
    this.manifestKeys = new Map();
    this.eventModules = new DefaultMap(() => new Set());
    this.settingsModules = new Set();

    this._modulesJSONLoaded = false;

    this.schemaURLs = new Map();

    this.apis = new DefaultWeakMap(() => new Map());

    this._scriptScopes = [];
  }

  onStartup(extension) {
    let promises = [];
    for (let apiName of this.eventModules.get("startup")) {
      promises.push(
        extension.apiManager.asyncGetAPI(apiName, extension).then(api => {
          if (api) {
            api.onStartup();
          }
        })
      );
    }

    return Promise.all(promises);
  }

  async loadModuleJSON(urls) {
    let promises = urls.map(url => fetch(url).then(resp => resp.json()));

    return this.initModuleJSON(await Promise.all(promises));
  }

  initModuleJSON(blobs) {
    for (let json of blobs) {
      this.registerModules(json);
    }

    this._modulesJSONLoaded = true;

    return new StructuredCloneHolder("SchemaAPIManager/initModuleJSON", null, {
      modules: this.modules,
      modulePaths: this.modulePaths,
      manifestKeys: this.manifestKeys,
      eventModules: this.eventModules,
      settingsModules: this.settingsModules,
      schemaURLs: this.schemaURLs,
    });
  }

  initModuleData(moduleData) {
    if (!this._modulesJSONLoaded) {
      let data = moduleData.deserialize({}, true);

      this.modules = data.modules;
      this.modulePaths = data.modulePaths;
      this.manifestKeys = data.manifestKeys;
      this.eventModules = new DefaultMap(() => new Set(), data.eventModules);
      this.settingsModules = new Set(data.settingsModules);
      this.schemaURLs = data.schemaURLs;
    }

    this._modulesJSONLoaded = true;
  }

  /**
   * Registers a set of ExtensionAPI modules to be lazily loaded and
   * managed by this manager.
   *
   * @param {object} obj
   *        An object containing property for eacy API module to be
   *        registered. Each value should be an object implementing the
   *        APIModule interface.
   */
  registerModules(obj) {
    for (let [name, details] of Object.entries(obj)) {
      details.namespaceName = name;

      if (this.modules.has(name)) {
        throw new Error(`Module '${name}' already registered`);
      }
      this.modules.set(name, details);

      if (details.schema) {
        let content =
          details.scopes &&
          (details.scopes.includes("content_parent") ||
            details.scopes.includes("content_child"));
        this.schemaURLs.set(details.schema, { content });
      }

      for (let event of details.events || []) {
        this.eventModules.get(event).add(name);
      }

      if (details.settings) {
        this.settingsModules.add(name);
      }

      for (let key of details.manifest || []) {
        if (this.manifestKeys.has(key)) {
          throw new Error(
            `Manifest key '${key}' already registered by '${this.manifestKeys.get(
              key
            )}'`
          );
        }

        this.manifestKeys.set(key, name);
      }

      for (let path of details.paths || []) {
        getPath(this.modulePaths, path).modules.add(name);
      }
    }
  }

  /**
   * Emits an `onManifestEntry` event for the top-level manifest entry
   * on all relevant {@link ExtensionAPI} instances for the given
   * extension.
   *
   * The API modules will be synchronously loaded if they have not been
   * loaded already.
   *
   * @param {Extension} extension
   *        The extension for which to emit the events.
   * @param {string} entry
   *        The name of the top-level manifest entry.
   *
   * @returns {*}
   */
  emitManifestEntry(extension, entry) {
    let apiName = this.manifestKeys.get(entry);
    if (apiName) {
      let api = extension.apiManager.getAPI(apiName, extension);
      return api.onManifestEntry(entry);
    }
  }
  /**
   * Emits an `onManifestEntry` event for the top-level manifest entry
   * on all relevant {@link ExtensionAPI} instances for the given
   * extension.
   *
   * The API modules will be asynchronously loaded if they have not been
   * loaded already.
   *
   * @param {Extension} extension
   *        The extension for which to emit the events.
   * @param {string} entry
   *        The name of the top-level manifest entry.
   *
   * @returns {Promise<*>}
   */
  async asyncEmitManifestEntry(extension, entry) {
    let apiName = this.manifestKeys.get(entry);
    if (apiName) {
      let api = await extension.apiManager.asyncGetAPI(apiName, extension);
      return api.onManifestEntry(entry);
    }
  }

  /**
   * Returns the {@link ExtensionAPI} instance for the given API module,
   * for the given extension, in the given scope, synchronously loading
   * and instantiating it if necessary.
   *
   * @param {string} name
   *        The name of the API module to load.
   * @param {Extension} extension
   *        The extension for which to load the API.
   * @param {string} [scope = null]
   *        The scope type for which to retrieve the API, or null if not
   *        being retrieved for a particular scope.
   *
   * @returns {ExtensionAPI?}
   */
  getAPI(name, extension, scope = null) {
    if (!this._checkGetAPI(name, extension, scope)) {
      return;
    }

    let apis = this.apis.get(extension);
    if (apis.has(name)) {
      return apis.get(name);
    }

    let module = this.loadModule(name);

    let api = new module(extension);
    apis.set(name, api);
    return api;
  }
  /**
   * Returns the {@link ExtensionAPI} instance for the given API module,
   * for the given extension, in the given scope, asynchronously loading
   * and instantiating it if necessary.
   *
   * @param {string} name
   *        The name of the API module to load.
   * @param {Extension} extension
   *        The extension for which to load the API.
   * @param {string} [scope = null]
   *        The scope type for which to retrieve the API, or null if not
   *        being retrieved for a particular scope.
   *
   * @returns {Promise<ExtensionAPI>?}
   */
  async asyncGetAPI(name, extension, scope = null) {
    if (!this._checkGetAPI(name, extension, scope)) {
      return;
    }

    let apis = this.apis.get(extension);
    if (apis.has(name)) {
      return apis.get(name);
    }

    let module = await this.asyncLoadModule(name);

    // Check again, because async.
    if (apis.has(name)) {
      return apis.get(name);
    }

    let api = new module(extension);
    apis.set(name, api);
    return api;
  }

  /**
   * Synchronously loads an API module, if not already loaded, and
   * returns its ExtensionAPI constructor.
   *
   * @param {string} name
   *        The name of the module to load.
   * @returns {typeof ExtensionAPI}
   */
  loadModule(name) {
    let module = this.modules.get(name);
    if (module.loaded) {
      return this.global[name];
    }

    this._checkLoadModule(module, name);

    this.initGlobal();

    Services.scriptloader.loadSubScript(module.url, this.global);

    module.loaded = true;

    return this.global[name];
  }
  /**
   * aSynchronously loads an API module, if not already loaded, and
   * returns its ExtensionAPI constructor.
   *
   * @param {string} name
   *        The name of the module to load.
   *
   * @returns {Promise<typeof ExtensionAPI>}
   */
  asyncLoadModule(name) {
    let module = this.modules.get(name);
    if (module.loaded) {
      return Promise.resolve(this.global[name]);
    }
    if (module.asyncLoaded) {
      return module.asyncLoaded;
    }

    this._checkLoadModule(module, name);

    module.asyncLoaded = ChromeUtils.compileScript(module.url).then(script => {
      this.initGlobal();
      script.executeInGlobal(this.global);

      module.loaded = true;

      return this.global[name];
    });

    return module.asyncLoaded;
  }

  asyncLoadSettingsModules() {
    return Promise.all(
      Array.from(this.settingsModules).map(apiName =>
        this.asyncLoadModule(apiName)
      )
    );
  }

  getModule(name) {
    return this.modules.get(name);
  }

  /**
   * Checks whether the given API module may be loaded for the given
   * extension, in the given scope.
   *
   * @param {string} name
   *        The name of the API module to check.
   * @param {Extension} extension
   *        The extension for which to check the API.
   * @param {string} [scope = null]
   *        The scope type for which to check the API, or null if not
   *        being checked for a particular scope.
   *
   * @returns {boolean}
   *        Whether the module may be loaded.
   */
  _checkGetAPI(name, extension, scope = null) {
    let module = this.getModule(name);
    if (!module) {
      // A module may not exist for a particular manifest version, but
      // we allow keys in the manifest.  An example is pageAction.
      return false;
    }

    if (
      module.permissions &&
      !module.permissions.some(perm => extension.hasPermission(perm))
    ) {
      return false;
    }

    if (!scope) {
      return true;
    }

    if (!module.scopes.includes(scope)) {
      return false;
    }

    if (!lazy.Schemas.checkPermissions(module.namespaceName, extension)) {
      return false;
    }

    return true;
  }

  _checkLoadModule(module, name) {
    if (!module) {
      throw new Error(`Module '${name}' does not exist`);
    }
    if (module.asyncLoaded) {
      throw new Error(`Module '${name}' currently being lazily loaded`);
    }
    if (this.global && this.global[name]) {
      throw new Error(
        `Module '${name}' conflicts with existing global property`
      );
    }
  }

  /**
   * Create a global object that is used as the shared global for all ext-*.js
   * scripts that are loaded via `loadScript`.
   *
   * @returns {object} A sandbox that is used as the global by `loadScript`.
   */
  _createExtGlobal() {
    let global = Cu.Sandbox(
      Services.scriptSecurityManager.getSystemPrincipal(),
      {
        wantXrays: false,
        wantGlobalProperties: ["ChromeUtils"],
        sandboxName: `Namespace of ext-*.js scripts for ${this.processType} (from: resource://gre/modules/ExtensionCommon.sys.mjs)`,
      }
    );

    Object.assign(global, {
      AppConstants,
      Cc,
      ChromeWorker,
      Ci,
      Cr,
      Cu,
      ExtensionAPI,
      ExtensionAPIPersistent,
      ExtensionCommon,
      IOUtils,
      MatchGlob,
      MatchPattern,
      MatchPatternSet,
      PathUtils,
      Services,
      StructuredCloneHolder,
      WebExtensionPolicy,
      XPCOMUtils,
      extensions: this,
      global,
    });

    ChromeUtils.defineLazyGetter(global, "console", getConsole);
    // eslint-disable-next-line mozilla/lazy-getter-object-name
    ChromeUtils.defineESModuleGetters(global, {
      ExtensionUtils: "resource://gre/modules/ExtensionUtils.sys.mjs",
    });

    return global;
  }

  initGlobal() {
    if (!this.global) {
      this.global = this._createExtGlobal();
    }
  }

  /**
   * Load an ext-*.js script. The script runs in its own scope, if it wishes to
   * share state with another script it can assign to the `global` variable. If
   * it wishes to communicate with this API manager, use `extensions`.
   *
   * @param {string} scriptUrl The URL of the ext-*.js script.
   */
  loadScript(scriptUrl) {
    // Create the object in the context of the sandbox so that the script runs
    // in the sandbox's context instead of here.
    let scope = Cu.createObjectIn(this.global);

    Services.scriptloader.loadSubScript(scriptUrl, scope);

    // Save the scope to avoid it being garbage collected.
    this._scriptScopes.push(scope);
  }
}

class LazyAPIManager extends SchemaAPIManager {
  constructor(processType, moduleData, schemaURLs) {
    super(processType);

    /** @type {Promise | boolean} */
    this.initialized = false;

    this.initModuleData(moduleData);

    this.schemaURLs = schemaURLs;
  }

  lazyInit() {}
}

defineLazyGetter(LazyAPIManager.prototype, "schema", function () {
  let root = new lazy.SchemaRoot(lazy.Schemas.rootSchema, this.schemaURLs);
  root.parseSchemas();
  return root;
});

class MultiAPIManager extends SchemaAPIManager {
  constructor(processType, children) {
    super(processType);

    this.initialized = false;

    this.children = children;
  }

  async lazyInit() {
    if (!this.initialized) {
      this.initialized = true;

      for (let child of this.children) {
        if (child.lazyInit) {
          let res = child.lazyInit();
          if (res && typeof res.then === "function") {
            await res;
          }
        }

        mergePaths(this.modulePaths, child.modulePaths);
      }
    }
  }

  onStartup(extension) {
    return Promise.all(this.children.map(child => child.onStartup(extension)));
  }

  getModule(name) {
    for (let child of this.children) {
      if (child.modules.has(name)) {
        return child.modules.get(name);
      }
    }
  }

  loadModule(name) {
    for (let child of this.children) {
      if (child.modules.has(name)) {
        return child.loadModule(name);
      }
    }
  }

  asyncLoadModule(name) {
    for (let child of this.children) {
      if (child.modules.has(name)) {
        return child.asyncLoadModule(name);
      }
    }
  }
}

defineLazyGetter(MultiAPIManager.prototype, "schema", function () {
  let bases = this.children.map(child => child.schema);

  // All API manager schema roots should derive from the global schema root,
  // so it doesn't need its own entry.
  if (bases[bases.length - 1] === lazy.Schemas) {
    bases.pop();
  }

  if (bases.length === 1) {
    bases = bases[0];
  }
  return new lazy.SchemaRoot(bases, new Map());
});

export function LocaleData(data) {
  this.defaultLocale = data.defaultLocale;
  this.selectedLocale = data.selectedLocale;
  this.locales = data.locales || new Map();
  this.warnedMissingKeys = new Set();

  /**
   * Map(locale-name -> Map(message-key -> localized-string))
   *
   * Contains a key for each loaded locale, each of which is a
   * Map of message keys to their localized strings.
   *
   * @type {Map<string, Map<string, string>>}
   */
  this.messages = data.messages || new Map();

  if (data.builtinMessages) {
    this.messages.set(this.BUILTIN, data.builtinMessages);
  }
}

LocaleData.prototype = {
  // Representation of the object to send to content processes. This
  // should include anything the content process might need.
  serialize() {
    return {
      defaultLocale: this.defaultLocale,
      selectedLocale: this.selectedLocale,
      messages: this.messages,
      locales: this.locales,
    };
  },

  BUILTIN: "@@BUILTIN_MESSAGES",

  has(locale) {
    return this.messages.has(locale);
  },

  // https://developer.chrome.com/extensions/i18n
  localizeMessage(message, substitutions = [], options = {}) {
    let defaultOptions = {
      defaultValue: "",
      cloneScope: null,
    };

    let locales = this.availableLocales;
    if (options.locale) {
      locales = new Set(
        [this.BUILTIN, options.locale, this.defaultLocale].filter(locale =>
          this.messages.has(locale)
        )
      );
    }

    options = Object.assign(defaultOptions, options);

    // Message names are case-insensitive, so normalize them to lower-case.
    message = message.toLowerCase();
    for (let locale of locales) {
      let messages = this.messages.get(locale);
      if (messages.has(message)) {
        let str = messages.get(message);

        if (!str.includes("$")) {
          return str;
        }

        if (!Array.isArray(substitutions)) {
          substitutions = [substitutions];
        }

        let replacer = (matched, index, dollarSigns) => {
          if (index) {
            // This is not quite Chrome-compatible. Chrome consumes any number
            // of digits following the $, but only accepts 9 substitutions. We
            // accept any number of substitutions.
            index = parseInt(index, 10) - 1;
            return index in substitutions ? substitutions[index] : "";
          }
          // For any series of contiguous `$`s, the first is dropped, and
          // the rest remain in the output string.
          return dollarSigns;
        };
        return str.replace(/\$(?:([1-9]\d*)|(\$+))/g, replacer);
      }
    }

    // Check for certain pre-defined messages.
    if (message == "@@ui_locale") {
      return this.uiLocale;
    } else if (message.startsWith("@@bidi_")) {
      let rtl = Services.locale.isAppLocaleRTL;

      if (message == "@@bidi_dir") {
        return rtl ? "rtl" : "ltr";
      } else if (message == "@@bidi_reversed_dir") {
        return rtl ? "ltr" : "rtl";
      } else if (message == "@@bidi_start_edge") {
        return rtl ? "right" : "left";
      } else if (message == "@@bidi_end_edge") {
        return rtl ? "left" : "right";
      }
    }

    if (!this.warnedMissingKeys.has(message)) {
      let error = `Unknown localization message ${message}`;
      if (options.cloneScope) {
        error = new options.cloneScope.Error(error);
      }
      Cu.reportError(error);
      this.warnedMissingKeys.add(message);
    }
    return options.defaultValue;
  },

  // Localize a string, replacing all |__MSG_(.*)__| tokens with the
  // matching string from the current locale, as determined by
  // |this.selectedLocale|.
  //
  // This may not be called before calling either |initLocale| or
  // |initAllLocales|.
  localize(str, locale = this.selectedLocale) {
    if (!str) {
      return str;
    }

    return str.replace(/__MSG_([A-Za-z0-9@_]+?)__/g, (matched, message) => {
      return this.localizeMessage(message, [], {
        locale,
        defaultValue: matched,
      });
    });
  },

  // Validates the contents of a locale JSON file, normalizes the
  // messages into a Map of message key -> localized string pairs.
  addLocale(locale, messages, extension) {
    let result = new Map();

    let isPlainObject = obj =>
      obj &&
      typeof obj === "object" &&
      ChromeUtils.getClassName(obj) === "Object";

    // Chrome does not document the semantics of its localization
    // system very well. It handles replacements by pre-processing
    // messages, replacing |$[a-zA-Z0-9@_]+$| tokens with the value of their
    // replacements. Later, it processes the resulting string for
    // |$[0-9]| replacements.
    //
    // Again, it does not document this, but it accepts any number
    // of sequential |$|s, and replaces them with that number minus
    // 1. It also accepts |$| followed by any number of sequential
    // digits, but refuses to process a localized string which
    // provides more than 9 substitutions.
    if (!isPlainObject(messages)) {
      extension.packagingError(`Invalid locale data for ${locale}`);
      return result;
    }

    for (let key of Object.keys(messages)) {
      let msg = messages[key];

      if (!isPlainObject(msg) || typeof msg.message != "string") {
        extension.packagingError(
          `Invalid locale message data for ${locale}, message ${JSON.stringify(
            key
          )}`
        );
        continue;
      }

      // Substitutions are case-insensitive, so normalize all of their names
      // to lower-case.
      let placeholders = new Map();
      if ("placeholders" in msg && isPlainObject(msg.placeholders)) {
        for (let key of Object.keys(msg.placeholders)) {
          placeholders.set(key.toLowerCase(), msg.placeholders[key]);
        }
      }

      let replacer = (match, name) => {
        let replacement = placeholders.get(name.toLowerCase());
        if (isPlainObject(replacement) && "content" in replacement) {
          return replacement.content;
        }
        return "";
      };

      let value = msg.message.replace(/\$([A-Za-z0-9@_]+)\$/g, replacer);

      // Message names are also case-insensitive, so normalize them to lower-case.
      result.set(key.toLowerCase(), value);
    }

    this.messages.set(locale, result);
    return result;
  },

  get acceptLanguages() {
    let result = Services.prefs.getComplexValue(
      "intl.accept_languages",
      Ci.nsIPrefLocalizedString
    ).data;
    return result.split(/\s*,\s*/g);
  },

  get uiLocale() {
    return Services.locale.appLocaleAsBCP47;
  },

  get availableLocales() {
    const locales = [this.BUILTIN, this.selectedLocale, this.defaultLocale];
    const value = new Set(locales.filter(locale => this.messages.has(locale)));
    return redefineGetter(this, "availableLocales", value);
  },
};

/**
 * This is a generic class for managing event listeners.
 *
 * @example
 * new EventManager({
 *   context,
 *   name: "api.subAPI",
 *   register:  fire => {
 *     let listener = (...) => {
 *       // Fire any listeners registered with addListener.
 *       fire.async(arg1, arg2);
 *     };
 *     // Register the listener.
 *     SomehowRegisterListener(listener);
 *     return () => {
 *       // Return a way to unregister the listener.
 *       SomehowUnregisterListener(listener);
 *     };
 *   }
 * }).api()
 *
 * The result is an object with addListener, removeListener, and
 * hasListener methods. `context` is an add-on scope (either an
 * ExtensionContext in the chrome process or ExtensionContext in a
 * content process).
 */
class EventManager {
  /*
   * A persistent event must provide module and name.  Additionally the
   * module must implement primeListeners in the ExtensionAPI class.
   *
   * A startup blocking event must also add the startupBlocking flag in
   * ext-toolkit.json or ext-browser.json.
   *
   * Listeners synchronously added from a background extension context
   * will be persisted, for a persistent background script only the
   * "startup blocking" events will be persisted.
   *
   * EventManager instances created in a child process can't persist any listener.
   *
   * @param {object} params
   *        Parameters that control this EventManager.
   * @param {BaseContext} params.context
   *        An object representing the extension instance using this event.
   * @param {string} params.module
   *        The API module name, required for persistent events.
   * @param {string} params.event
   *        The API event name, required for persistent events.
   * @param {ExtensionAPI} params.extensionApi
   *        The API intance.  If the API uses the ExtensionAPIPersistent class, some simplification is
   *        possible by passing the api (self or this) and the internal register function will be used.
   * @param {string} [params.name]
   *        A name used only for debugging.  If not provided, name is built from module and event.
   * @param {functon} params.register
   *        A function called whenever a new listener is added.
   * @param {boolean} [params.inputHandling=false]
   *        If true, the "handling user input" flag is set while handlers
   *        for this event are executing.
   */
  constructor(params) {
    let {
      context,
      module,
      event,
      name,
      register,
      extensionApi,
      inputHandling = false,
      resetIdleOnEvent = true,
    } = params;
    this.context = context;
    this.module = module;
    this.event = event;
    this.name = name;
    this.register = register;
    this.inputHandling = inputHandling;
    this.resetIdleOnEvent = resetIdleOnEvent;

    const isBackgroundParent =
      this.context.envType === "addon_parent" &&
      this.context.isBackgroundContext;

    // TODO(Bug 1844041): ideally we should restrict resetIdleOnEvent to
    // EventManager instances that belongs to the event page, but along
    // with that we should consider if calling sendMessage from an event
    // page should also reset idle timer, and so in the shorter term
    // here we are allowing listeners from other extension pages to
    // also reset the idle timer.
    const isAddonContext = ["addon_parent", "addon_child"].includes(
      this.context.envType
    );

    // Avoid resetIdleOnEvent overhead by only consider it when applicable.
    if (!isAddonContext || context.extension.persistentBackground) {
      this.resetIdleOnEvent = false;
    }

    if (!name) {
      this.name = `${module}.${event}`;
    }

    if (!this.register && extensionApi instanceof ExtensionAPIPersistent) {
      this.register = (fire, ...params) => {
        return extensionApi.registerEventListener(
          { context, event, fire },
          params
        );
      };
    }
    if (!this.register) {
      throw new Error(
        `EventManager requires register method for ${this.name}.`
      );
    }

    this.canPersistEvents = module && event && isBackgroundParent;

    if (this.canPersistEvents) {
      let { extension } = context;
      if (extension.persistentBackground) {
        // Persistent backgrounds will only persist startup blocking APIs.
        let api_module = extension.apiManager.getModule(this.module);
        if (!api_module?.startupBlocking) {
          this.canPersistEvents = false;
        }
      } else {
        // Event pages will persist all APIs that implement primeListener.
        // The api is already loaded so this does not have performance effect.
        let api = extension.apiManager.getAPI(
          this.module,
          extension,
          "addon_parent"
        );

        // If the api doesn't implement primeListener we do not persist the events.
        if (!api?.primeListener) {
          this.canPersistEvents = false;
        }
      }
    }

    this.unregister = new Map();
    this.remove = new Map();
  }

  /*
   * Information about listeners to persistent events is associated with
   * the extension to which they belong.  Any extension thas has such
   * listeners has a property called `persistentListeners` that is a
   * 3-level Map:
   *
   * - the first 2 keys are the module name (e.g., webRequest)
   *   and the name of the event within the module (e.g., onBeforeRequest).
   *
   * - the third level of the map is used to track multiple listeners for
   *   the same event, these listeners are distinguished by the extra arguments
   *   passed to addListener()
   *
   * - for quick lookups, the key to the third Map is the result of calling
   *   uneval() on the array of extra arguments.
   *
   * - the value stored in the Map or persistent listeners we keep in memory
   *   is a plain object with:
   *   - a property called `params` that is the original (ie, not uneval()ed)
   *     extra arguments to addListener()
   *   - and a property called `listeners` that is an array of plain object
   *     each representing a listener to be primed and a `primeId` autoincremented
   *     integer that represents each of the primed listeners that belongs to the
   *     group listeners with the same set of extra params.
   *   - a `nextPrimeId` property keeps track of the numeric primeId that should
   *     be assigned to new persistent listeners added for the same event and
   *     same set of extra params.
   *
   * For a primed listener (i.e., the stub listener created during browser startup
   * before the extension background page is started, and after an event page is
   * suspended on idle), the object will be later populated (by the callers of
   * EventManager.primeListeners) with an additional `primed` property that serves
   * as a placeholder listener, collecting all events that got emitted while the
   * background page was not yet started, and eventually replaced by a callback
   * registered from the extension code, once the background page scripts have been
   * executed (or dropped if the background page scripts do not register the same
   * listener anymore).
   *
   * @param {Extension} extension
   * @returns {boolean} True if the extension had any persistent listeners.
   */
  static _initPersistentListeners(extension) {
    if (extension.persistentListeners) {
      return !!extension.persistentListeners.size;
    }

    let listeners = new DefaultMap(() => new DefaultMap(() => new Map()));
    extension.persistentListeners = listeners;

    let persistentListeners = extension.startupData?.persistentListeners;
    if (!persistentListeners) {
      return false;
    }

    let found = false;
    for (let [module, savedModuleEntry] of Object.entries(
      persistentListeners
    )) {
      for (let [event, savedEventEntry] of Object.entries(savedModuleEntry)) {
        for (let paramList of savedEventEntry) {
          /* Before Bug 1795801 (Firefox < 113) each entry was related to a listener
           * registered with a different set of extra params (and so only one listener
           * could be persisted for the same set of extra params)
           *
           * After Bug 1795801 (Firefox >= 113) each entry still represents a listener
           * registered for that event, but multiple listeners registered with the same
           * set of extra params will be captured as multiple entries in the
           * paramsList array.
           *
           * NOTE: persisted listeners are stored in the startupData part of the Addon DB
           * and are expected to be preserved across Firefox and Addons upgrades and downgrades
           * (unlike the WebExtensions startupCache data which is cleared when Firefox or the
           * addon is updated) and so we are taking special care about forward and backward
           * compatibility of the persistentListeners on-disk format:
           *
           * - forward compatibility: when this new version of this startupData loading logic
           *   is loading the old persistentListeners on-disk format:
           *   - on the first run only one listener will be primed for each of the extra params
           *     recorded in the startupData (same as in older Firefox versions)
           *     and Bug 1795801 will still be hit, but once the background
           *     context is started once the startupData will be updated to
           *     include each of the listeners (indipendently if the set of
           *     extra params is the same as another listener already been
           *     persisted).
           *   - after the first run, all listeners will be primed separately, even if the extra
           *     params are the same as other listeners already primed, and so
           *     each of the listener will receive the pending events collected
           *     by their related primed listener and Bug 1795801 not to be hit anymore.
           *
           * - backward compatibility: when the old version of this startupData loading logic
           *   (https://searchfox.org/mozilla-central/rev/cd2121e7d8/toolkit/components/extensions/ExtensionCommon.jsm#2360-2371)
           *   is loading the new persistentListeners on-disk format, the last
           *   entry with the same set of extra params will be eventually overwritting the
           *   entry for another primed listener with the same extra params, Bug 1795801 will still
           *   be hit, but no actual change in behavior is expected.
           */
          let key = uneval(paramList);
          const eventEntry = listeners.get(module).get(event);

          if (eventEntry.has(key)) {
            const keyEntry = eventEntry.get(key);
            let primeId = keyEntry.nextPrimeId;
            keyEntry.listeners.push({ primeId });
            keyEntry.nextPrimeId++;
          } else {
            eventEntry.set(key, {
              params: paramList,
              nextPrimeId: 1,
              listeners: [{ primeId: 0 }],
            });
          }
          found = true;
        }
      }
    }
    return found;
  }

  // Extract just the information needed at startup for all persistent
  // listeners, and arrange for it to be saved.  This should be called
  // whenever the set of persistent listeners for an extension changes.
  static _writePersistentListeners(extension) {
    let startupListeners = {};
    for (let [module, moduleEntry] of extension.persistentListeners) {
      startupListeners[module] = {};
      for (let [event, eventEntry] of moduleEntry) {
        // Turn the per-event entries from the format they are being kept
        // in memory:
        //
        //   [
        //     { params: paramList1, listeners: [listener1, listener2, ...] },
        //     { params: paramList2, listeners: [listener3, listener3, ...] },
        //     ...
        //   ]
        //
        // into the format used for storing them on disk (in the startupData),
        // which is an array of the params for each listener (with the param list
        // included as many times as many listeners are persisted for the same
        // set of params):
        //
        //   [paramList1, paramList1, ..., paramList2, paramList2, ...]
        //
        // This format will also work as expected on older Firefox versions where
        // only one listener was being persisted for each set of params.
        startupListeners[module][event] = Array.from(
          eventEntry.values()
        ).flatMap(keyEntry => keyEntry.listeners.map(() => keyEntry.params));
      }
    }

    extension.startupData.persistentListeners = startupListeners;
    extension.saveStartupData();
  }

  // Set up "primed" event listeners for any saved event listeners
  // in an extension's startup data.
  // This function is only called during browser startup, it stores details
  // about all primed listeners in the extension's persistentListeners Map.
  static primeListeners(extension, isInStartup = false) {
    if (!EventManager._initPersistentListeners(extension)) {
      return;
    }

    for (let [module, moduleEntry] of extension.persistentListeners) {
      // If we're in startup, we only want to continue attempting to prime a
      // subset of events that should be startup blocking.
      if (isInStartup) {
        let api_module = extension.apiManager.getModule(module);
        if (!api_module.startupBlocking) {
          continue;
        }
      }

      let api = extension.apiManager.getAPI(module, extension, "addon_parent");

      // If an extension is upgraded and a permission, such as webRequest, is
      // removed, we will have been called but the API is no longer available.
      if (!api?.primeListener) {
        // The runtime module no longer implements primed listeners, drop them.
        extension.persistentListeners.delete(module);
        EventManager._writePersistentListeners(extension);
        continue;
      }
      for (let [event, eventEntry] of moduleEntry) {
        for (let [key, { params, listeners }] of eventEntry) {
          for (let listener of listeners) {
            // Reset the `listener.added` flag by setting it to `false` while
            // re-priming the listeners because the event page has suspended
            // and the previous converted listener is no longer listening.
            const listenerWasAdded = listener.added;
            listener.added = false;
            listener.params = params;
            let primed = { pendingEvents: [] };

            let fireEvent = (...args) =>
              new Promise((resolve, reject) => {
                if (!listener.primed) {
                  reject(
                    new Error(
                      `primed listener ${module}.${event} not re-registered`
                    )
                  );
                  return;
                }
                primed.pendingEvents.push({ args, resolve, reject });
                extension.emit("background-script-event");
              });

            let fire = {
              wakeup: () => extension.wakeupBackground(),
              sync: fireEvent,
              async: fireEvent,
              // fire.async for ProxyContextParent is already not cloning.
              raw: fireEvent,
            };

            try {
              let handler = api.primeListener(
                event,
                fire,
                listener.params,
                isInStartup
              );
              if (handler) {
                listener.primed = primed;
                Object.assign(primed, handler);
              }
            } catch (e) {
              Cu.reportError(
                `Error priming listener ${module}.${event}: ${e} :: ${e.stack}`
              );
              // Force this listener to be cleared.
              listener.error = true;
            }

            // If an attempt to prime a listener failed, ensure it is cleared now.
            // If a module is a startup blocking module, not all listeners may
            // get primed during early startup.  For that reason, we don't clear
            // persisted listeners during early startup.  At the end of background
            // execution any listeners that were not renewed will be cleared.
            //
            // TODO(Bug 1797474): consider priming runtime.onStartup and
            // avoid to special handling it here.
            if (
              listener.error ||
              (!isInStartup &&
                !(
                  (`${module}.${event}` === "runtime.onStartup" &&
                    listenerWasAdded) ||
                  listener.primed
                ))
            ) {
              EventManager.clearPersistentListener(
                extension,
                module,
                event,
                key,
                listener.primeId
              );
            }
          }
        }
      }
    }
  }

  /**
   * This is called as a result of background script startup-finished and shutdown.
   *
   * After startup, it removes any remaining primed listeners.  These exist if the
   * listener was not renewed during startup.  In this case the persisted listener
   * data is also removed.
   *
   * During shutdown, care should be taken to set clearPersistent to false.
   * persisted listener data should NOT be cleared during shutdown.
   *
   * @param {Extension} extension
   * @param {boolean} clearPersistent whether the persisted listener data should be cleared.
   */
  static clearPrimedListeners(extension, clearPersistent = true) {
    if (!extension.persistentListeners) {
      return;
    }

    for (let [module, moduleEntry] of extension.persistentListeners) {
      for (let [event, eventEntry] of moduleEntry) {
        for (let [key, { listeners }] of eventEntry) {
          for (let listener of listeners) {
            let { primed, added, primeId } = listener;
            // When a primed listener is added or renewed during initial
            // background execution we set an added flag.  If it was primed
            // when added, primed is set to null.
            if (added) {
              continue;
            }

            if (primed) {
              // When a primed listener was not renewed, primed will still be truthy.
              // These need to be cleared on shutdown (important for event pages), but
              // we only clear the persisted listener data after the startup of a background.
              // Release any pending events and unregister the primed handler.
              listener.primed = null;

              for (let evt of primed.pendingEvents) {
                evt.reject(new Error("listener not re-registered"));
              }
              primed.unregister();
            }

            // Clear any persisted events that were not renewed, should typically
            // only be done at the end of the background page load.
            if (clearPersistent) {
              EventManager.clearPersistentListener(
                extension,
                module,
                event,
                key,
                primeId
              );
            }
          }
        }
      }
    }
  }

  // Record the fact that there is a listener for the given event in
  // the given extension.  `args` is an Array containing any extra
  // arguments that were passed to addListener().
  static savePersistentListener(extension, module, event, args = []) {
    EventManager._initPersistentListeners(extension);
    let key = uneval(args);
    const eventEntry = extension.persistentListeners.get(module).get(event);

    let primeId;
    if (!eventEntry.has(key)) {
      // when writing, only args are written, other properties are dropped
      primeId = 0;
      eventEntry.set(key, {
        params: args,
        listeners: [{ added: true, primeId }],
        nextPrimeId: 1,
      });
    } else {
      const keyEntry = eventEntry.get(key);
      primeId = keyEntry.nextPrimeId;
      keyEntry.listeners.push({ added: true, primeId });
      keyEntry.nextPrimeId = primeId + 1;
    }

    EventManager._writePersistentListeners(extension);
    return [module, event, key, primeId];
  }

  // Remove the record for the given event listener from the extension's
  // startup data.  `key` must be a string, the result of calling uneval()
  // on the array of extra arguments originally passed to addListener().
  static clearPersistentListener(
    extension,
    module,
    event,
    key = uneval([]),
    primeId = undefined
  ) {
    let eventEntry = extension.persistentListeners.get(module).get(event);

    let keyEntry = eventEntry.get(key);

    if (primeId != undefined && keyEntry) {
      keyEntry.listeners = keyEntry.listeners.filter(
        listener => listener.primeId !== primeId
      );
    }

    if (primeId == undefined || keyEntry?.listeners.length === 0) {
      eventEntry.delete(key);
      if (eventEntry.size == 0) {
        let moduleEntry = extension.persistentListeners.get(module);
        moduleEntry.delete(event);
        if (moduleEntry.size == 0) {
          extension.persistentListeners.delete(module);
        }
      }
    }

    EventManager._writePersistentListeners(extension);
  }

  addListener(callback, ...args) {
    if (this.unregister.has(callback)) {
      return;
    }
    this.context.logActivity("api_call", `${this.name}.addListener`, { args });

    let shouldFire = () => {
      if (this.context.unloaded) {
        dump(`${this.name} event fired after context unloaded.\n`);
      } else if (!this.context.active) {
        dump(`${this.name} event fired while context is inactive.\n`);
      } else if (this.unregister.has(callback)) {
        return true;
      }
      return false;
    };

    let { extension } = this.context;
    const resetIdle = () => {
      if (this.resetIdleOnEvent) {
        extension?.emit("background-script-reset-idle", {
          reason: "event",
          eventName: this.name,
        });
      }
    };

    let fire = {
      // Bug 1754866 fire.sync doesn't match documentation.
      sync: (...args) => {
        if (shouldFire()) {
          resetIdle();
          let result = this.context.applySafe(callback, args);
          this.context.logActivity("api_event", this.name, { args, result });
          return result;
        }
      },
      async: (...args) => {
        return Promise.resolve().then(() => {
          if (shouldFire()) {
            resetIdle();
            let result = this.context.applySafe(callback, args);
            this.context.logActivity("api_event", this.name, { args, result });
            return result;
          }
        });
      },
      raw: (...args) => {
        if (!shouldFire()) {
          throw new Error("Called raw() on unloaded/inactive context");
        }
        resetIdle();
        let result = Reflect.apply(callback, null, args);
        this.context.logActivity("api_event", this.name, { args, result });
        return result;
      },
      asyncWithoutClone: (...args) => {
        return Promise.resolve().then(() => {
          if (shouldFire()) {
            resetIdle();
            let result = this.context.applySafeWithoutClone(callback, args);
            this.context.logActivity("api_event", this.name, { args, result });
            return result;
          }
        });
      },
    };

    let { module, event } = this;

    let unregister = null;
    let recordStartupData = false;

    // If this is a persistent event, check for a listener that was already
    // created during startup.  If there is one, use it and don't create a
    // new one.
    if (this.canPersistEvents) {
      // Once a background is started, listenerPromises is set to null. At
      // that point, we stop recording startup data.
      recordStartupData = !!this.context.listenerPromises;

      let key = uneval(args);
      EventManager._initPersistentListeners(extension);
      let keyEntry = extension.persistentListeners
        .get(module)
        .get(event)
        .get(key);

      // Get the first persistent listener which matches the module, event and extra arguments
      // and not added back by the extension yet, the persistent listener found may be either
      // primed or not (in particular API Events that belongs to APIs that should not be blocking
      // startup may have persistent listeners that are not primed during the first execution
      // of the background context happening as part of the applications startup, whereas they
      // will be primed when the background context will be suspended on the idle timeout).
      let listener = keyEntry?.listeners.find(listener => !listener.added);
      if (listener) {
        // During startup only a subset of persisted listeners are primed.  As
        // well, each API determines whether to prime a specific listener.
        let { primed } = listener;
        if (primed) {
          listener.primed = null;

          primed.convert(fire, this.context);
          unregister = primed.unregister;

          for (let evt of primed.pendingEvents) {
            evt.resolve(fire.async(...evt.args));
          }
        }
        listener.added = true;

        recordStartupData = false;
        this.remove.set(callback, () => {
          EventManager.clearPersistentListener(
            extension,
            module,
            event,
            uneval(args),
            listener.primeId
          );
        });
      }
    }

    if (!unregister) {
      unregister = this.register(fire, ...args);
    }

    this.unregister.set(callback, unregister);
    this.context.callOnClose(this);

    // If this is a new listener for a persistent event, record
    // the details for subsequent startups.
    if (recordStartupData) {
      const [, , , /* _module */ /* _event */ /* _key */ primeId] =
        EventManager.savePersistentListener(extension, module, event, args);
      this.remove.set(callback, () => {
        EventManager.clearPersistentListener(
          extension,
          module,
          event,
          uneval(args),
          primeId
        );
      });
    }
  }

  removeListener(callback, clearPersistentListener = true) {
    if (!this.unregister.has(callback)) {
      return;
    }
    this.context.logActivity("api_call", `${this.name}.removeListener`, {
      args: [],
    });

    let unregister = this.unregister.get(callback);
    this.unregister.delete(callback);
    try {
      unregister();
    } catch (e) {
      Cu.reportError(e);
    }

    if (clearPersistentListener && this.remove.has(callback)) {
      let cleanup = this.remove.get(callback);
      this.remove.delete(callback);
      cleanup();
    }

    if (this.unregister.size == 0) {
      this.context.forgetOnClose(this);
    }
  }

  hasListener(callback) {
    return this.unregister.has(callback);
  }

  revoke() {
    for (let callback of this.unregister.keys()) {
      this.removeListener(callback, false);
    }
  }

  close() {
    this.revoke();
  }

  api() {
    return {
      addListener: (...args) => this.addListener(...args),
      removeListener: (...args) => this.removeListener(...args),
      hasListener: (...args) => this.hasListener(...args),
      setUserInput: this.inputHandling,
      [lazy.Schemas.REVOKE]: () => this.revoke(),
    };
  }
}

// Simple API for event listeners where events never fire.
function ignoreEvent(context, name) {
  return {
    addListener: function () {
      let id = context.extension.id;
      let frame = Components.stack.caller;
      let msg = `In add-on ${id}, attempting to use listener "${name}", which is unimplemented.`;
      let scriptError = Cc["@mozilla.org/scripterror;1"].createInstance(
        Ci.nsIScriptError
      );
      scriptError.init(
        msg,
        frame.filename,
        null,
        frame.lineNumber,
        frame.columnNumber,
        Ci.nsIScriptError.warningFlag,
        "content javascript"
      );
      Services.console.logMessage(scriptError);
    },
    removeListener: function () {},
    hasListener: function () {},
  };
}

const stylesheetMap = new DefaultMap(url => {
  let uri = Services.io.newURI(url);
  return lazy.styleSheetService.preloadSheet(
    uri,
    // Note: keep in sync with ext-browser-content.js. This used to be
    // AGENT_SHEET, but changed to AUTHOR_SHEET, see bug 1873024.
    lazy.styleSheetService.AUTHOR_SHEET
  );
});

/**
 * Updates the in-memory representation of extension host permissions, i.e.
 * policy.allowedOrigins.
 *
 * @param {WebExtensionPolicy} policy
 *        A policy. All MatchPattern instances in policy.allowedOrigins are
 *        expected to have been constructed with ignorePath: true.
 * @param {string[]} origins
 *        A list of already-normalized origins, equivalent to using the
 *        MatchPattern constructor with ignorePath: true.
 * @param {boolean} isAdd
 *        Whether to add instead of removing the host permissions.
 */
function updateAllowedOrigins(policy, origins, isAdd) {
  if (!origins.length) {
    // Nothing to modify.
    return;
  }
  let patternMap = new Map();
  for (let pattern of policy.allowedOrigins.patterns) {
    patternMap.set(pattern.pattern, pattern);
  }
  if (!isAdd) {
    for (let origin of origins) {
      patternMap.delete(origin);
    }
  } else {
    // In the parent process, policy.extension.restrictSchemes is available.
    // In the content process, we need to check the mozillaAddons permission,
    // which is only available if approved by the parent.
    const restrictSchemes =
      policy.extension?.restrictSchemes ??
      policy.hasPermission("mozillaAddons");
    for (let origin of origins) {
      if (patternMap.has(origin)) {
        continue;
      }
      patternMap.set(
        origin,
        new MatchPattern(origin, { restrictSchemes, ignorePath: true })
      );
    }
  }
  // patternMap contains only MatchPattern instances, so we don't need to set
  // the options parameter (with restrictSchemes, etc.) since that is only used
  // if the input is a string.
  policy.allowedOrigins = new MatchPatternSet(Array.from(patternMap.values()));
}

export var ExtensionCommon = {
  BaseContext,
  CanOfAPIs,
  EventManager,
  ExtensionAPI,
  ExtensionAPIPersistent,
  EventEmitter,
  LocalAPIImplementation,
  LocaleData,
  NoCloneSpreadArgs,
  SchemaAPIInterface,
  SchemaAPIManager,
  SpreadArgs,
  checkLoadURI,
  checkLoadURL,
  defineLazyGetter,
  redefineGetter,
  getConsole,
  ignoreEvent,
  instanceOf,
  makeWidgetId,
  normalizeTime,
  runSafeSyncWithoutClone,
  stylesheetMap,
  updateAllowedOrigins,
  withHandlingUserInput,

  MultiAPIManager,
  LazyAPIManager,
};