mirror of
https://github.com/lightpanda-io/browser.git
synced 2026-03-29 16:10:04 +00:00
Compare commits
2385 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
060afcd459 | ||
|
|
5d1522a61f | ||
|
|
b1b54afc56 | ||
|
|
2abc490732 | ||
|
|
d4807df2e9 | ||
|
|
d5f4ca15cc | ||
|
|
e642c85ebd | ||
|
|
7ea0cdba36 | ||
|
|
612b3a26b7 | ||
|
|
56d89895a8 | ||
|
|
21d502b81f | ||
|
|
dd3de6efea | ||
|
|
d934fe6d4e | ||
|
|
dab6345885 | ||
|
|
39874137d6 | ||
|
|
89f215c3ee | ||
|
|
408d3f0a53 | ||
|
|
a010684ce9 | ||
|
|
a4a98da4a4 | ||
|
|
6f30d459d5 | ||
|
|
71f27a55e1 | ||
|
|
c92903aae5 | ||
|
|
518e0aa07a | ||
|
|
b908b0bf8a | ||
|
|
f9fa5be324 | ||
|
|
8ec6bb1577 | ||
|
|
70f8c53703 | ||
|
|
6d5a984413 | ||
|
|
5fa8fbc6f8 | ||
|
|
7050d5fc68 | ||
|
|
6af9d12f71 | ||
|
|
a54e1db784 | ||
|
|
2319b0fda5 | ||
|
|
6864a22721 | ||
|
|
c9d0e2097d | ||
|
|
d8f7eb3f24 | ||
|
|
90ee919f45 | ||
|
|
ddc6431720 | ||
|
|
2ea6557fb7 | ||
|
|
15358c1928 | ||
|
|
d65025b3cb | ||
|
|
54fa3bc054 | ||
|
|
68f5fa738c | ||
|
|
2ea57ba979 | ||
|
|
1acc0b0dc8 | ||
|
|
645ec79fce | ||
|
|
97e897e80e | ||
|
|
6f72eeae65 | ||
|
|
a845b2e35e | ||
|
|
b164ffeb95 | ||
|
|
7ba34af884 | ||
|
|
7f543ac7c8 | ||
|
|
a1bf92c07f | ||
|
|
0b221615b7 | ||
|
|
f81a9b54a7 | ||
|
|
05da040ce1 | ||
|
|
b911051842 | ||
|
|
a67f46b550 | ||
|
|
dcde19de3c | ||
|
|
a8b4e8c1bc | ||
|
|
7b0e256408 | ||
|
|
5a974f0d77 | ||
|
|
f7fe8d00fb | ||
|
|
946b6d8226 | ||
|
|
25366f0e47 | ||
|
|
562e8e8d87 | ||
|
|
11ff9ed366 | ||
|
|
9a9f2ab94b | ||
|
|
27048fb06d | ||
|
|
e103ee1ffa | ||
|
|
acebbb9041 | ||
|
|
0264c94426 | ||
|
|
88de72a9ea | ||
|
|
9306adc786 | ||
|
|
43c30f8a34 | ||
|
|
7c7240d5ab | ||
|
|
169582c992 | ||
|
|
7b74161e9c | ||
|
|
633e98c8f4 | ||
|
|
5743c4fc93 | ||
|
|
9984b3445f | ||
|
|
90a7e96181 | ||
|
|
00d4ac6137 | ||
|
|
ee432c54b8 | ||
|
|
76ec3eb738 | ||
|
|
37832c63a4 | ||
|
|
d1c33f0872 | ||
|
|
4684b8611d | ||
|
|
f4961ee8b2 | ||
|
|
27f6f4243f | ||
|
|
dcf1d34889 | ||
|
|
76f30dc985 | ||
|
|
2d6c37fa6f | ||
|
|
3e52abf471 | ||
|
|
d697944b5a | ||
|
|
cf14b9e762 | ||
|
|
121cf40062 | ||
|
|
abc89b7eae | ||
|
|
dc33c4d5fd | ||
|
|
087086c308 | ||
|
|
05cb5221d4 | ||
|
|
0fff379ee0 | ||
|
|
0c23818470 | ||
|
|
25dbac9945 | ||
|
|
b379b775f9 | ||
|
|
7cc2c2344e | ||
|
|
d50f6b830a | ||
|
|
8f2921f61f | ||
|
|
e9ec089f76 | ||
|
|
dca99c338e | ||
|
|
cc3a498294 | ||
|
|
c88cb35b84 | ||
|
|
8be7a9f2bc | ||
|
|
899567328e | ||
|
|
9f3cb4349d | ||
|
|
b2b890b8b1 | ||
|
|
f266dbc171 | ||
|
|
b28ac8ca19 | ||
|
|
248ce4f1a8 | ||
|
|
872ec33662 | ||
|
|
b3e6186c78 | ||
|
|
a31497937b | ||
|
|
90088c5d7c | ||
|
|
4c8abd4680 | ||
|
|
a25fb4a8e4 | ||
|
|
29efb467f0 | ||
|
|
ffe2bc9a02 | ||
|
|
8105dff167 | ||
|
|
8d992d74c0 | ||
|
|
296fa2a2f4 | ||
|
|
a9e6051867 | ||
|
|
0fcb316837 | ||
|
|
c0704f822b | ||
|
|
ba974f695d | ||
|
|
3ca82b9ab5 | ||
|
|
df4e5d859f | ||
|
|
67875036c5 | ||
|
|
83f008de1f | ||
|
|
7183b0339b | ||
|
|
9969ff7165 | ||
|
|
0ca97d01ac | ||
|
|
fc4dbb6184 | ||
|
|
9b16212d4b | ||
|
|
4d67cfa340 | ||
|
|
2bd38608e9 | ||
|
|
6ce117e5fa | ||
|
|
2b10b1c17a | ||
|
|
bbf58a2807 | ||
|
|
44ffcaeed8 | ||
|
|
a597d31505 | ||
|
|
6dbd008724 | ||
|
|
7d47f8623a | ||
|
|
7c755483b1 | ||
|
|
e387e005d8 | ||
|
|
c9f6cb7520 | ||
|
|
596ee82a52 | ||
|
|
79b62e0dfc | ||
|
|
e67cf21917 | ||
|
|
8fb1c3971c | ||
|
|
437df18a07 | ||
|
|
8215f2fd8f | ||
|
|
af7f51a647 | ||
|
|
3ab09d87f2 | ||
|
|
4c1d82162f | ||
|
|
3830e2610b | ||
|
|
e3265d400e | ||
|
|
d9c53a3def | ||
|
|
da32440a14 | ||
|
|
25ad3559f7 | ||
|
|
8fbd64955f | ||
|
|
32c83d166d | ||
|
|
d95b19d31b | ||
|
|
9e62e72d1f | ||
|
|
29259c23d7 | ||
|
|
3d6af216dc | ||
|
|
f475aa09e8 | ||
|
|
1278dc28cd | ||
|
|
33ee2fb1a0 | ||
|
|
2ac90262b7 | ||
|
|
bb1ea39c54 | ||
|
|
a087386af3 | ||
|
|
fe96bc7895 | ||
|
|
7a69e3fc9b | ||
|
|
566fa72bcd | ||
|
|
520e197e0e | ||
|
|
c15ef590c2 | ||
|
|
098eeea8f7 | ||
|
|
c3f8f9de54 | ||
|
|
ba4900b61f | ||
|
|
3e03f7559f | ||
|
|
46f8a11339 | ||
|
|
b3a0aaaeea | ||
|
|
aa5e71112e | ||
|
|
22303d2ae8 | ||
|
|
9dbfac02b2 | ||
|
|
6f43d9979d | ||
|
|
d63a045534 | ||
|
|
fe2d309d33 | ||
|
|
94ca2c41e4 | ||
|
|
8873e613d2 | ||
|
|
761b35b199 | ||
|
|
8a2641d213 | ||
|
|
e47091f9a1 | ||
|
|
ea399390ef | ||
|
|
d26869278f | ||
|
|
1639ff1b98 | ||
|
|
9b3107d4fe | ||
|
|
4bebc4c142 | ||
|
|
ac0601b141 | ||
|
|
6040cd3338 | ||
|
|
f93403d3dc | ||
|
|
82cd5d4bab | ||
|
|
0d3055716e | ||
|
|
c9b4067686 | ||
|
|
52dcc6765a | ||
|
|
eab328e2b5 | ||
|
|
23146f64ab | ||
|
|
a6d3a3d0ab | ||
|
|
5eb54bbc95 | ||
|
|
a4fa40743a | ||
|
|
6d8c6a947e | ||
|
|
13cf0096ad | ||
|
|
bd0f1d2884 | ||
|
|
5671580c2d | ||
|
|
669c934ae0 | ||
|
|
b568eb4e1e | ||
|
|
4d8d6c10c6 | ||
|
|
3667fbc49e | ||
|
|
269c880ee0 | ||
|
|
fe89aad621 | ||
|
|
38fb5b101e | ||
|
|
3d8b1abda4 | ||
|
|
0b141e44ae | ||
|
|
695ed817e4 | ||
|
|
f0d9d53588 | ||
|
|
471e94d58e | ||
|
|
7b6776345a | ||
|
|
68763d9a30 | ||
|
|
bead805680 | ||
|
|
34f0857b4f | ||
|
|
b25e46de2e | ||
|
|
86ae004825 | ||
|
|
a355d9e517 | ||
|
|
61aca85632 | ||
|
|
159165490d | ||
|
|
9c8299f13f | ||
|
|
27e58181fb | ||
|
|
02a0727870 | ||
|
|
7c9d7259e6 | ||
|
|
ddb83cf9c5 | ||
|
|
3662d1681e | ||
|
|
6534dc4c4f | ||
|
|
395f93240d | ||
|
|
ac85341cab | ||
|
|
01d71323fc | ||
|
|
ee7852665e | ||
|
|
9d7b80c1ac | ||
|
|
907298c6b1 | ||
|
|
cc53fec08d | ||
|
|
ab165d3f1f | ||
|
|
7c34cb5852 | ||
|
|
71d57c1e27 | ||
|
|
6a5e088c52 | ||
|
|
8ec9f634b4 | ||
|
|
0e4cfbfe6b | ||
|
|
370c3a49a7 | ||
|
|
a7e0110acb | ||
|
|
3769715582 | ||
|
|
0d8dd84df5 | ||
|
|
e98bb16255 | ||
|
|
6a098665fa | ||
|
|
47b4b68e60 | ||
|
|
53ccefc15c | ||
|
|
0e1b966dce | ||
|
|
9132bc2375 | ||
|
|
49c0e95664 | ||
|
|
97e920b68f | ||
|
|
3538c77b78 | ||
|
|
4bc4b2aeac | ||
|
|
38030c7d21 | ||
|
|
e74d45d6c2 | ||
|
|
0479813494 | ||
|
|
ef3ba13979 | ||
|
|
f82cfca2ee | ||
|
|
4b204265c9 | ||
|
|
fbb37633f0 | ||
|
|
09328aeb5a | ||
|
|
5284d75cb7 | ||
|
|
aac35ae868 | ||
|
|
65751a69ae | ||
|
|
121c49e9c3 | ||
|
|
0beae3b1a6 | ||
|
|
57ce4e16a9 | ||
|
|
9370e298d2 | ||
|
|
240e8b3502 | ||
|
|
eecadb3962 | ||
|
|
08d7f544dd | ||
|
|
a673eb89b6 | ||
|
|
f5d3dede6b | ||
|
|
e41d53019f | ||
|
|
637a105e5d | ||
|
|
8e16c587c8 | ||
|
|
1cde0bb8b8 | ||
|
|
61a1a2564e | ||
|
|
dd3781a1ea | ||
|
|
ff9f9bae1d | ||
|
|
aa3a402f70 | ||
|
|
c9882e10a4 | ||
|
|
7cb06f3e58 | ||
|
|
60c1f19581 | ||
|
|
b6420f75e2 | ||
|
|
45e74d3336 | ||
|
|
dc040dfc37 | ||
|
|
9071d98cbe | ||
|
|
74ffc273ef | ||
|
|
2a4cbbe569 | ||
|
|
63eeadad1d | ||
|
|
2de0d4bc48 | ||
|
|
c0da6994da | ||
|
|
568a4428ba | ||
|
|
4823e0b188 | ||
|
|
0690dd9550 | ||
|
|
b5eceb52fb | ||
|
|
c90e9c165b | ||
|
|
a61e87c5dd | ||
|
|
abd3ee9c5d | ||
|
|
3dd61aeb71 | ||
|
|
6a46a9ba47 | ||
|
|
fd39168106 | ||
|
|
6a48f6df25 | ||
|
|
e807c9b6be | ||
|
|
af8970bbb9 | ||
|
|
07931dd75f | ||
|
|
bfa2e6b4dd | ||
|
|
129b59a43f | ||
|
|
4b60f56e5f | ||
|
|
ee7c38045f | ||
|
|
d18253d50b | ||
|
|
c9b9ef9934 | ||
|
|
f968db63e9 | ||
|
|
92572c977b | ||
|
|
493c5b41f8 | ||
|
|
92ae2c46b6 | ||
|
|
613428c54c | ||
|
|
bde8b64ba3 | ||
|
|
e74a286d70 | ||
|
|
1e090f9d30 | ||
|
|
a1064a54cc | ||
|
|
dbd500cab9 | ||
|
|
0bc0a38704 | ||
|
|
9f587ab24b | ||
|
|
8858f889b4 | ||
|
|
833a33678c | ||
|
|
34c10e1e48 | ||
|
|
8ce8c7a0f3 | ||
|
|
94bcb30f11 | ||
|
|
819424fd3b | ||
|
|
f25b8fc7b0 | ||
|
|
0d57356c11 | ||
|
|
8775564e04 | ||
|
|
15dff342a6 | ||
|
|
45c7184fde | ||
|
|
2ddaa351ab | ||
|
|
afe9ee5367 | ||
|
|
8348f2dcc8 | ||
|
|
63f489d39f | ||
|
|
8bbf57c199 | ||
|
|
67f63a6bb3 | ||
|
|
18b51de696 | ||
|
|
d23eacbd37 | ||
|
|
444ae00129 | ||
|
|
6280232e91 | ||
|
|
23e3a1d012 | ||
|
|
71af78caea | ||
|
|
e1d9732a60 | ||
|
|
058f86ec5f | ||
|
|
0da87e1d5e | ||
|
|
be0a808f01 | ||
|
|
a0fa232a3a | ||
|
|
4a4602137b | ||
|
|
6d6f1340af | ||
|
|
35a728e69f | ||
|
|
218d08b1f6 | ||
|
|
219245be95 | ||
|
|
aa1742db63 | ||
|
|
e336c67857 | ||
|
|
871fd46c89 | ||
|
|
f536f16926 | ||
|
|
d3c00cdd52 | ||
|
|
6b990f8f12 | ||
|
|
3c010f0e73 | ||
|
|
357df22fab | ||
|
|
470f5b5029 | ||
|
|
216b1664bd | ||
|
|
cbe2124387 | ||
|
|
11934233a0 | ||
|
|
de9a0c0166 | ||
|
|
5c9ff9d1a2 | ||
|
|
0142520bb8 | ||
|
|
b4f9f968f6 | ||
|
|
9a7bafb02c | ||
|
|
3e44d5bfdf | ||
|
|
f4d58c8823 | ||
|
|
4d192f5930 | ||
|
|
20cbf99cdf | ||
|
|
6784388a42 | ||
|
|
b504a79bf7 | ||
|
|
1b9b49f045 | ||
|
|
095413c6c5 | ||
|
|
b9486e8935 | ||
|
|
302b9f9dd7 | ||
|
|
57aa267f24 | ||
|
|
ce351afb9a | ||
|
|
7b513bd29d | ||
|
|
0e65bfc78b | ||
|
|
afaf105cb0 | ||
|
|
629297e0c2 | ||
|
|
1aca22f219 | ||
|
|
bd3da38fc8 | ||
|
|
991c2c18de | ||
|
|
54a2e7650a | ||
|
|
5819cfb438 | ||
|
|
38ca58d71e | ||
|
|
c1c0edab9f | ||
|
|
8670938397 | ||
|
|
83b552780e | ||
|
|
b8cc74f377 | ||
|
|
c3ba39c80f | ||
|
|
ff3a9c51f3 | ||
|
|
19dfea7762 | ||
|
|
c311828217 | ||
|
|
5ae74d6924 | ||
|
|
04f719c33c | ||
|
|
7ab88e9a71 | ||
|
|
1164da5e7a | ||
|
|
6742646e89 | ||
|
|
6cf01631ad | ||
|
|
7a5cade510 | ||
|
|
c5a1d8a8bd | ||
|
|
32bad5f8bb | ||
|
|
5ec5647395 | ||
|
|
4e9f7c729d | ||
|
|
4c0437b3fb | ||
|
|
de71b97b1f | ||
|
|
21d008c6c2 | ||
|
|
9138a3c881 | ||
|
|
8b3f36c1f8 | ||
|
|
d397d75aca | ||
|
|
618b28a292 | ||
|
|
c966211481 | ||
|
|
5ae1190ddd | ||
|
|
fb9cce747d | ||
|
|
1a04ebce35 | ||
|
|
59bbfc4e06 | ||
|
|
d3973172e8 | ||
|
|
cdd31353c5 | ||
|
|
b047cb6dc1 | ||
|
|
c52dce1c48 | ||
|
|
0b4a1b4a1b | ||
|
|
cc0c1bcf3a | ||
|
|
55746f1a1d | ||
|
|
7bb8581a95 | ||
|
|
521c0f8460 | ||
|
|
4bfe3b6fe1 | ||
|
|
b610aa1c0c | ||
|
|
73da04bea2 | ||
|
|
18c851e53f | ||
|
|
41f4533bc0 | ||
|
|
4db8a967b6 | ||
|
|
ff70f4e79f | ||
|
|
c9517aff7d | ||
|
|
3657a49a2c | ||
|
|
71e7aa5262 | ||
|
|
2e435f5d4e | ||
|
|
859b03c4a6 | ||
|
|
ee8786444f | ||
|
|
d87d782fd5 | ||
|
|
afac4fc37f | ||
|
|
de83521e08 | ||
|
|
99f8fe1592 | ||
|
|
02c092a122 | ||
|
|
70ca74747f | ||
|
|
594d754022 | ||
|
|
c381e4153d | ||
|
|
e761c7e8f4 | ||
|
|
b8d4e3ac50 | ||
|
|
4c2b95d00b | ||
|
|
cea4f052ba | ||
|
|
9b4ea7a040 | ||
|
|
26c2b258b4 | ||
|
|
27c9e18535 | ||
|
|
b53c2bfa0c | ||
|
|
80605633c4 | ||
|
|
acf06fdd8f | ||
|
|
58cc5b4684 | ||
|
|
c502bd901e | ||
|
|
55027747fd | ||
|
|
f6d77afe2e | ||
|
|
cd9466dafa | ||
|
|
4bf79e4bc9 | ||
|
|
7afecf0f85 | ||
|
|
0b38b7d473 | ||
|
|
1b462da4aa | ||
|
|
07948304b2 | ||
|
|
0634acdac4 | ||
|
|
75e0637d2d | ||
|
|
852c30b2e5 | ||
|
|
dc85c6552a | ||
|
|
76e8506022 | ||
|
|
2d6e2551f6 | ||
|
|
080b1d9a7c | ||
|
|
fe008b0966 | ||
|
|
4ad10d057b | ||
|
|
a65aa9f312 | ||
|
|
5b43c16f35 | ||
|
|
9cb37dc011 | ||
|
|
2ba6737c41 | ||
|
|
33d737f957 | ||
|
|
381a18a40e | ||
|
|
207f0655dd | ||
|
|
88d64da257 | ||
|
|
cf378dfd6d | ||
|
|
a3939d9a66 | ||
|
|
ef363209a4 | ||
|
|
fe9a10c617 | ||
|
|
2e734fae57 | ||
|
|
432e3c3a5e | ||
|
|
a4b13a80ce | ||
|
|
a6997a7e85 | ||
|
|
a60d06af6b | ||
|
|
dab8012b6a | ||
|
|
66f82fd9cc | ||
|
|
0bff8ba632 | ||
|
|
32226297ab | ||
|
|
ab18c90b36 | ||
|
|
27b6fd561a | ||
|
|
15b64d5a25 | ||
|
|
08a50a8ada | ||
|
|
9d172bb29d | ||
|
|
c891322129 | ||
|
|
77434850f7 | ||
|
|
69b65dbd41 | ||
|
|
c335a545a3 | ||
|
|
5bcccec610 | ||
|
|
20ae9c3a53 | ||
|
|
92ca7c5a4b | ||
|
|
37fa41b4a2 | ||
|
|
298f959e13 | ||
|
|
1cb431f204 | ||
|
|
74dc7b278b | ||
|
|
b47d8a794c | ||
|
|
eaf845959c | ||
|
|
651521d346 | ||
|
|
fb37b29671 | ||
|
|
2ecf9016ba | ||
|
|
444b08be32 | ||
|
|
2b84712eee | ||
|
|
20cb6cdd8b | ||
|
|
477a5e5338 | ||
|
|
2a151229cb | ||
|
|
1d50e091c7 | ||
|
|
c587e380a0 | ||
|
|
54f9bfba84 | ||
|
|
489ba131c5 | ||
|
|
5eac1a146f | ||
|
|
d7ce6bdeff | ||
|
|
e88473d090 | ||
|
|
b9024ab032 | ||
|
|
98906be0f6 | ||
|
|
220775715d | ||
|
|
ecbf52157b | ||
|
|
a579977f66 | ||
|
|
418dc6fdc2 | ||
|
|
2aa4b03673 | ||
|
|
f236a65a79 | ||
|
|
f7b08a1160 | ||
|
|
eed10dd1bb | ||
|
|
9992bd0999 | ||
|
|
6912175e7e | ||
|
|
a59c32757e | ||
|
|
2438a0e60b | ||
|
|
a850a902ce | ||
|
|
b7ba993ba6 | ||
|
|
3eb0d57d5b | ||
|
|
6bf2ff9168 | ||
|
|
92226a8d06 | ||
|
|
134424dfdc | ||
|
|
58ceb66452 | ||
|
|
902b8fc789 | ||
|
|
923491a510 | ||
|
|
255b45d07b | ||
|
|
8f68b5b289 | ||
|
|
252fd78473 | ||
|
|
b692c5db60 | ||
|
|
eff7d58f4b | ||
|
|
17e9bdf8e8 | ||
|
|
22d2694b71 | ||
|
|
e74d7fa454 | ||
|
|
464f42a121 | ||
|
|
05e7079178 | ||
|
|
f03fcc9a31 | ||
|
|
c3ad054bb3 | ||
|
|
202e137d77 | ||
|
|
6b35664e37 | ||
|
|
1a7dbd56ac | ||
|
|
1a40853aae | ||
|
|
6bad2b16e4 | ||
|
|
db166b4633 | ||
|
|
71bc624a74 | ||
|
|
907a941795 | ||
|
|
559783eed7 | ||
|
|
68585c8837 | ||
|
|
eccbc9d9b3 | ||
|
|
e7d1d55170 | ||
|
|
f04754c254 | ||
|
|
a8e5a48b87 | ||
|
|
283a9af406 | ||
|
|
e3896455db | ||
|
|
5e6d2700a2 | ||
|
|
dfd0dfe0f6 | ||
|
|
e6b9be5020 | ||
|
|
6f7c87516f | ||
|
|
516a78326d | ||
|
|
853b7f84ef | ||
|
|
b248a2515e | ||
|
|
6826c42c65 | ||
|
|
4f041e48a3 | ||
|
|
ec6800500b | ||
|
|
856d65a8e9 | ||
|
|
8a2efde365 | ||
|
|
2ddcc6d9e6 | ||
|
|
25962326d2 | ||
|
|
bbc2fbf984 | ||
|
|
edc53d6de3 | ||
|
|
47710210bd | ||
|
|
823b7f0670 | ||
|
|
f5130ce48f | ||
|
|
347524a5b3 | ||
|
|
51830f5907 | ||
|
|
346f538c3b | ||
|
|
9d2948ff50 | ||
|
|
36ce227bf6 | ||
|
|
024f7ad9ef | ||
|
|
f8425fe614 | ||
|
|
7802a1b5a4 | ||
|
|
17549d8a43 | ||
|
|
f6ed706855 | ||
|
|
89ef25501b | ||
|
|
4870125e64 | ||
|
|
2d24e3c7f7 | ||
|
|
cdb3f46506 | ||
|
|
e225ed9f19 | ||
|
|
17bebf4f3a | ||
|
|
26550129ea | ||
|
|
66362c2762 | ||
|
|
f6f0e141a1 | ||
|
|
f22ee54bd8 | ||
|
|
2a969f911e | ||
|
|
2a0964f66b | ||
|
|
c553a2cd38 | ||
|
|
24330a7491 | ||
|
|
cd763a7a35 | ||
|
|
ed11eab0a7 | ||
|
|
a875ce4d68 | ||
|
|
969bfb4e53 | ||
|
|
76dae43103 | ||
|
|
af75ce79ac | ||
|
|
fe89c2ff9b | ||
|
|
bb2595eca5 | ||
|
|
618fff0191 | ||
|
|
9bbd06ce76 | ||
|
|
20463a662b | ||
|
|
9251180501 | ||
|
|
2659043afd | ||
|
|
7766892ad2 | ||
|
|
a7848f43cd | ||
|
|
cf8f76b454 | ||
|
|
f68f184c68 | ||
|
|
463440bce4 | ||
|
|
51ee313910 | ||
|
|
744b0bfff7 | ||
|
|
949479aa81 | ||
|
|
8743841145 | ||
|
|
6225cb38ae | ||
|
|
8dcba37672 | ||
|
|
38b922df75 | ||
|
|
6d884382a1 | ||
|
|
752e75e94b | ||
|
|
5ca41b5e13 | ||
|
|
1b3707ad33 | ||
|
|
c6e82d5af6 | ||
|
|
814e41122a | ||
|
|
a133a71eb9 | ||
|
|
dc2addb0ed | ||
|
|
f9014bb90c | ||
|
|
df0b6d5b07 | ||
|
|
56c6e8be06 | ||
|
|
b47b8297d6 | ||
|
|
5d1e17c598 | ||
|
|
94fe34bd10 | ||
|
|
e68ff62723 | ||
|
|
04487b6b91 | ||
|
|
49a27a67bc | ||
|
|
745de2ede2 | ||
|
|
82e5698f1d | ||
|
|
c4090851c5 | ||
|
|
9cb4431e89 | ||
|
|
2221d0cb6f | ||
|
|
5ea97c4910 | ||
|
|
a40590b4bf | ||
|
|
58acb2b821 | ||
|
|
6b9dc90639 | ||
|
|
b7d26cf0d5 | ||
|
|
59b4033ab2 | ||
|
|
13a7219dbd | ||
|
|
eae8a90a89 | ||
|
|
a87f4abd5f | ||
|
|
1b73691c69 | ||
|
|
e00066466b | ||
|
|
b87a8ba97d | ||
|
|
57aa270032 | ||
|
|
90a96fd8a7 | ||
|
|
c05470515f | ||
|
|
81ed4f3699 | ||
|
|
c9ac1eab11 | ||
|
|
1ba542fb3b | ||
|
|
4f127c9de3 | ||
|
|
16656f6c13 | ||
|
|
0f13e062fe | ||
|
|
2e68407fbe | ||
|
|
974f350f27 | ||
|
|
27ffea9052 | ||
|
|
9b2b35e8a2 | ||
|
|
3b51ca3947 | ||
|
|
62a2d08b53 | ||
|
|
e790bde717 | ||
|
|
0ab6b15292 | ||
|
|
2aeeb14c21 | ||
|
|
e5e57ab3bd | ||
|
|
f3ce5dcfbd | ||
|
|
bc341e98fc | ||
|
|
80851f4861 | ||
|
|
22b4456bce | ||
|
|
8d67502997 | ||
|
|
8f31fd778b | ||
|
|
f79f25bcf4 | ||
|
|
68e237eec5 | ||
|
|
8895c70c7f | ||
|
|
3964f8649d | ||
|
|
b7fb0ef1d3 | ||
|
|
66e403c5b4 | ||
|
|
0913abe806 | ||
|
|
6d3065c4c6 | ||
|
|
9092d1f8eb | ||
|
|
1bd1f123a3 | ||
|
|
44c072dcbb | ||
|
|
45c59e2990 | ||
|
|
75f0cd6e62 | ||
|
|
80f758018c | ||
|
|
b5e2c62fdd | ||
|
|
ede35718ae | ||
|
|
31fe2807aa | ||
|
|
f77693d768 | ||
|
|
96e3c16cca | ||
|
|
edd41b37f0 | ||
|
|
139d0038f2 | ||
|
|
d25fc64d7a | ||
|
|
9c83b268b9 | ||
|
|
42092ac16a | ||
|
|
e4860d5bae | ||
|
|
a5d9b658fb | ||
|
|
f464e89415 | ||
|
|
cdc439c4ef | ||
|
|
746168f9ed | ||
|
|
5ad4885102 | ||
|
|
7eb53ca2bc | ||
|
|
10fc056184 | ||
|
|
7517937155 | ||
|
|
a86fa8cc37 | ||
|
|
e1c765e78a | ||
|
|
56b08bddd8 | ||
|
|
2ed8a1c0ec | ||
|
|
389dff7031 | ||
|
|
123d69e595 | ||
|
|
4ab7fe26fc | ||
|
|
0aa1e0200f | ||
|
|
575f827958 | ||
|
|
7136851893 | ||
|
|
67935b11c9 | ||
|
|
85f60cbc7b | ||
|
|
9c35f8a24e | ||
|
|
9971de2ccd | ||
|
|
1ca8dc0ac0 | ||
|
|
85d148822e | ||
|
|
1e738dcf79 | ||
|
|
b5ffd8d046 | ||
|
|
21e354d252 | ||
|
|
15628d9b07 | ||
|
|
950182986a | ||
|
|
bc82023878 | ||
|
|
d5363e5993 | ||
|
|
80adee8558 | ||
|
|
37fe6a661b | ||
|
|
eb453f471b | ||
|
|
afd278ca4e | ||
|
|
ca8877da2d | ||
|
|
42828c64fb | ||
|
|
6600626f4f | ||
|
|
ac10d5b2a3 | ||
|
|
9f040025e7 | ||
|
|
2522e7fe9c | ||
|
|
dd22c55d23 | ||
|
|
a6efa9e9b2 | ||
|
|
5087b8004a | ||
|
|
d4c40242d0 | ||
|
|
5af55f1d5d | ||
|
|
55ef0a5e9e | ||
|
|
5dda86bf4a | ||
|
|
d81377b10d | ||
|
|
da128f5d49 | ||
|
|
6e5fe8e4a2 | ||
|
|
b3d350d41e | ||
|
|
7c6870f8eb | ||
|
|
327b4e4e37 | ||
|
|
7fdc857326 | ||
|
|
0382c2775e | ||
|
|
a0374133cd | ||
|
|
055f697340 | ||
|
|
ec8a9862c7 | ||
|
|
f393eb7b7d | ||
|
|
78285d7b1e | ||
|
|
b6137b03cd | ||
|
|
e237e709b6 | ||
|
|
2ac9b2088a | ||
|
|
a791212d89 | ||
|
|
5cc5f45ef3 | ||
|
|
a11e50c087 | ||
|
|
4dc09360a1 | ||
|
|
3a5528cc4d | ||
|
|
de533755e5 | ||
|
|
024b69ee3e | ||
|
|
d7e7832e9f | ||
|
|
8d4d72bf15 | ||
|
|
86a82d55fa | ||
|
|
5a15066da3 | ||
|
|
81766c8517 | ||
|
|
e486f28a41 | ||
|
|
8a9cbaf413 | ||
|
|
3a0a930b79 | ||
|
|
c40704d2f3 | ||
|
|
c0f0630e17 | ||
|
|
19dbb3a778 | ||
|
|
d4fc6f1b35 | ||
|
|
7c82942912 | ||
|
|
87d48b028b | ||
|
|
d6640f4d15 | ||
|
|
785a8da623 | ||
|
|
57dc303d90 | ||
|
|
ce08cc9659 | ||
|
|
866393743c | ||
|
|
ba255aa653 | ||
|
|
7d46e8fe80 | ||
|
|
6c41245c73 | ||
|
|
2a8e51c2d2 | ||
|
|
b2cf5df612 | ||
|
|
ada9ddd5b8 | ||
|
|
f66f4d9aeb | ||
|
|
d02ba777f2 | ||
|
|
aef614823b | ||
|
|
431db85ecb | ||
|
|
1ebac06f4b | ||
|
|
c7c5af4708 | ||
|
|
0b6a9d3a0b | ||
|
|
23d6362058 | ||
|
|
1443f38e5f | ||
|
|
94960cc842 | ||
|
|
efc983b009 | ||
|
|
74d90f2892 | ||
|
|
56f1b6cc19 | ||
|
|
fa2cd9dfd9 | ||
|
|
687f09d952 | ||
|
|
67b479b5c8 | ||
|
|
eac2140693 | ||
|
|
7a3f5de9c2 | ||
|
|
7005bf2481 | ||
|
|
b80ee3342c | ||
|
|
4c7b7b1e60 | ||
|
|
1a4a3608c8 | ||
|
|
6800d50339 | ||
|
|
036f808ec6 | ||
|
|
7647ce9e6d | ||
|
|
545d3f81ce | ||
|
|
455615b9c1 | ||
|
|
d0e2a03da5 | ||
|
|
fa408e644c | ||
|
|
a22416584d | ||
|
|
b8fc60df45 | ||
|
|
c6455cf02e | ||
|
|
2ac1d39367 | ||
|
|
041e014d68 | ||
|
|
5defb5c442 | ||
|
|
520a572bb4 | ||
|
|
4c602256da | ||
|
|
5a40cbd655 | ||
|
|
a75f9dd48d | ||
|
|
6b47aa2446 | ||
|
|
a847a1faae | ||
|
|
bb381e522c | ||
|
|
6962cfb91a | ||
|
|
302c50a90e | ||
|
|
e2d47e1c86 | ||
|
|
7d51da1efb | ||
|
|
c7674926c3 | ||
|
|
f0ca9728ae | ||
|
|
5fa8567801 | ||
|
|
e5b1acb6e1 | ||
|
|
8fdbaef4c7 | ||
|
|
7869159657 | ||
|
|
7046e18d7e | ||
|
|
a7516061d0 | ||
|
|
e61d787ff0 | ||
|
|
25ad420f85 | ||
|
|
fcd49c000f | ||
|
|
e2320ebe66 | ||
|
|
5e78a26e3d | ||
|
|
159bd06a56 | ||
|
|
bc7e1e07f4 | ||
|
|
ccc9618102 | ||
|
|
0ad09cca9d | ||
|
|
0959eea677 | ||
|
|
3316f2fcf4 | ||
|
|
390a21e4aa | ||
|
|
70ce54a5cd | ||
|
|
087e42a641 | ||
|
|
e26d4afce2 | ||
|
|
b9ae4c6077 | ||
|
|
11485d24f5 | ||
|
|
ce14f0b380 | ||
|
|
8bb2158a2a | ||
|
|
1a9d4af565 | ||
|
|
a6f37633a1 | ||
|
|
3182a47858 | ||
|
|
7335b1d0a4 | ||
|
|
cd33e9ad0e | ||
|
|
557f8444b2 | ||
|
|
65088b8644 | ||
|
|
7cc9521cbb | ||
|
|
4ad19fc4d8 | ||
|
|
ec71f8e2d9 | ||
|
|
ff8a847795 | ||
|
|
6b001c50a4 | ||
|
|
5759c88932 | ||
|
|
00c11d9bd4 | ||
|
|
ed99acebfe | ||
|
|
bade412d30 | ||
|
|
191e9ba073 | ||
|
|
b21688a0ac | ||
|
|
a4d4da4d96 | ||
|
|
16c85c5b8a | ||
|
|
2c7b39927a | ||
|
|
7f47692ad4 | ||
|
|
af4066da87 | ||
|
|
4de4e7504d | ||
|
|
b46c181b07 | ||
|
|
e4f89092b3 | ||
|
|
4fbedf5b20 | ||
|
|
d51a03f1b6 | ||
|
|
f7eee0d461 | ||
|
|
39178d8d2b | ||
|
|
7795916c08 | ||
|
|
0e2a3d8009 | ||
|
|
38a0b6905e | ||
|
|
8797549369 | ||
|
|
f5ec74252d | ||
|
|
211012d367 | ||
|
|
c1319d1f27 | ||
|
|
d4d8773fd1 | ||
|
|
01223601f2 | ||
|
|
d9ed4cfca8 | ||
|
|
7d0e4b6270 | ||
|
|
b2f645a5ce | ||
|
|
6a29d6711c | ||
|
|
5b2806a784 | ||
|
|
a2f15ce0b2 | ||
|
|
68400f3bcf | ||
|
|
31f3c2771a | ||
|
|
f9352e26cb | ||
|
|
4fa542bc38 | ||
|
|
a707e10af7 | ||
|
|
1e095fede5 | ||
|
|
96b10f4b85 | ||
|
|
5100e06f38 | ||
|
|
35e2fa5058 | ||
|
|
8d2d4ffdd2 | ||
|
|
7d05712f40 | ||
|
|
c0106a238b | ||
|
|
f6c68e4580 | ||
|
|
3c8065fdee | ||
|
|
9bd8b2fc43 | ||
|
|
5a3d5f5512 | ||
|
|
ca9e850ac7 | ||
|
|
2dc09c799f | ||
|
|
a49154acf4 | ||
|
|
77eee7f087 | ||
|
|
03694b54f0 | ||
|
|
bed320204d | ||
|
|
971524fa3b | ||
|
|
4758456069 | ||
|
|
3ef4ba6b8b | ||
|
|
a504f051e7 | ||
|
|
ea0bbaf332 | ||
|
|
19c908035b | ||
|
|
05192b6850 | ||
|
|
079ce5e9de | ||
|
|
ff742c0169 | ||
|
|
332e264437 | ||
|
|
3554634c1c | ||
|
|
c96fb3c2f2 | ||
|
|
1e612e4166 | ||
|
|
06984ace21 | ||
|
|
cabd4fa718 | ||
|
|
ddb549cb45 | ||
|
|
c7484c69c0 | ||
|
|
9876d79680 | ||
|
|
32566ccc80 | ||
|
|
7f9e309ae8 | ||
|
|
7831aabe5a | ||
|
|
74b40b97ec | ||
|
|
f45726d61f | ||
|
|
3c0d027306 | ||
|
|
dc83765808 | ||
|
|
4244b572d1 | ||
|
|
77475ca5e4 | ||
|
|
3555680335 | ||
|
|
f65a39a3e3 | ||
|
|
94e8964f69 | ||
|
|
254d22e2cc | ||
|
|
54ab1326e5 | ||
|
|
b0fe5d60ab | ||
|
|
4b1eb2794f | ||
|
|
6a2dd1111c | ||
|
|
f5da89b50b | ||
|
|
bede244598 | ||
|
|
4df48c9695 | ||
|
|
05ad77ffbe | ||
|
|
dc23a74e7b | ||
|
|
f463cb16da | ||
|
|
b785884cd8 | ||
|
|
f09caec09a | ||
|
|
5e30a3997e | ||
|
|
8552a5797c | ||
|
|
a0d528981e | ||
|
|
7ffdee0d7f | ||
|
|
3d0928a449 | ||
|
|
ea1bca05c7 | ||
|
|
df292a2103 | ||
|
|
7f2c360f33 | ||
|
|
fbd40a6514 | ||
|
|
9dd02ec67d | ||
|
|
8e55082d4e | ||
|
|
29378c57ea | ||
|
|
16c74cf3b4 | ||
|
|
b199925f91 | ||
|
|
28397bf9d0 | ||
|
|
1b7abf9972 | ||
|
|
b98bdeaae7 | ||
|
|
221274b473 | ||
|
|
cc6d443113 | ||
|
|
b3c81c9e55 | ||
|
|
84d07f3f18 | ||
|
|
0fee2bbf28 | ||
|
|
ea38845622 | ||
|
|
81a0e95916 | ||
|
|
2a9feee476 | ||
|
|
c38c1fa93a | ||
|
|
8d7c35d034 | ||
|
|
425f62607b | ||
|
|
c1752ae5eb | ||
|
|
d61e91b949 | ||
|
|
090c0f8857 | ||
|
|
c453dd2b3c | ||
|
|
b2b2e97edc | ||
|
|
bd9e4dbc79 | ||
|
|
0c19070800 | ||
|
|
07e37b257f | ||
|
|
0a5f060d1b | ||
|
|
6fcfcb630d | ||
|
|
7aff90aec7 | ||
|
|
f1e513443b | ||
|
|
c533b10e19 | ||
|
|
b4014e8c24 | ||
|
|
478f3a5308 | ||
|
|
b98edf3d76 | ||
|
|
02fe46de58 | ||
|
|
ab2fd0ad36 | ||
|
|
88655d877b | ||
|
|
6e94affea6 | ||
|
|
f7f382275a | ||
|
|
23f3bf43c2 | ||
|
|
8a0c4909b9 | ||
|
|
2aeaf02d05 | ||
|
|
f4a6e34713 | ||
|
|
3eb85da02c | ||
|
|
6533456472 | ||
|
|
7969e047c7 | ||
|
|
f0d6d9d177 | ||
|
|
ca574df3be | ||
|
|
0b793d82fe | ||
|
|
f6d51462eb | ||
|
|
5bdacbab61 | ||
|
|
e239cc962b | ||
|
|
6ebd4fcf5b | ||
|
|
ef427fa966 | ||
|
|
f4383a11d7 | ||
|
|
77b6377473 | ||
|
|
7bf3cf999f | ||
|
|
4ab611de0c | ||
|
|
d7745a418f | ||
|
|
058a5a43ba | ||
|
|
878dbd81b1 | ||
|
|
3c64ed1eb2 | ||
|
|
ee50f1238c | ||
|
|
1af2513fc0 | ||
|
|
9c0d26bc84 | ||
|
|
4d9053a83b | ||
|
|
3f7e98c277 | ||
|
|
aebc877e7b | ||
|
|
eef5f3fec2 | ||
|
|
16a1677fde | ||
|
|
f199816fcd | ||
|
|
5e74e17b41 | ||
|
|
98b041e84a | ||
|
|
bba9c8f652 | ||
|
|
1a05fe6ae1 | ||
|
|
16fcbf66ee | ||
|
|
b7fd4e90e2 | ||
|
|
b6341c10cc | ||
|
|
08487b0fcc | ||
|
|
b084dde22a | ||
|
|
5229a7c997 | ||
|
|
e56c56e2fe | ||
|
|
7374f956cf | ||
|
|
287df42994 | ||
|
|
06e514cc2e | ||
|
|
dffd8b5fec | ||
|
|
2a87337875 | ||
|
|
a74f79118f | ||
|
|
a13ed0bec3 | ||
|
|
f8ca45f0f2 | ||
|
|
4bf92a34f6 | ||
|
|
4f1c84004a | ||
|
|
1bd430598d | ||
|
|
3bc654bf97 | ||
|
|
3906acb83d | ||
|
|
cfd62ac137 | ||
|
|
cd540dfae9 | ||
|
|
74ad9ec8bf | ||
|
|
4f8a3fe5b9 | ||
|
|
09ca0e6ef0 | ||
|
|
fae2b5acfa | ||
|
|
d35a3eab6c | ||
|
|
7f7f47497a | ||
|
|
eb14ac3741 | ||
|
|
22334faba3 | ||
|
|
d08fd297e8 | ||
|
|
0dd664bfbf | ||
|
|
1602932d72 | ||
|
|
98c8b7d2b0 | ||
|
|
b9ae24c42d | ||
|
|
b387fd2bd4 | ||
|
|
818f4540fd | ||
|
|
49a97dbb66 | ||
|
|
a8b72c1d5f | ||
|
|
765b8dc97b | ||
|
|
5123697afe | ||
|
|
2a2a9d7941 | ||
|
|
2873aa5f81 | ||
|
|
795c925ba1 | ||
|
|
d6ace3f695 | ||
|
|
dd04759de7 | ||
|
|
10fbde84ba | ||
|
|
2b5652e1e4 | ||
|
|
18796ae44e | ||
|
|
a67692dc29 | ||
|
|
1efd756a55 | ||
|
|
29671acdb6 | ||
|
|
e82240a60e | ||
|
|
72083c8614 | ||
|
|
8c2c1e534c | ||
|
|
bfc01d957b | ||
|
|
4a12d045e4 | ||
|
|
2d78b2c219 | ||
|
|
3049bb0b9f | ||
|
|
34ab8152fb | ||
|
|
fb58c50fb7 | ||
|
|
955f917015 | ||
|
|
12c7df98e4 | ||
|
|
889c29a163 | ||
|
|
886c1370e7 | ||
|
|
febcc0a673 | ||
|
|
98cad6bf8d | ||
|
|
7e5daedc8c | ||
|
|
da3fe6f7ea | ||
|
|
f612ce262f | ||
|
|
24ccfca279 | ||
|
|
34b3c3982b | ||
|
|
7f732c94da | ||
|
|
bdc49a65aa | ||
|
|
73d82dd0ba | ||
|
|
dfa4403c8a | ||
|
|
b8f3b19499 | ||
|
|
448718d112 | ||
|
|
6de55df4bc | ||
|
|
189fe26667 | ||
|
|
7230884116 | ||
|
|
d7fba81f8f | ||
|
|
29ac13185c | ||
|
|
3a49ee83ce | ||
|
|
95cbbc3b45 | ||
|
|
2a5c7d139f | ||
|
|
b74863873b | ||
|
|
7b46fe9cc8 | ||
|
|
afc8c69a82 | ||
|
|
38bbad6e88 | ||
|
|
1df47fd415 | ||
|
|
faf21c5fff | ||
|
|
2aee580795 | ||
|
|
404c027546 | ||
|
|
04e59c6df2 | ||
|
|
835042b794 | ||
|
|
907490e266 | ||
|
|
80fe167646 | ||
|
|
d30631f991 | ||
|
|
8956ab85f9 | ||
|
|
2cdc9e9f5f | ||
|
|
13c623755c | ||
|
|
bdfceec520 | ||
|
|
941dace7f9 | ||
|
|
07693e54af | ||
|
|
b6132f2497 | ||
|
|
b3fe3d02c9 | ||
|
|
e880b18bb1 | ||
|
|
74a299eef7 | ||
|
|
300428ddfb | ||
|
|
1c27f8251e | ||
|
|
92badd3722 | ||
|
|
8a80f0b3dd | ||
|
|
fcc74b63d3 | ||
|
|
d7155e6662 | ||
|
|
42c3841639 | ||
|
|
c331713401 | ||
|
|
002d9c1747 | ||
|
|
2885ceceb1 | ||
|
|
22a644ba01 | ||
|
|
bab120a75d | ||
|
|
7a07c82f06 | ||
|
|
e881d2f6cf | ||
|
|
c8d003a08f | ||
|
|
e2cc404571 | ||
|
|
be71eaae47 | ||
|
|
ed31a452b2 | ||
|
|
f51ee7f3a0 | ||
|
|
9d1dc97766 | ||
|
|
b78729f685 | ||
|
|
44a76e59f9 | ||
|
|
1504e36a68 | ||
|
|
80348ef190 | ||
|
|
a3c14748d3 | ||
|
|
3c0143af92 | ||
|
|
22a93a9c39 | ||
|
|
e8866a6431 | ||
|
|
455ed79872 | ||
|
|
3d17c531d7 | ||
|
|
dfe90243d6 | ||
|
|
bf1db50667 | ||
|
|
a2565a7c83 | ||
|
|
947d01a3c0 | ||
|
|
be11d82c9c | ||
|
|
7a0e7fff13 | ||
|
|
81fb71b7f7 | ||
|
|
b10f5ec99f | ||
|
|
5abe7bdeef | ||
|
|
54be651415 | ||
|
|
cdbf6d7ae7 | ||
|
|
50349edf4d | ||
|
|
da307c1b40 | ||
|
|
b50b96bd1d | ||
|
|
92654fc5aa | ||
|
|
36b2de216b | ||
|
|
8745c1016e | ||
|
|
f5a58c1ff0 | ||
|
|
d9e72049ae | ||
|
|
927ca01161 | ||
|
|
3ea8d0b01c | ||
|
|
c52d33e331 | ||
|
|
fd36606acc | ||
|
|
1c6f4a79e0 | ||
|
|
7896d274a3 | ||
|
|
6937c8ecb4 | ||
|
|
f02b9566c5 | ||
|
|
c9936c2b7e | ||
|
|
bbd9e5e07c | ||
|
|
476fb7ec4e | ||
|
|
7435274be2 | ||
|
|
08d2ea6a10 | ||
|
|
41b7ed6938 | ||
|
|
7a311a181b | ||
|
|
ddcb597710 | ||
|
|
9c75f29875 | ||
|
|
343f3885f7 | ||
|
|
ed7dfeab84 | ||
|
|
8de27b3674 | ||
|
|
f56b0a5f6d | ||
|
|
0a27e1254f | ||
|
|
3f9b256fcb | ||
|
|
9ea9859150 | ||
|
|
03e3f95d2e | ||
|
|
e721b0af92 | ||
|
|
e18c589de3 | ||
|
|
aea34264a9 | ||
|
|
8d3a04235d | ||
|
|
9c4088b24c | ||
|
|
1e7ee4e0a1 | ||
|
|
ec92f110b3 | ||
|
|
2aa5eb85ad | ||
|
|
2815f02382 | ||
|
|
8bd7c8dd41 | ||
|
|
269dcf071f | ||
|
|
997ec7f0bc | ||
|
|
d9c26bb77f | ||
|
|
c0fc3a19c8 | ||
|
|
ce638c39e3 | ||
|
|
6b651cd5e4 | ||
|
|
4560f31010 | ||
|
|
c97a32e24b | ||
|
|
8a005bc5a1 | ||
|
|
20aabee72e | ||
|
|
a00c2345ee | ||
|
|
cb35b3624a | ||
|
|
c6f59a7aa6 | ||
|
|
bf296ad797 | ||
|
|
256540934b | ||
|
|
3c07c0818d | ||
|
|
a01d18ace1 | ||
|
|
55e02f01dc | ||
|
|
fe6ccad485 | ||
|
|
11fe79312d | ||
|
|
bdb2338b5b | ||
|
|
bbafb048d0 | ||
|
|
9fc2fa51bd | ||
|
|
d8ec50345a | ||
|
|
9f1cc09ca8 | ||
|
|
5dcc3db36b | ||
|
|
898b73ffc8 | ||
|
|
c5d49a9d34 | ||
|
|
ef9f828d35 | ||
|
|
c691764205 | ||
|
|
2c940d4fd6 | ||
|
|
54bd55d45d | ||
|
|
0b846b15b1 | ||
|
|
269eb7e154 | ||
|
|
97bc19e4ae | ||
|
|
2656cc7842 | ||
|
|
ba94818415 | ||
|
|
ac759a6eed | ||
|
|
1839b346a6 | ||
|
|
c1ffe7f8e6 | ||
|
|
833b4d10bd | ||
|
|
ce98c336c9 | ||
|
|
d05619990a | ||
|
|
8033e41d4a | ||
|
|
60f4eab759 | ||
|
|
d7656ea985 | ||
|
|
e402998577 | ||
|
|
073f75efa3 | ||
|
|
da414f7eb3 | ||
|
|
270b89830a | ||
|
|
74ce7ca416 | ||
|
|
3f4338cb51 | ||
|
|
30ee41fd0e | ||
|
|
4965fec55c | ||
|
|
18dff8455c | ||
|
|
fe16f06aee | ||
|
|
48c1c05a93 | ||
|
|
38dee1166d | ||
|
|
0c6fc68eae | ||
|
|
223611d89e | ||
|
|
6f5141d5fb | ||
|
|
a6ac7d9c4e | ||
|
|
9b35736be3 | ||
|
|
9f54cb35f4 | ||
|
|
329bffb127 | ||
|
|
e2542f41b5 | ||
|
|
efc7b9d4a5 | ||
|
|
72915760c4 | ||
|
|
e9d7a946c5 | ||
|
|
714e5e0456 | ||
|
|
26e8642aca | ||
|
|
68dfb4ee86 | ||
|
|
f1ff789334 | ||
|
|
1f45d5b8e4 | ||
|
|
c20052f314 | ||
|
|
c28d87d59c | ||
|
|
237ddcba9a | ||
|
|
eadb5b6461 | ||
|
|
faebabe3c7 | ||
|
|
02c510b07f | ||
|
|
63541970eb | ||
|
|
a8a5605fe1 | ||
|
|
0c0ddc10ee | ||
|
|
9bd5ff69ef | ||
|
|
eadf351e82 | ||
|
|
e3afa294af | ||
|
|
582894cdc3 | ||
|
|
2788c36ca6 | ||
|
|
872a9d393d | ||
|
|
b1ca242d89 | ||
|
|
97c769e805 | ||
|
|
0de33b36f8 | ||
|
|
cf39bdc7f7 | ||
|
|
34b49498c9 | ||
|
|
3a4bd00020 | ||
|
|
effd07d8c0 | ||
|
|
d9ce89ab31 | ||
|
|
5483c52227 | ||
|
|
f12e9b6a49 | ||
|
|
2b48902f1b | ||
|
|
305460dedb | ||
|
|
bacef41a3b | ||
|
|
f789c84816 | ||
|
|
09466a2dff | ||
|
|
e77d888aab | ||
|
|
478d91928c | ||
|
|
fdd1a778f3 | ||
|
|
a5d87ab948 | ||
|
|
f1672dd6d2 | ||
|
|
48c25c380d | ||
|
|
3a5aa87853 | ||
|
|
f436744dd4 | ||
|
|
6df5e55807 | ||
|
|
c758054250 | ||
|
|
fff0a8a522 | ||
|
|
4ff978f318 | ||
|
|
b29e07faba | ||
|
|
b35107a966 | ||
|
|
1090ff0175 | ||
|
|
8de57ec0e0 | ||
|
|
4165f47a64 | ||
|
|
f931026216 | ||
|
|
19df73729a | ||
|
|
9efc1a1c09 | ||
|
|
234e7afb12 | ||
|
|
8904afaa74 | ||
|
|
d95a18b6eb | ||
|
|
bcd4bdb4e0 | ||
|
|
73df41b5b2 | ||
|
|
d32fbfd634 | ||
|
|
6b0c532f48 | ||
|
|
9f4ee7d6a8 | ||
|
|
7da83d2259 | ||
|
|
ceb9453006 | ||
|
|
7091b37f3a | ||
|
|
18e6f9be71 | ||
|
|
19d40845a4 | ||
|
|
211ce20132 | ||
|
|
275b97948b | ||
|
|
13d602a9e0 | ||
|
|
69215e7d27 | ||
|
|
7e8df34681 | ||
|
|
6451065c77 | ||
|
|
bde8c54e7e | ||
|
|
97b17af056 | ||
|
|
9c2e3e2c76 | ||
|
|
3c637872f2 | ||
|
|
4c8e2a1258 | ||
|
|
e5a76d737c | ||
|
|
a482d5998d | ||
|
|
12bc540ec9 | ||
|
|
b6a37f6fb8 | ||
|
|
bbdb25420a | ||
|
|
e3099a16d4 | ||
|
|
167fe5f758 | ||
|
|
36f59da7cc | ||
|
|
1ac23ce191 | ||
|
|
a000dfe676 | ||
|
|
9e834e0db5 | ||
|
|
021fc8fb59 | ||
|
|
625fa03c22 | ||
|
|
6e80b03faa | ||
|
|
c3f3eea7fb | ||
|
|
47da5e0338 | ||
|
|
2ef7ea6512 | ||
|
|
6b1f2c0ed2 | ||
|
|
bb465ed1ed | ||
|
|
ac75f9bf57 | ||
|
|
c80deeb5ec | ||
|
|
1b87f9690c | ||
|
|
e799fcd48a | ||
|
|
4644e55883 | ||
|
|
747a8ad09c | ||
|
|
32dc19cb1c | ||
|
|
527579aef4 | ||
|
|
1869ef0c38 | ||
|
|
e7007b4231 | ||
|
|
6ca57c1f8c | ||
|
|
f2f7a349ce | ||
|
|
f696aa3748 | ||
|
|
f35e3ec78a | ||
|
|
e339ee3f0c | ||
|
|
c30b424f36 | ||
|
|
0b0b405974 | ||
|
|
ef64fa3794 | ||
|
|
2531aed50b | ||
|
|
6adb46abd5 | ||
|
|
3ef1d8b0b9 | ||
|
|
71b5dc2f81 | ||
|
|
5909ab7641 | ||
|
|
b7beb73a92 | ||
|
|
0acbb20c00 | ||
|
|
9a2c0067f1 | ||
|
|
ab45b42382 | ||
|
|
4a6cee0611 | ||
|
|
d39cada0c6 | ||
|
|
b7b67681c7 | ||
|
|
8551e05808 | ||
|
|
cfdbd418c1 | ||
|
|
2a4feb7bee | ||
|
|
7202d758a2 | ||
|
|
dab59aded3 | ||
|
|
20d0b4ad16 | ||
|
|
eed4fc7844 | ||
|
|
0ccd9e0579 | ||
|
|
74b36d6d32 | ||
|
|
58215a470b | ||
|
|
608e0a0122 | ||
|
|
bddb3f0542 | ||
|
|
83da81839b | ||
|
|
73d63293d9 | ||
|
|
f49710f361 | ||
|
|
dffbce1934 | ||
|
|
06a33b0c8b | ||
|
|
a1f140acf7 | ||
|
|
fed37bcc48 | ||
|
|
88df9f0134 | ||
|
|
79d1425530 | ||
|
|
f9144378ae | ||
|
|
d13d28e6f4 | ||
|
|
c438bb2fbe | ||
|
|
5f4dd43124 | ||
|
|
e7f16f371c | ||
|
|
30ff17df28 | ||
|
|
d7a3e2f450 | ||
|
|
9ce3fc9f8e | ||
|
|
f0017c3e92 | ||
|
|
99b7508c7a | ||
|
|
cff8857a36 | ||
|
|
60395852d5 | ||
|
|
edf125b4ba | ||
|
|
b731fa4b78 | ||
|
|
676e6ecec1 | ||
|
|
7d9951aa3c | ||
|
|
1d0876af4d | ||
|
|
c6f23eee77 | ||
|
|
8d3cf04324 | ||
|
|
fe9344ce57 | ||
|
|
d7c4824633 | ||
|
|
2feba3182a | ||
|
|
e9920caa69 | ||
|
|
9bcaaab9d7 | ||
|
|
d47db317fb | ||
|
|
287d0fad85 | ||
|
|
7c19de3d61 | ||
|
|
a76cdf7514 | ||
|
|
9abead7c49 | ||
|
|
5ff3f71f83 | ||
|
|
e2f9ca66b6 | ||
|
|
e90048e5a8 | ||
|
|
eb1795aff9 | ||
|
|
3a92f93e6f | ||
|
|
d1bd358785 | ||
|
|
f63ea62f2d | ||
|
|
3fd5ed4feb | ||
|
|
ba7df8b9cf | ||
|
|
18b97df619 | ||
|
|
087d23269b | ||
|
|
c77fb98b1f | ||
|
|
8c1f38f74d | ||
|
|
13091e0de4 | ||
|
|
1a72bf5962 | ||
|
|
b8cd0c1a77 | ||
|
|
ecd593fb53 | ||
|
|
b17f20e2c5 | ||
|
|
eae9f9ceee | ||
|
|
d2c13ed32b | ||
|
|
6fb78a99bf | ||
|
|
bcc4980189 | ||
|
|
bed394db80 | ||
|
|
1fe2bf5dd5 | ||
|
|
7cc332a96e | ||
|
|
6ce24b3443 | ||
|
|
1dc6e91ec4 | ||
|
|
f59e3cd4da | ||
|
|
94a30b2167 | ||
|
|
bd0fa1487f | ||
|
|
d262f017c5 | ||
|
|
a98c08c06c | ||
|
|
a2e0fd28e0 | ||
|
|
5dbdf8321a | ||
|
|
9d122bd181 | ||
|
|
09727101c1 | ||
|
|
5fc9cd7d48 | ||
|
|
7adaa53f42 | ||
|
|
cc82b1ae25 | ||
|
|
0df531a646 | ||
|
|
b1d0368479 | ||
|
|
46c6a0b4ff | ||
|
|
97d414aa00 | ||
|
|
ab8da3965b | ||
|
|
589fa4c9de | ||
|
|
f4a27af37e | ||
|
|
ca0f407b7b | ||
|
|
4810a5643e | ||
|
|
72a983f6d8 | ||
|
|
a720333c0f | ||
|
|
38c6fa9c76 | ||
|
|
eed3d27665 | ||
|
|
450e345b28 | ||
|
|
913568aba2 | ||
|
|
3c3de9d325 | ||
|
|
fada732b33 | ||
|
|
152d0fdda7 | ||
|
|
6506fa792d | ||
|
|
867c72ba90 | ||
|
|
3f6b095da4 | ||
|
|
f1d6d386c5 | ||
|
|
72944a4e5e | ||
|
|
193e012aa6 | ||
|
|
3ee17e01e1 | ||
|
|
7421fa0a33 | ||
|
|
2cdfc3f4c3 | ||
|
|
4322d8e494 | ||
|
|
73a59dcd7d | ||
|
|
3a15790847 | ||
|
|
3f31573bcb | ||
|
|
967ab18d53 | ||
|
|
0929bd217d | ||
|
|
ce832a8063 | ||
|
|
fc0281b563 | ||
|
|
f42bd02cfc | ||
|
|
52634ddeb3 | ||
|
|
ed79b4ebd8 | ||
|
|
36ca7839d6 | ||
|
|
fa5d583657 | ||
|
|
5e67f09583 | ||
|
|
8b74d96f12 | ||
|
|
769d99e7bd | ||
|
|
812f4d2699 | ||
|
|
f95defe82f | ||
|
|
226dafa9e3 | ||
|
|
6c92d50c68 | ||
|
|
384e74fe7e | ||
|
|
216f6cc8e8 | ||
|
|
333c377bc7 | ||
|
|
59b33faf61 | ||
|
|
b87003427c | ||
|
|
cb48000df7 | ||
|
|
58cc5d8d1a | ||
|
|
39799d3006 | ||
|
|
73bf4479b5 | ||
|
|
9f0f84bbee | ||
|
|
1ff422a29c | ||
|
|
8daa525cc1 | ||
|
|
76f1fcb634 | ||
|
|
2b6cf95752 | ||
|
|
a99d193b12 | ||
|
|
a3b576abd8 | ||
|
|
2261eac288 | ||
|
|
9366729d7a | ||
|
|
ad1a4fe450 | ||
|
|
9f97725894 | ||
|
|
bff3d27518 | ||
|
|
2bc1192ad3 | ||
|
|
f165131da8 | ||
|
|
afd29fef81 | ||
|
|
071a4f97e5 | ||
|
|
04c990de89 | ||
|
|
b08ffcc437 | ||
|
|
7156df8d9a | ||
|
|
1a83e69669 | ||
|
|
210d4f6aa1 | ||
|
|
b559506d4e | ||
|
|
3fec6ff5bc | ||
|
|
ce74307172 | ||
|
|
e44e68f8fc | ||
|
|
eff1341088 | ||
|
|
ddd35e3d80 | ||
|
|
265272b9d3 | ||
|
|
206e34ac80 | ||
|
|
ea556ff201 | ||
|
|
110dc751a4 | ||
|
|
46546def28 | ||
|
|
48de14ade3 | ||
|
|
f74647ccfc | ||
|
|
b92a85f0a9 | ||
|
|
853965e7a9 | ||
|
|
6f9dd8d7cd | ||
|
|
905eb1a93f | ||
|
|
7862fc7cb7 | ||
|
|
903168b3a6 | ||
|
|
5e8fcb579f | ||
|
|
fae018b4ea | ||
|
|
dc0e278a24 | ||
|
|
aaa34ab860 | ||
|
|
66638cab33 | ||
|
|
a729a61100 | ||
|
|
23b39c6a63 | ||
|
|
37467d3753 | ||
|
|
8d3a378761 | ||
|
|
3993f9c2bb | ||
|
|
b542762dce | ||
|
|
35b2ea870d | ||
|
|
b2605dd30c | ||
|
|
18b04e2999 | ||
|
|
54c2dedac0 | ||
|
|
0efa6661b8 | ||
|
|
42d0532580 | ||
|
|
8d5f7c8d3e | ||
|
|
04214200b8 | ||
|
|
99229513ba | ||
|
|
c3a992e6d4 | ||
|
|
e15c80927b | ||
|
|
e918a0bf26 | ||
|
|
35bff8cc67 | ||
|
|
0998ae753c | ||
|
|
7bb6506709 | ||
|
|
64f80312de | ||
|
|
ce2eed28c1 | ||
|
|
505fa91d7d | ||
|
|
dd7e6d3831 | ||
|
|
b086337dbe | ||
|
|
49562f50f2 | ||
|
|
884ec05a1e | ||
|
|
212d7f1865 | ||
|
|
9ab8a2cbd2 | ||
|
|
f633eddd73 | ||
|
|
f5761ee69d | ||
|
|
b8cdc0f145 | ||
|
|
b5eea2136b | ||
|
|
deded47da2 | ||
|
|
fdc0e2597d | ||
|
|
da5b0260f2 | ||
|
|
beb960b753 | ||
|
|
5cc338dedc | ||
|
|
15be42340d | ||
|
|
f10bee8cb0 | ||
|
|
eadf18821f | ||
|
|
56b1c7b11a | ||
|
|
e4513976f7 | ||
|
|
b71ea3852e | ||
|
|
ae6c29ccff | ||
|
|
1820e79617 | ||
|
|
2a95b7a37c | ||
|
|
fb95df66c9 | ||
|
|
3c76284d89 | ||
|
|
29967fde50 | ||
|
|
bd65e4084c | ||
|
|
a2a9977af6 | ||
|
|
0369b490b8 | ||
|
|
d9e5821d31 | ||
|
|
54a7df8d40 | ||
|
|
17ed502123 | ||
|
|
56eef2ec94 | ||
|
|
200036efc9 | ||
|
|
7fa7f4ed8a | ||
|
|
3466325d4d | ||
|
|
1613345dec | ||
|
|
759accef07 | ||
|
|
6d02669fc3 | ||
|
|
6d8d688063 | ||
|
|
5207bdfd85 | ||
|
|
690d4238e8 | ||
|
|
95ee78b1bd | ||
|
|
25eadc2263 | ||
|
|
28e4065890 | ||
|
|
e44388b506 | ||
|
|
540dea9fc3 | ||
|
|
c31290b794 | ||
|
|
f1fe4c0c70 | ||
|
|
921ac18876 | ||
|
|
505ad0380e | ||
|
|
2b7a7c0054 | ||
|
|
0dea4c51b7 | ||
|
|
3095f2110e | ||
|
|
e32d35b156 | ||
|
|
db28336e5d | ||
|
|
c5c5accaa8 | ||
|
|
78bfdd4515 | ||
|
|
01aa826a24 | ||
|
|
7f2506d8a6 | ||
|
|
7c2f7b6338 | ||
|
|
5f05de30a6 | ||
|
|
7741de7ae0 | ||
|
|
d4c8e8c50e | ||
|
|
bf36ff9cb9 | ||
|
|
8eadccdee2 | ||
|
|
b32839292c | ||
|
|
2402443dcc | ||
|
|
9f72c98967 | ||
|
|
f6f744aea1 | ||
|
|
cddc55694a | ||
|
|
8930e2f06e | ||
|
|
b8e5e130b9 | ||
|
|
a8c5087a38 | ||
|
|
d9f21e0475 | ||
|
|
ca3fa3dc40 | ||
|
|
ddd0a42b26 | ||
|
|
f884627927 | ||
|
|
9373cf9cf6 | ||
|
|
f04030904e | ||
|
|
271b2a0417 | ||
|
|
a4f7393fc8 | ||
|
|
8f851beda1 | ||
|
|
4489efa8d9 | ||
|
|
8b9084cb73 | ||
|
|
1146453dc2 | ||
|
|
bd54395948 | ||
|
|
89ac27ba97 | ||
|
|
74eaee53a4 | ||
|
|
20e4261aa7 | ||
|
|
312189fbde | ||
|
|
d05063ec61 | ||
|
|
47c14db54c | ||
|
|
f0e0650244 | ||
|
|
d2a68e62e9 | ||
|
|
09fbbc1e17 | ||
|
|
8971822247 | ||
|
|
1f0d1920bf | ||
|
|
cb7c8502b0 | ||
|
|
27d1f79839 | ||
|
|
83ef21e699 | ||
|
|
6c592669da | ||
|
|
88f7687646 | ||
|
|
f12a527ae3 | ||
|
|
7dde0be043 | ||
|
|
2910f4f527 | ||
|
|
93c0df33c2 | ||
|
|
7d9f6eef27 | ||
|
|
7d742d62b8 | ||
|
|
4db80cb9e7 | ||
|
|
addfbcb68f | ||
|
|
fac46d9d0b | ||
|
|
e38ff08de2 | ||
|
|
c31e2d91dd | ||
|
|
7309fec51d | ||
|
|
2e01fa738a | ||
|
|
9044925f32 | ||
|
|
2d5ff8252c | ||
|
|
072110481f | ||
|
|
0fb0532875 | ||
|
|
d8dd94c679 | ||
|
|
f3d7736acf | ||
|
|
8fbf5590f8 | ||
|
|
b8ac93045e | ||
|
|
89fea9b4df | ||
|
|
a3323dc8a7 | ||
|
|
ba0505c13c | ||
|
|
dd8432e8fd | ||
|
|
11c7f57745 | ||
|
|
89a3fac316 | ||
|
|
b0b3e92600 | ||
|
|
1fca035cfe | ||
|
|
4c89bb0e0a | ||
|
|
332508f563 | ||
|
|
158d11e93c | ||
|
|
18a49601a0 | ||
|
|
b971b4754f | ||
|
|
cfef22257e | ||
|
|
3153d8ee8c | ||
|
|
b2a975fe4a | ||
|
|
b2ba505954 | ||
|
|
a1b673175a | ||
|
|
d666de07a7 | ||
|
|
64508cec61 | ||
|
|
e0bcb625c2 | ||
|
|
9534e765e5 | ||
|
|
39124d2878 | ||
|
|
9ae4d66194 | ||
|
|
09850d7500 | ||
|
|
8897d9179c | ||
|
|
2d1b9d64bd | ||
|
|
e603a1707c | ||
|
|
6b1e7a1c5d | ||
|
|
5acd4b5fd4 | ||
|
|
9e88adb0da | ||
|
|
69eaf0d338 | ||
|
|
680de2dca1 | ||
|
|
837188f8d1 | ||
|
|
4a696b4053 | ||
|
|
0b2c4679fd | ||
|
|
5a08c92d02 | ||
|
|
faf93441f6 | ||
|
|
8aa3608a3c | ||
|
|
9727a9d000 | ||
|
|
1b74289c43 | ||
|
|
a698ff8309 | ||
|
|
5026c48805 | ||
|
|
2ac63b6985 | ||
|
|
114e11f52a | ||
|
|
3277d1baac | ||
|
|
f3d8ec040c | ||
|
|
0a29e9b3cf | ||
|
|
4b7c17ac03 | ||
|
|
1849f4c11d | ||
|
|
b9f61466ba | ||
|
|
d8fa9b8c4f | ||
|
|
42bc80e5b5 | ||
|
|
9f7446ba56 | ||
|
|
7bdea1befa | ||
|
|
66ec087416 | ||
|
|
9b4d1d442e | ||
|
|
16a30fa3b7 | ||
|
|
1cd3ebfc3f | ||
|
|
fd170df98f | ||
|
|
a2291b0713 | ||
|
|
3134ff81f4 | ||
|
|
072bc514f4 | ||
|
|
581a79f3fc | ||
|
|
cccb8e9645 | ||
|
|
646fcafa62 | ||
|
|
615453a687 | ||
|
|
361a1a21ac | ||
|
|
e3e3311dd0 | ||
|
|
74fa9a6b2b | ||
|
|
b62faef520 | ||
|
|
74391d59a5 | ||
|
|
1c08b3e5e4 | ||
|
|
8c489c2131 | ||
|
|
19976939b7 | ||
|
|
4e1659b98d | ||
|
|
26ef8deca5 | ||
|
|
4e5fe5ae1a | ||
|
|
7f308f59b4 | ||
|
|
f4e8bb6c66 | ||
|
|
e3638053d0 | ||
|
|
d688d8812d | ||
|
|
4a6bf38666 | ||
|
|
f532b62913 | ||
|
|
0080c8457f | ||
|
|
613904e3a4 | ||
|
|
753a093689 | ||
|
|
ea6f8ce4d9 | ||
|
|
180359e148 | ||
|
|
5816443ad3 | ||
|
|
e9fce9223e | ||
|
|
f6c43eaf9c | ||
|
|
8af71be551 | ||
|
|
9e36702eb2 | ||
|
|
cda6f89dba | ||
|
|
b8d7744563 | ||
|
|
25dcae7648 | ||
|
|
ee6382ef03 | ||
|
|
0310192660 | ||
|
|
c88bc65379 | ||
|
|
37340dc549 | ||
|
|
9b6764a852 | ||
|
|
b176857b8d | ||
|
|
f034065247 | ||
|
|
64bd4dee38 | ||
|
|
22307239ae | ||
|
|
3fc7ffadbf | ||
|
|
b87a80a32d | ||
|
|
c775de260a | ||
|
|
30fd358286 | ||
|
|
71c3d484a9 | ||
|
|
66bac32e33 | ||
|
|
4f0ea888ef | ||
|
|
bc1a83d04a | ||
|
|
32d9fc0d32 | ||
|
|
41bd3704ef | ||
|
|
be75b5b237 | ||
|
|
3a7da6665f | ||
|
|
2f47e04de7 | ||
|
|
7dc3add5fd | ||
|
|
8b296534a4 | ||
|
|
f9c4cefe59 | ||
|
|
d772eaf4a2 | ||
|
|
27ec1a13da | ||
|
|
07e8dfa257 | ||
|
|
0fbf48ab4d | ||
|
|
f38a0d2d67 | ||
|
|
b76875bf5d | ||
|
|
0253de80de | ||
|
|
647575261e | ||
|
|
3c2b348ce5 | ||
|
|
8aef6ca372 | ||
|
|
0139437c3d | ||
|
|
a7b91ee57d | ||
|
|
ad0117e060 | ||
|
|
309d70c142 | ||
|
|
c9ff59a433 | ||
|
|
ec9a1416a1 | ||
|
|
dac622fc46 | ||
|
|
92e2daf056 | ||
|
|
08e68a1cff | ||
|
|
8f4be9b76f | ||
|
|
fab6ec94fa | ||
|
|
5cbcb901f1 | ||
|
|
4d075818f6 | ||
|
|
4302be5619 | ||
|
|
68d1be3b94 | ||
|
|
af68b10c5d | ||
|
|
8b16d0e7ed | ||
|
|
2d5c24d8b5 | ||
|
|
0110ac62bf | ||
|
|
5bfa44b1b4 | ||
|
|
d21821a0fb | ||
|
|
84dfde2e51 | ||
|
|
22d33fa286 | ||
|
|
f6f83e2114 | ||
|
|
c6ad734de0 | ||
|
|
cf015b2ce7 | ||
|
|
fbe8086c98 | ||
|
|
95cae6e7de | ||
|
|
d12fd78ef0 | ||
|
|
b2d9f835bf | ||
|
|
735772f43a | ||
|
|
75f66a6cb2 | ||
|
|
24d5dfe3c6 | ||
|
|
be9e953971 | ||
|
|
82e67b7550 | ||
|
|
791549fda8 | ||
|
|
c763783d53 | ||
|
|
e347e7e5fb | ||
|
|
3f1d0df7f9 | ||
|
|
c6cb6d5eeb | ||
|
|
57025f8173 | ||
|
|
3e7f07374c | ||
|
|
fba9cb071d | ||
|
|
c6538e1038 | ||
|
|
3a1a582013 | ||
|
|
531a484cb0 | ||
|
|
16c477229a | ||
|
|
f2565049b8 | ||
|
|
afdb5d7233 | ||
|
|
18be1202db | ||
|
|
14cc87e1a5 | ||
|
|
2a0d1b0a48 | ||
|
|
22aa126b29 | ||
|
|
feb2046549 | ||
|
|
2f362f2aa2 | ||
|
|
de160d9170 | ||
|
|
226c18cb56 | ||
|
|
314aea4e1e | ||
|
|
807d3a600c | ||
|
|
fa8ea1ef43 | ||
|
|
2017d4785b | ||
|
|
fd35724aa8 | ||
|
|
e1a85d97e3 | ||
|
|
b972c9fe30 | ||
|
|
4c68150dec | ||
|
|
3d6dd06b99 | ||
|
|
81759fa57a | ||
|
|
20160cb071 | ||
|
|
8931506657 | ||
|
|
2aee346299 | ||
|
|
f89efd84d3 | ||
|
|
7607ab2c84 | ||
|
|
fe7f6bee1c | ||
|
|
b43658eb3f | ||
|
|
85caa09e63 | ||
|
|
c32853bfd6 | ||
|
|
e79cd58c8f | ||
|
|
0d291f1a36 | ||
|
|
24aa8e2a07 | ||
|
|
0a0c155292 | ||
|
|
55a942aa22 | ||
|
|
b51499e87b | ||
|
|
936048d478 | ||
|
|
bd6497743c | ||
|
|
6873d8d445 | ||
|
|
21c9dde858 | ||
|
|
17d3d620ff | ||
|
|
705603a088 | ||
|
|
ba8a0179d5 | ||
|
|
9fe10747ce | ||
|
|
4a4d9a9377 | ||
|
|
2e7342a59c | ||
|
|
c9bc5be42b | ||
|
|
b75b36dc61 | ||
|
|
1e6a1bd3af | ||
|
|
b0a2087015 | ||
|
|
a5ee34a2db | ||
|
|
a6a8130234 | ||
|
|
288761632f | ||
|
|
25bf4fa738 | ||
|
|
3b4de6a405 | ||
|
|
75512602c3 | ||
|
|
cd33a089d1 | ||
|
|
6b83281539 | ||
|
|
2609671982 | ||
|
|
accf2c0e5e | ||
|
|
53f6e66c23 | ||
|
|
56ddcc8e29 | ||
|
|
430779979e | ||
|
|
671dbcfd55 | ||
|
|
087a7b5f3c | ||
|
|
229844d399 | ||
|
|
36081653b0 | ||
|
|
9811c5d577 | ||
|
|
4394186dc3 | ||
|
|
725b48d8aa | ||
|
|
3fd8347943 | ||
|
|
5e7c26c34b | ||
|
|
d7019264a2 | ||
|
|
ade9fa5d0e | ||
|
|
f84c4393b9 | ||
|
|
48d01c0ab5 | ||
|
|
aca01d81d6 | ||
|
|
6a0b154d67 | ||
|
|
7ce69987d5 | ||
|
|
3fe28d5441 | ||
|
|
43f42f9ca0 | ||
|
|
3e288f1fcf | ||
|
|
8ccd75fdfb | ||
|
|
fd6aa6e54e | ||
|
|
4802a2ce82 | ||
|
|
e3409a27e7 | ||
|
|
5182edce6f | ||
|
|
763d8d025e | ||
|
|
a3045c9808 | ||
|
|
6b78b011b7 | ||
|
|
bd7b84e136 | ||
|
|
2a9bab3f13 | ||
|
|
6ca1e6c6dd | ||
|
|
f3a1a6a191 | ||
|
|
675932c65b | ||
|
|
708abb0e30 | ||
|
|
9de84aee2e | ||
|
|
adb8779d00 | ||
|
|
fbb0e675f5 | ||
|
|
a3e2b5246e | ||
|
|
ccacac0597 | ||
|
|
ca230aa230 | ||
|
|
7b775d2ad7 | ||
|
|
c5397bfbe2 | ||
|
|
9fec6ebc66 | ||
|
|
6bc38c5782 | ||
|
|
7f9d585d7f | ||
|
|
0b14d36c95 | ||
|
|
e22ca2d082 | ||
|
|
52a70cb7f5 | ||
|
|
a00d1d068a | ||
|
|
6ae4ed9fc3 | ||
|
|
6f5028612a | ||
|
|
c31c12d31a | ||
|
|
28008d835e | ||
|
|
08e99a32cb | ||
|
|
68fc87bc01 | ||
|
|
d0ba06c44b | ||
|
|
d501cbf765 | ||
|
|
488c7e6c27 | ||
|
|
155559c2c4 | ||
|
|
a22e1bc5e5 | ||
|
|
9519d3f7ce | ||
|
|
3f23e07c02 | ||
|
|
6c75177edc | ||
|
|
85df280447 | ||
|
|
734cf243f6 | ||
|
|
d8f7817eeb | ||
|
|
94b6b2636a | ||
|
|
1036f7580f | ||
|
|
908febb363 | ||
|
|
aefd091b44 | ||
|
|
99fb82e244 | ||
|
|
756d6620cc | ||
|
|
09505dba09 | ||
|
|
9401eff297 | ||
|
|
adbec3d272 | ||
|
|
e301ba0cdb | ||
|
|
b12eef218a | ||
|
|
bc4560877a | ||
|
|
521a740d3a | ||
|
|
be12b724cc | ||
|
|
073873a3e9 | ||
|
|
fcdcb50b8b | ||
|
|
61a7848fd9 | ||
|
|
6d6b840cf6 | ||
|
|
4dbba103d4 | ||
|
|
a2932f05f4 | ||
|
|
5d4efb7692 | ||
|
|
39a9efb73b | ||
|
|
5037bd07d5 | ||
|
|
73a2fa3f9c | ||
|
|
79387f469b | ||
|
|
f986cfecff | ||
|
|
4d51a9123b | ||
|
|
7602f15544 | ||
|
|
3180ba7de9 | ||
|
|
3e01cf19b0 | ||
|
|
14eebfe39e | ||
|
|
9176599b29 | ||
|
|
d6575faa9f | ||
|
|
24c5bf9ff4 | ||
|
|
cdcc5e106f | ||
|
|
1a8cc2d019 | ||
|
|
27e907491b | ||
|
|
0a1e6623c8 | ||
|
|
689dddd11a | ||
|
|
f8d01e1596 | ||
|
|
cd429f5935 | ||
|
|
03355f6a4a | ||
|
|
dc1d593019 | ||
|
|
9894cceeaa | ||
|
|
bcedbc845e | ||
|
|
f508288ce3 | ||
|
|
18080cef9f | ||
|
|
c4eeef2a86 | ||
|
|
b60a91f53c | ||
|
|
b1c3de6518 | ||
|
|
a43a6a299c | ||
|
|
d8fae5bc41 | ||
|
|
fa9b6f58e5 | ||
|
|
89ff1411e9 | ||
|
|
701e8277d6 | ||
|
|
4a11f80c45 | ||
|
|
f1b275d5d0 | ||
|
|
68e0ffc95c | ||
|
|
0753eb7691 | ||
|
|
92afcd174d | ||
|
|
94be7a0e79 | ||
|
|
0814daf99d | ||
|
|
b2e3419bff | ||
|
|
1846d0bc21 | ||
|
|
d282055e10 | ||
|
|
6ab64d155b | ||
|
|
6ba3e57f5f | ||
|
|
14fe4f65e1 | ||
|
|
bdb70444d6 | ||
|
|
4d9cc55a87 | ||
|
|
f41c1cbfd0 | ||
|
|
72eaab68be | ||
|
|
733c6b4c17 | ||
|
|
c0c0694fcc | ||
|
|
055530c8c6 | ||
|
|
fb3b38aec7 | ||
|
|
4e4a8f1bab | ||
|
|
39b3786776 | ||
|
|
8b22313ca1 | ||
|
|
402f72cfa8 | ||
|
|
e7dcb8a605 | ||
|
|
8f8a1fda85 | ||
|
|
26be25c3d5 | ||
|
|
50b53b00e0 | ||
|
|
94531cb3d0 | ||
|
|
842760255b | ||
|
|
c78b582d71 | ||
|
|
4ab02fab1c | ||
|
|
6863f3227f | ||
|
|
d01d43eccb | ||
|
|
2aa5f4fc82 | ||
|
|
3af0531111 | ||
|
|
6e58b98b3d | ||
|
|
62805cdf1d | ||
|
|
4229b1d2a4 | ||
|
|
2c4661a250 | ||
|
|
0c1a486ed9 | ||
|
|
688cb55c2b | ||
|
|
1594f148f8 | ||
|
|
fafd8c4af1 | ||
|
|
3d66758507 | ||
|
|
fc0ec860b0 | ||
|
|
00d332cd16 | ||
|
|
4c8c0f8738 | ||
|
|
54978132bb | ||
|
|
018abe0188 | ||
|
|
b186497fb0 | ||
|
|
27f9963ccb | ||
|
|
a4e3f03bf5 | ||
|
|
27a6be4ce0 | ||
|
|
76a2520e56 | ||
|
|
0a472681af | ||
|
|
6d530691f3 | ||
|
|
a74c9e8481 | ||
|
|
8aac26a331 | ||
|
|
fc59a0f6ab | ||
|
|
3fb16774b7 | ||
|
|
7b35bb4c0f | ||
|
|
318e2bd1c6 | ||
|
|
09ba4bcf43 | ||
|
|
0c89fa7b1e | ||
|
|
7eedb3320d | ||
|
|
cfac75ea49 | ||
|
|
f00a6c396f | ||
|
|
e74a9711ca | ||
|
|
636d3cdf90 | ||
|
|
71966affa1 | ||
|
|
bf4dc195ec | ||
|
|
dccca17e09 | ||
|
|
5381a4354c | ||
|
|
c70425fbf7 | ||
|
|
341f5725a4 | ||
|
|
d7069df80d | ||
|
|
579714a60b | ||
|
|
bbdf63635a | ||
|
|
fd7db18221 | ||
|
|
482ed8d958 | ||
|
|
673e16878d | ||
|
|
e11ceab029 | ||
|
|
7fe719f43c | ||
|
|
3fd3ac1de1 | ||
|
|
0e90a675af | ||
|
|
ee861c1f91 | ||
|
|
40c9355088 | ||
|
|
8f1557254a | ||
|
|
11d28b0bc3 | ||
|
|
974cf780c0 | ||
|
|
73bb14e4a9 | ||
|
|
daf4236023 | ||
|
|
4c9a24c64e | ||
|
|
c149f65158 | ||
|
|
c5688c1bd3 | ||
|
|
b276a15786 | ||
|
|
2fed239ece | ||
|
|
8e2cb36597 | ||
|
|
bcaace1c91 | ||
|
|
d664d07141 | ||
|
|
cb8b80c856 | ||
|
|
d777d77b06 | ||
|
|
43678f8dc0 | ||
|
|
5811577824 | ||
|
|
1587122efa | ||
|
|
48e7c8ad0f | ||
|
|
766f9798f6 | ||
|
|
680d634725 | ||
|
|
7ac945bf88 | ||
|
|
188d7a8558 | ||
|
|
ee561b0d1e | ||
|
|
82bbe78e95 | ||
|
|
c761cd059b | ||
|
|
03e87155ca | ||
|
|
ea39cc52b1 | ||
|
|
90fb90b186 | ||
|
|
5f8327eaf7 | ||
|
|
07869f3c48 | ||
|
|
8377eb02a5 | ||
|
|
3738e8eb44 | ||
|
|
4b000e44b3 | ||
|
|
d6021d1702 | ||
|
|
b391eafc38 | ||
|
|
2af4545e10 | ||
|
|
b96644d893 | ||
|
|
3cb77c0a32 | ||
|
|
b3f7fb7be3 | ||
|
|
9fb51a1f29 | ||
|
|
d78e8a725d | ||
|
|
7829bdbc95 | ||
|
|
90ba6deba2 | ||
|
|
5fc763a738 | ||
|
|
84614e903c | ||
|
|
c95d739347 | ||
|
|
c55849cef5 | ||
|
|
88adb09417 | ||
|
|
cb356ffca9 | ||
|
|
2ba3f252ee | ||
|
|
ebe2c8e3dd | ||
|
|
ca2d63edcf | ||
|
|
489a1a1c37 | ||
|
|
5cad13eea3 | ||
|
|
a3e09e015c | ||
|
|
22a6accac1 | ||
|
|
277c97a959 | ||
|
|
c08bc3239a | ||
|
|
f798c7e0fb | ||
|
|
193780a88f | ||
|
|
ab4973ab6c | ||
|
|
f9da815e8f | ||
|
|
59e187d59a | ||
|
|
3b018e2a6d | ||
|
|
d4939c8260 | ||
|
|
485352594c | ||
|
|
bcdcfee467 | ||
|
|
0217e3fcae | ||
|
|
6e7d6421d5 | ||
|
|
913d3af938 | ||
|
|
53dd0a5e4c |
39
.github/actions/install/action.yml
vendored
39
.github/actions/install/action.yml
vendored
@@ -2,10 +2,6 @@ name: "Browsercore install"
|
||||
description: "Install deps for the project browsercore"
|
||||
|
||||
inputs:
|
||||
zig:
|
||||
description: 'Zig version to install'
|
||||
required: false
|
||||
default: '0.13.0'
|
||||
arch:
|
||||
description: 'CPU arch used to select the v8 lib'
|
||||
required: false
|
||||
@@ -17,11 +13,11 @@ inputs:
|
||||
zig-v8:
|
||||
description: 'zig v8 version to install'
|
||||
required: false
|
||||
default: 'v0.1.9'
|
||||
default: 'v0.2.2'
|
||||
v8:
|
||||
description: 'v8 version to install'
|
||||
required: false
|
||||
default: '11.1.134'
|
||||
default: '14.0.365.4'
|
||||
cache-dir:
|
||||
description: 'cache dir to use'
|
||||
required: false
|
||||
@@ -34,11 +30,15 @@ runs:
|
||||
- name: Install apt deps
|
||||
if: ${{ inputs.os == 'linux' }}
|
||||
shell: bash
|
||||
run: sudo apt-get install -y wget xz-utils python3 ca-certificates git pkg-config libglib2.0-dev gperf libexpat1-dev cmake clang
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y wget xz-utils python3 ca-certificates git pkg-config libglib2.0-dev gperf libexpat1-dev cmake clang
|
||||
|
||||
- uses: mlugg/setup-zig@v1
|
||||
with:
|
||||
version: ${{ inputs.zig }}
|
||||
# Zig version used from the `minimum_zig_version` field in build.zig.zon
|
||||
- uses: mlugg/setup-zig@v2
|
||||
|
||||
# Rust Toolchain for html5ever
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Cache v8
|
||||
id: cache-v8
|
||||
@@ -59,20 +59,5 @@ runs:
|
||||
- name: install v8
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p vendor/zig-js-runtime/vendor/v8/${{inputs.arch}}-${{inputs.os}}/debug
|
||||
ln -s ${{ inputs.cache-dir }}/v8/libc_v8.a vendor/zig-js-runtime/vendor/v8/${{inputs.arch}}-${{inputs.os}}/debug/libc_v8.a
|
||||
|
||||
mkdir -p vendor/zig-js-runtime/vendor/v8/${{inputs.arch}}-${{inputs.os}}/release
|
||||
ln -s ${{ inputs.cache-dir }}/v8/libc_v8.a vendor/zig-js-runtime/vendor/v8/${{inputs.arch}}-${{inputs.os}}/release/libc_v8.a
|
||||
|
||||
- name: libiconv
|
||||
shell: bash
|
||||
run: make install-libiconv
|
||||
|
||||
- name: build mimalloc
|
||||
shell: bash
|
||||
run: make install-mimalloc
|
||||
|
||||
- name: build netsurf
|
||||
shell: bash
|
||||
run: make install-netsurf
|
||||
mkdir -p v8
|
||||
ln -s ${{ inputs.cache-dir }}/v8/libc_v8.a v8/libc_v8.a
|
||||
|
||||
135
.github/workflows/build.yml
vendored
135
.github/workflows/build.yml
vendored
@@ -1,6 +1,16 @@
|
||||
name: nightly build
|
||||
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ vars.NIGHTLY_BUILD_AWS_ACCESS_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.NIGHTLY_BUILD_AWS_SECRET_ACCESS_KEY }}
|
||||
AWS_BUCKET: ${{ vars.NIGHTLY_BUILD_AWS_BUCKET }}
|
||||
AWS_REGION: ${{ vars.NIGHTLY_BUILD_AWS_REGION }}
|
||||
RELEASE: ${{ github.ref_type == 'tag' && github.ref_name || 'nightly' }}
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
schedule:
|
||||
- cron: "2 2 * * *"
|
||||
|
||||
@@ -17,35 +27,49 @@ jobs:
|
||||
OS: linux
|
||||
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
# fetch submodules recusively, to get zig-js-runtime submodules also.
|
||||
submodules: recursive
|
||||
|
||||
- uses: ./.github/actions/install
|
||||
with:
|
||||
os: ${{env.OS}}
|
||||
arch: ${{env.ARCH}}
|
||||
mode: 'release'
|
||||
|
||||
- name: v8 snapshot
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin
|
||||
|
||||
- name: zig build
|
||||
run: zig build --release=safe -Doptimize=ReleaseSafe -Dengine=v8 -Dcpu=x86_64
|
||||
run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=x86_64 -Dgit_commit=$(git rev-parse --short ${{ github.sha }})
|
||||
|
||||
- name: Rename binary
|
||||
run: mv zig-out/bin/lightpanda lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
|
||||
- name: upload on s3
|
||||
run: |
|
||||
export DIR=`git show --no-patch --no-notes --pretty='%cs_%h'`
|
||||
aws s3 cp --storage-class=GLACIER_IR lightpanda-${{ env.ARCH }}-${{ env.OS }} s3://lpd-nightly-build/${DIR}/lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
|
||||
- name: Upload the build
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
allowUpdates: true
|
||||
artifacts: lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
tag: nightly
|
||||
tag: ${{ env.RELEASE }}
|
||||
|
||||
build-macos-aarch64:
|
||||
build-linux-aarch64:
|
||||
env:
|
||||
ARCH: aarch64
|
||||
OS: macos
|
||||
OS: linux
|
||||
|
||||
runs-on: macos-latest
|
||||
runs-on: ubuntu-22.04-arm
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -58,16 +82,111 @@ jobs:
|
||||
with:
|
||||
os: ${{env.OS}}
|
||||
arch: ${{env.ARCH}}
|
||||
mode: 'release'
|
||||
|
||||
- name: v8 snapshot
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin
|
||||
|
||||
- name: zig build
|
||||
run: zig build --release=safe -Doptimize=ReleaseSafe -Dengine=v8
|
||||
run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=generic -Dgit_commit=$(git rev-parse --short ${{ github.sha }})
|
||||
|
||||
- name: Rename binary
|
||||
run: mv zig-out/bin/lightpanda lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
|
||||
- name: upload on s3
|
||||
run: |
|
||||
export DIR=`git show --no-patch --no-notes --pretty='%cs_%h'`
|
||||
aws s3 cp --storage-class=GLACIER_IR lightpanda-${{ env.ARCH }}-${{ env.OS }} s3://lpd-nightly-build/${DIR}/lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
|
||||
- name: Upload the build
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
allowUpdates: true
|
||||
artifacts: lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
tag: nightly
|
||||
tag: ${{ env.RELEASE }}
|
||||
|
||||
build-macos-aarch64:
|
||||
env:
|
||||
ARCH: aarch64
|
||||
OS: macos
|
||||
|
||||
# macos-14 runs on arm CPU. see
|
||||
# https://github.com/actions/runner-images?tab=readme-ov-file
|
||||
runs-on: macos-14
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
# fetch submodules recusively, to get zig-js-runtime submodules also.
|
||||
submodules: recursive
|
||||
|
||||
- uses: ./.github/actions/install
|
||||
with:
|
||||
os: ${{env.OS}}
|
||||
arch: ${{env.ARCH}}
|
||||
mode: 'release'
|
||||
|
||||
- name: v8 snapshot
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin
|
||||
|
||||
- name: zig build
|
||||
run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dgit_commit=$(git rev-parse --short ${{ github.sha }})
|
||||
|
||||
- name: Rename binary
|
||||
run: mv zig-out/bin/lightpanda lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
|
||||
- name: upload on s3
|
||||
run: |
|
||||
export DIR=`git show --no-patch --no-notes --pretty='%cs_%h'`
|
||||
aws s3 cp --storage-class=GLACIER_IR lightpanda-${{ env.ARCH }}-${{ env.OS }} s3://lpd-nightly-build/${DIR}/lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
|
||||
- name: Upload the build
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
allowUpdates: true
|
||||
artifacts: lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
tag: ${{ env.RELEASE }}
|
||||
|
||||
build-macos-x86_64:
|
||||
env:
|
||||
ARCH: x86_64
|
||||
OS: macos
|
||||
|
||||
runs-on: macos-14-large
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
# fetch submodules recusively, to get zig-js-runtime submodules also.
|
||||
submodules: recursive
|
||||
|
||||
- uses: ./.github/actions/install
|
||||
with:
|
||||
os: ${{env.OS}}
|
||||
arch: ${{env.ARCH}}
|
||||
mode: 'release'
|
||||
|
||||
- name: v8 snapshot
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin
|
||||
|
||||
- name: zig build
|
||||
run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dgit_commit=$(git rev-parse --short ${{ github.sha }})
|
||||
|
||||
- name: Rename binary
|
||||
run: mv zig-out/bin/lightpanda lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
|
||||
- name: upload on s3
|
||||
run: |
|
||||
export DIR=`git show --no-patch --no-notes --pretty='%cs_%h'`
|
||||
aws s3 cp --storage-class=GLACIER_IR lightpanda-${{ env.ARCH }}-${{ env.OS }} s3://lpd-nightly-build/${DIR}/lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
|
||||
- name: Upload the build
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
allowUpdates: true
|
||||
artifacts: lightpanda-${{ env.ARCH }}-${{ env.OS }}
|
||||
tag: ${{ env.RELEASE }}
|
||||
|
||||
4
.github/workflows/cla.yml
vendored
4
.github/workflows/cla.yml
vendored
@@ -14,6 +14,8 @@ permissions:
|
||||
jobs:
|
||||
CLAAssistant:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
|
||||
steps:
|
||||
- name: "CLA Assistant"
|
||||
if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target'
|
||||
@@ -26,7 +28,7 @@ jobs:
|
||||
path-to-document: 'https://github.com/lightpanda-io/browser/blob/main/CLA.md'
|
||||
# branch should not be protected
|
||||
branch: 'main'
|
||||
allowlist: krichprollsch,francisbouvier
|
||||
allowlist: krichprollsch,francisbouvier,katie-lpd,sjorsdonkers,bornlex
|
||||
|
||||
remote-organization-name: lightpanda-io
|
||||
remote-repository-name: cla
|
||||
|
||||
68
.github/workflows/e2e-integration-test.yml
vendored
Normal file
68
.github/workflows/e2e-integration-test.yml
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
name: e2e-integration-test
|
||||
|
||||
env:
|
||||
LIGHTPANDA_DISABLE_TELEMETRY: true
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "4 4 * * *"
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
zig-build-release:
|
||||
name: zig build release
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
# Don't run the CI with draft PR.
|
||||
if: github.event.pull_request.draft == false
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
# fetch submodules recusively, to get zig-js-runtime submodules also.
|
||||
submodules: recursive
|
||||
|
||||
- uses: ./.github/actions/install
|
||||
|
||||
- name: zig build release
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=x86_64 -Dgit_commit=$(git rev-parse --short ${{ github.sha }})
|
||||
|
||||
- name: upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: lightpanda-build-release
|
||||
path: |
|
||||
zig-out/bin/lightpanda
|
||||
retention-days: 1
|
||||
|
||||
demo-scripts:
|
||||
name: demo-integration-scripts
|
||||
needs: zig-build-release
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: 'lightpanda-io/demo'
|
||||
fetch-depth: 0
|
||||
|
||||
- run: npm install
|
||||
|
||||
- name: download artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: lightpanda-build-release
|
||||
|
||||
- run: chmod a+x ./lightpanda
|
||||
|
||||
- name: run end to end integration tests
|
||||
run: |
|
||||
./lightpanda serve & echo $! > LPD.pid
|
||||
go run integration/main.go
|
||||
kill `cat LPD.pid`
|
||||
234
.github/workflows/e2e-test.yml
vendored
Normal file
234
.github/workflows/e2e-test.yml
vendored
Normal file
@@ -0,0 +1,234 @@
|
||||
name: e2e-test
|
||||
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ vars.LPD_PERF_AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.LPD_PERF_AWS_SECRET_ACCESS_KEY }}
|
||||
AWS_BUCKET: ${{ vars.LPD_PERF_AWS_BUCKET }}
|
||||
AWS_REGION: ${{ vars.LPD_PERF_AWS_REGION }}
|
||||
LIGHTPANDA_DISABLE_TELEMETRY: true
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "build.zig"
|
||||
- "src/**/*.zig"
|
||||
- "src/*.zig"
|
||||
- "vendor/zig-js-runtime"
|
||||
- ".github/**"
|
||||
- "vendor/**"
|
||||
pull_request:
|
||||
|
||||
# By default GH trigger on types opened, synchronize and reopened.
|
||||
# see https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request
|
||||
# Since we skip the job when the PR is in draft state, we want to force CI
|
||||
# running when the PR is marked ready_for_review w/o other change.
|
||||
# see https://github.com/orgs/community/discussions/25722#discussioncomment-3248917
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
paths:
|
||||
- ".github/**"
|
||||
- "build.zig"
|
||||
- "src/**/*.zig"
|
||||
- "src/*.zig"
|
||||
- "vendor/**"
|
||||
- ".github/**"
|
||||
- "vendor/**"
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
zig-build-release:
|
||||
name: zig build release
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
# Don't run the CI with draft PR.
|
||||
if: github.event.pull_request.draft == false
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
# fetch submodules recusively, to get zig-js-runtime submodules also.
|
||||
submodules: recursive
|
||||
|
||||
- uses: ./.github/actions/install
|
||||
with:
|
||||
mode: 'release'
|
||||
|
||||
- name: zig build release
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=x86_64 -Dgit_commit=$(git rev-parse --short ${{ github.sha }})
|
||||
|
||||
- name: upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: lightpanda-build-release
|
||||
path: |
|
||||
zig-out/bin/lightpanda
|
||||
retention-days: 1
|
||||
|
||||
demo-scripts:
|
||||
name: demo-scripts
|
||||
needs: zig-build-release
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: 'lightpanda-io/demo'
|
||||
fetch-depth: 0
|
||||
|
||||
- run: npm install
|
||||
|
||||
- name: download artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: lightpanda-build-release
|
||||
|
||||
- run: chmod a+x ./lightpanda
|
||||
|
||||
- name: run end to end tests
|
||||
run: |
|
||||
./lightpanda serve & echo $! > LPD.pid
|
||||
go run runner/main.go
|
||||
kill `cat LPD.pid`
|
||||
|
||||
- name: build proxy
|
||||
run: |
|
||||
cd proxy
|
||||
go build
|
||||
|
||||
- name: run end to end tests through proxy
|
||||
run: |
|
||||
./proxy/proxy & echo $! > PROXY.id
|
||||
./lightpanda serve --http_proxy 'http://127.0.0.1:3000' & echo $! > LPD.pid
|
||||
go run runner/main.go
|
||||
kill `cat LPD.pid` `cat PROXY.id`
|
||||
|
||||
- name: run request interception through proxy
|
||||
run: |
|
||||
export PROXY_USERNAME=username PROXY_PASSWORD=password
|
||||
./proxy/proxy & echo $! > PROXY.id
|
||||
./lightpanda serve & echo $! > LPD.pid
|
||||
URL=https://demo-browser.lightpanda.io/campfire-commerce/ node puppeteer/proxy_auth.js
|
||||
BASE_URL=https://demo-browser.lightpanda.io/ node playwright/proxy_auth.js
|
||||
kill `cat LPD.pid` `cat PROXY.id`
|
||||
|
||||
cdp-and-hyperfine-bench:
|
||||
name: cdp-and-hyperfine-bench
|
||||
needs: zig-build-release
|
||||
|
||||
env:
|
||||
MAX_MEMORY: 28000
|
||||
MAX_AVG_DURATION: 23
|
||||
LIGHTPANDA_DISABLE_TELEMETRY: true
|
||||
|
||||
# use a self host runner.
|
||||
runs-on: lpd-bench-hetzner
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: 'lightpanda-io/demo'
|
||||
fetch-depth: 0
|
||||
|
||||
- run: npm install
|
||||
|
||||
- name: download artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: lightpanda-build-release
|
||||
|
||||
- run: chmod a+x ./lightpanda
|
||||
|
||||
- name: start http
|
||||
run: |
|
||||
go run ws/main.go & echo $! > WS.pid
|
||||
sleep 2
|
||||
|
||||
- name: run puppeteer
|
||||
run: |
|
||||
./lightpanda serve & echo $! > LPD.pid
|
||||
sleep 2
|
||||
RUNS=100 npm run bench-puppeteer-cdp > puppeteer.out || exit 1
|
||||
cat /proc/`cat LPD.pid`/status |grep VmHWM|grep -oP '\d+' > LPD.VmHWM
|
||||
kill `cat LPD.pid`
|
||||
|
||||
- name: puppeteer result
|
||||
run: cat puppeteer.out
|
||||
|
||||
- name: memory regression
|
||||
run: |
|
||||
export LPD_VmHWM=`cat LPD.VmHWM`
|
||||
echo "Peak resident set size: $LPD_VmHWM"
|
||||
test "$LPD_VmHWM" -le "$MAX_MEMORY"
|
||||
|
||||
- name: duration regression
|
||||
run: |
|
||||
export PUPPETEER_AVG_DURATION=`cat puppeteer.out|grep 'avg run'|sed 's/avg run duration (ms) //'`
|
||||
echo "puppeteer avg duration: $PUPPETEER_AVG_DURATION"
|
||||
test "$PUPPETEER_AVG_DURATION" -le "$MAX_AVG_DURATION"
|
||||
|
||||
- name: json output
|
||||
run: |
|
||||
export AVG_DURATION=`cat puppeteer.out|grep 'avg run'|sed 's/avg run duration (ms) //'`
|
||||
export TOTAL_DURATION=`cat puppeteer.out|grep 'total duration'|sed 's/total duration (ms) //'`
|
||||
export LPD_VmHWM=`cat LPD.VmHWM`
|
||||
echo "{\"duration_total\":${TOTAL_DURATION},\"duration_avg\":${AVG_DURATION},\"mem_peak\":${LPD_VmHWM}}" > bench.json
|
||||
cat bench.json
|
||||
|
||||
- name: run hyperfine
|
||||
run: |
|
||||
hyperfine --export-json=hyperfine.json --warmup 3 --runs 20 --shell=none "./lightpanda --dump http://127.0.0.1:1234/campfire-commerce/"
|
||||
|
||||
- name: stop http
|
||||
run: kill `cat WS.pid`
|
||||
|
||||
- name: write commit
|
||||
run: |
|
||||
echo "${{github.sha}}" > commit.txt
|
||||
|
||||
- name: upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: bench-results
|
||||
path: |
|
||||
bench.json
|
||||
hyperfine.json
|
||||
commit.txt
|
||||
retention-days: 10
|
||||
|
||||
|
||||
perf-fmt:
|
||||
name: perf-fmt
|
||||
needs: cdp-and-hyperfine-bench
|
||||
|
||||
# Don't execute on PR
|
||||
if: github.event_name != 'pull_request'
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
container:
|
||||
image: ghcr.io/lightpanda-io/perf-fmt:latest
|
||||
credentials:
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
steps:
|
||||
- name: download artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: bench-results
|
||||
|
||||
- name: format and send json result
|
||||
run: /perf-fmt cdp ${{ github.sha }} bench.json
|
||||
|
||||
- name: format and send json result
|
||||
run: /perf-fmt hyperfine ${{ github.sha }} hyperfine.json
|
||||
51
.github/workflows/wpt.yml
vendored
51
.github/workflows/wpt.yml
vendored
@@ -5,49 +5,24 @@ env:
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.LPD_PERF_AWS_SECRET_ACCESS_KEY }}
|
||||
AWS_BUCKET: ${{ vars.LPD_PERF_AWS_BUCKET }}
|
||||
AWS_REGION: ${{ vars.LPD_PERF_AWS_REGION }}
|
||||
LIGHTPANDA_DISABLE_TELEMETRY: true
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "build.zig"
|
||||
- "src/**/*.zig"
|
||||
- "src/*.zig"
|
||||
- "tests/wpt/**"
|
||||
- "vendor/**"
|
||||
- ".github/**"
|
||||
pull_request:
|
||||
schedule:
|
||||
- cron: "23 2 * * *"
|
||||
|
||||
# By default GH trigger on types opened, synchronize and reopened.
|
||||
# see https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request
|
||||
# Since we skip the job when the PR is in draft state, we want to force CI
|
||||
# running when the PR is marked ready_for_review w/o other change.
|
||||
# see https://github.com/orgs/community/discussions/25722#discussioncomment-3248917
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
paths:
|
||||
- ".github/**"
|
||||
- "build.zig"
|
||||
- "src/**/*.zig"
|
||||
- "src/*.zig"
|
||||
- "tests/wpt/**"
|
||||
- "vendor/**"
|
||||
- ".github/**"
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
wpt:
|
||||
name: web platform tests
|
||||
|
||||
# Don't run the CI with draft PR.
|
||||
if: github.event.pull_request.draft == false
|
||||
name: web platform tests json output
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
# fetch submodules recusively, to get zig-js-runtime submodules also.
|
||||
@@ -55,15 +30,8 @@ jobs:
|
||||
|
||||
- uses: ./.github/actions/install
|
||||
|
||||
- run: zig build wpt -Dengine=v8 -- --safe --summary
|
||||
|
||||
# For now WPT tests doesn't pass at all.
|
||||
# We accept then to continue the job on failure.
|
||||
# TODO remove the continue-on-error when tests will pass.
|
||||
continue-on-error: true
|
||||
|
||||
- name: json output
|
||||
run: zig build wpt -Dengine=v8 -- --safe --json > wpt.json
|
||||
run: zig build wpt -- --json > wpt.json
|
||||
|
||||
- name: write commit
|
||||
run: |
|
||||
@@ -82,10 +50,9 @@ jobs:
|
||||
name: perf-fmt
|
||||
needs: wpt
|
||||
|
||||
# Don't execute on PR
|
||||
if: github.event_name != 'pull_request'
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
container:
|
||||
image: ghcr.io/lightpanda-io/perf-fmt:latest
|
||||
credentials:
|
||||
|
||||
14
.github/workflows/zig-fmt.yml
vendored
14
.github/workflows/zig-fmt.yml
vendored
@@ -1,8 +1,5 @@
|
||||
name: zig-fmt
|
||||
|
||||
env:
|
||||
ZIG_VERSION: 0.13.0
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
@@ -29,16 +26,16 @@ jobs:
|
||||
if: github.event.pull_request.draft == false
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: mlugg/setup-zig@v1
|
||||
with:
|
||||
version: ${{ env.ZIG_VERSION }}
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# Zig version used from the `minimum_zig_version` field in build.zig.zon
|
||||
- uses: mlugg/setup-zig@v2
|
||||
|
||||
- name: Run zig fmt
|
||||
id: fmt
|
||||
run: |
|
||||
@@ -57,6 +54,7 @@ jobs:
|
||||
fi
|
||||
|
||||
echo "${delimiter}" >> "${GITHUB_OUTPUT}"
|
||||
|
||||
- name: Fail the job
|
||||
if: steps.fmt.outputs.zig_fmt_errs != ''
|
||||
run: exit 1
|
||||
|
||||
41
.github/workflows/zig-test.yml
vendored
41
.github/workflows/zig-test.yml
vendored
@@ -16,6 +16,7 @@ on:
|
||||
- "src/*.zig"
|
||||
- "vendor/zig-js-runtime"
|
||||
- ".github/**"
|
||||
- "vendor/**"
|
||||
pull_request:
|
||||
|
||||
# By default GH trigger on types opened, synchronize and reopened.
|
||||
@@ -32,6 +33,7 @@ on:
|
||||
- "src/*.zig"
|
||||
- "vendor/**"
|
||||
- ".github/**"
|
||||
- "vendor/**"
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -45,39 +47,46 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
# fetch submodules recusively, to get zig-js-runtime submodules also.
|
||||
submodules: recursive
|
||||
|
||||
- uses: ./.github/actions/install
|
||||
|
||||
- name: zig build debug
|
||||
run: zig build -Dengine=v8
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a
|
||||
|
||||
zig-build-release:
|
||||
name: zig build release
|
||||
- name: upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: lightpanda-build-dev
|
||||
path: |
|
||||
zig-out/bin/lightpanda
|
||||
retention-days: 1
|
||||
|
||||
# Don't run the CI on PR
|
||||
if: github.event_name != 'pull_request'
|
||||
browser-fetch:
|
||||
name: browser fetch
|
||||
needs: zig-build-dev
|
||||
|
||||
# Don't run the CI with draft PR.
|
||||
if: github.event.pull_request.draft == false
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: download artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
# fetch submodules recusively, to get zig-js-runtime submodules also.
|
||||
submodules: recursive
|
||||
name: lightpanda-build-dev
|
||||
|
||||
- uses: ./.github/actions/install
|
||||
- run: chmod a+x ./lightpanda
|
||||
|
||||
- name: zig build release
|
||||
run: zig build -Doptimize=ReleaseSafe -Dengine=v8
|
||||
- run: ./lightpanda fetch https://httpbin.io/xhr/get
|
||||
|
||||
zig-test:
|
||||
name: zig test
|
||||
timeout-minutes: 15
|
||||
|
||||
# Don't run the CI with draft PR.
|
||||
if: github.event.pull_request.draft == false
|
||||
@@ -94,7 +103,7 @@ jobs:
|
||||
- uses: ./.github/actions/install
|
||||
|
||||
- name: zig build test
|
||||
run: zig build test -Dengine=v8 -- --json > bench.json
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a test -- --json > bench.json
|
||||
|
||||
- name: write commit
|
||||
run: |
|
||||
@@ -117,6 +126,8 @@ jobs:
|
||||
if: github.event_name != 'pull_request'
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
container:
|
||||
image: ghcr.io/lightpanda-io/perf-fmt:latest
|
||||
credentials:
|
||||
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -1,5 +1,11 @@
|
||||
zig-cache
|
||||
/.zig-cache/
|
||||
/.lp-cache/
|
||||
zig-out
|
||||
/vendor/netsurf/out
|
||||
/vendor/libiconv/
|
||||
lightpanda.id
|
||||
/v8/
|
||||
/build/
|
||||
/src/html5ever/target/
|
||||
src/snapshot.bin
|
||||
|
||||
43
.gitmodules
vendored
43
.gitmodules
vendored
@@ -1,34 +1,15 @@
|
||||
[submodule "vendor/zig-js-runtime"]
|
||||
path = vendor/zig-js-runtime
|
||||
url = git@github.com:lightpanda-io/zig-js-runtime.git
|
||||
[submodule "vendor/netsurf/libwapcaplet"]
|
||||
path = vendor/netsurf/libwapcaplet
|
||||
url = git@github.com:lightpanda-io/libwapcaplet.git
|
||||
[submodule "vendor/netsurf/libparserutils"]
|
||||
path = vendor/netsurf/libparserutils
|
||||
url = git@github.com:lightpanda-io/libparserutils.git
|
||||
[submodule "vendor/netsurf/libdom"]
|
||||
path = vendor/netsurf/libdom
|
||||
url = git@github.com:lightpanda-io/libdom.git
|
||||
[submodule "vendor/netsurf/share/netsurf-buildsystem"]
|
||||
path = vendor/netsurf/share/netsurf-buildsystem
|
||||
url = https://source.netsurf-browser.org/buildsystem.git
|
||||
[submodule "vendor/netsurf/libhubbub"]
|
||||
path = vendor/netsurf/libhubbub
|
||||
url = git@github.com:lightpanda-io/libhubbub.git
|
||||
[submodule "tests/wpt"]
|
||||
path = tests/wpt
|
||||
url = https://github.com/lightpanda-io/wpt
|
||||
[submodule "vendor/mimalloc"]
|
||||
path = vendor/mimalloc
|
||||
url = git@github.com:microsoft/mimalloc.git
|
||||
[submodule "vendor/tls.zig"]
|
||||
path = vendor/tls.zig
|
||||
url = git@github.com:ianic/tls.zig.git
|
||||
[submodule "vendor/zig-async-io"]
|
||||
path = vendor/zig-async-io
|
||||
url = git@github.com:lightpanda-io/zig-async-io.git
|
||||
[submodule "vendor/websocket.zig"]
|
||||
path = vendor/websocket.zig
|
||||
url = git@github.com:lightpanda-io/websocket.zig.git
|
||||
branch = lightpanda
|
||||
[submodule "vendor/nghttp2"]
|
||||
path = vendor/nghttp2
|
||||
url = https://github.com/nghttp2/nghttp2.git
|
||||
[submodule "vendor/zlib"]
|
||||
path = vendor/zlib
|
||||
url = https://github.com/madler/zlib.git
|
||||
[submodule "vendor/curl"]
|
||||
path = vendor/curl
|
||||
url = https://github.com/curl/curl.git
|
||||
[submodule "vendor/brotli"]
|
||||
path = vendor/brotli
|
||||
url = https://github.com/google/brotli
|
||||
|
||||
10
CONTRIBUTING.md
Normal file
10
CONTRIBUTING.md
Normal file
@@ -0,0 +1,10 @@
|
||||
# Contributing
|
||||
|
||||
Lightpanda accepts pull requests through GitHub.
|
||||
|
||||
You have to sign our [CLA](CLA.md) during your first pull request process
|
||||
otherwise we're not able to accept your contributions.
|
||||
|
||||
The process signature uses the [CLA assistant
|
||||
lite](https://github.com/marketplace/actions/cla-assistant-lite). You can see
|
||||
an example of the process in [#303](https://github.com/lightpanda-io/browser/pull/303).
|
||||
110
Dockerfile
110
Dockerfile
@@ -1,77 +1,81 @@
|
||||
FROM ubuntu:22.04
|
||||
FROM debian:stable-slim
|
||||
|
||||
ARG ZIG=0.13.0
|
||||
ARG MINISIG=0.12
|
||||
ARG ZIG_MINISIG=RWSGOq2NVecA2UPNdBUZykf1CCb147pkmdtYxgb3Ti+JO/wCYvhbAb/U
|
||||
ARG OS=linux
|
||||
ARG ARCH=x86_64
|
||||
ARG V8=11.1.134
|
||||
ARG ZIG_V8=v0.1.9
|
||||
ARG V8=14.0.365.4
|
||||
ARG ZIG_V8=v0.2.2
|
||||
ARG TARGETPLATFORM
|
||||
|
||||
RUN apt-get update -yq && \
|
||||
apt-get install -yq xz-utils \
|
||||
python3 ca-certificates git \
|
||||
pkg-config libglib2.0-dev \
|
||||
gperf libexpat1-dev \
|
||||
cmake clang \
|
||||
curl git
|
||||
apt-get install -yq xz-utils ca-certificates \
|
||||
clang make curl git
|
||||
|
||||
# Get Rust
|
||||
RUN curl https://sh.rustup.rs -sSf | sh -s -- --profile minimal -y
|
||||
ENV PATH="/root/.cargo/bin:${PATH}"
|
||||
|
||||
# install minisig
|
||||
RUN curl -L -O https://github.com/jedisct1/minisign/releases/download/0.11/minisign-0.11-linux.tar.gz && \
|
||||
tar xvzf minisign-0.11-linux.tar.gz
|
||||
|
||||
# install zig
|
||||
RUN curl -O https://ziglang.org/download/${ZIG}/zig-linux-x86_64-${ZIG}.tar.xz && \
|
||||
curl -O https://ziglang.org/download/${ZIG}/zig-linux-x86_64-${ZIG}.tar.xz.minisig
|
||||
|
||||
RUN minisign-linux/x86_64/minisign -Vm zig-linux-x86_64-${ZIG}.tar.xz -P ${ZIG_MINISIG}
|
||||
|
||||
# clean minisg
|
||||
RUN rm -fr minisign-0.11-linux.tar.gz minisign-linux
|
||||
|
||||
# install zig
|
||||
RUN tar xvf zig-linux-x86_64-${ZIG}.tar.xz && \
|
||||
mv zig-linux-x86_64-${ZIG} /usr/local/lib && \
|
||||
ln -s /usr/local/lib/zig-linux-x86_64-${ZIG}/zig /usr/local/bin/zig
|
||||
|
||||
# clean up zig install
|
||||
RUN rm -fr zig-linux-x86_64-${ZIG}.tar.xz zig-linux-x86_64-${ZIG}.tar.xz.minisig
|
||||
|
||||
# force use of http instead of ssh with github
|
||||
RUN cat <<EOF > /root/.gitconfig
|
||||
[url "https://github.com/"]
|
||||
insteadOf="git@github.com:"
|
||||
EOF
|
||||
RUN curl --fail -L -O https://github.com/jedisct1/minisign/releases/download/${MINISIG}/minisign-${MINISIG}-linux.tar.gz && \
|
||||
tar xvzf minisign-${MINISIG}-linux.tar.gz -C /
|
||||
|
||||
# clone lightpanda
|
||||
RUN git clone git@github.com:lightpanda-io/browser.git
|
||||
|
||||
RUN git clone https://github.com/lightpanda-io/browser.git
|
||||
WORKDIR /browser
|
||||
|
||||
# install zig
|
||||
RUN ZIG=$(grep '\.minimum_zig_version = "' "build.zig.zon" | cut -d'"' -f2) && \
|
||||
case $TARGETPLATFORM in \
|
||||
"linux/arm64") ARCH="aarch64" ;; \
|
||||
*) ARCH="x86_64" ;; \
|
||||
esac && \
|
||||
curl --fail -L -O https://ziglang.org/download/${ZIG}/zig-${ARCH}-linux-${ZIG}.tar.xz && \
|
||||
curl --fail -L -O https://ziglang.org/download/${ZIG}/zig-${ARCH}-linux-${ZIG}.tar.xz.minisig && \
|
||||
/minisign-linux/${ARCH}/minisign -Vm zig-${ARCH}-linux-${ZIG}.tar.xz -P ${ZIG_MINISIG} && \
|
||||
tar xvf zig-${ARCH}-linux-${ZIG}.tar.xz && \
|
||||
mv zig-${ARCH}-linux-${ZIG} /usr/local/lib && \
|
||||
ln -s /usr/local/lib/zig-${ARCH}-linux-${ZIG}/zig /usr/local/bin/zig
|
||||
|
||||
# install deps
|
||||
RUN git submodule init && \
|
||||
git submodule update --recursive
|
||||
|
||||
RUN cd vendor/zig-js-runtime && \
|
||||
git submodule init && \
|
||||
git submodule update --recursive
|
||||
|
||||
RUN make install-libiconv && \
|
||||
make install-netsurf && \
|
||||
make install-mimalloc
|
||||
|
||||
# download and install v8
|
||||
RUN curl -L -o libc_v8.a https://github.com/lightpanda-io/zig-v8-fork/releases/download/${ZIG_V8}/libc_v8_${V8}_${OS}_${ARCH}.a && \
|
||||
mkdir -p vendor/zig-js-runtime/vendor/v8/${ARCH}-${OS}/release && \
|
||||
mv libc_v8.a vendor/zig-js-runtime/vendor/v8/${ARCH}-${OS}/release/libc_v8.a
|
||||
RUN case $TARGETPLATFORM in \
|
||||
"linux/arm64") ARCH="aarch64" ;; \
|
||||
*) ARCH="x86_64" ;; \
|
||||
esac && \
|
||||
curl --fail -L -o libc_v8.a https://github.com/lightpanda-io/zig-v8-fork/releases/download/${ZIG_V8}/libc_v8_${V8}_linux_${ARCH}.a && \
|
||||
mkdir -p v8/ && \
|
||||
mv libc_v8.a v8/libc_v8.a
|
||||
|
||||
# build v8 snapshot
|
||||
RUN zig build -Doptimize=ReleaseFast \
|
||||
-Dprebuilt_v8_path=v8/libc_v8.a \
|
||||
snapshot_creator -- src/snapshot.bin
|
||||
|
||||
# build release
|
||||
RUN make build
|
||||
RUN zig build -Doptimize=ReleaseFast \
|
||||
-Dsnapshot_path=../../snapshot.bin \
|
||||
-Dprebuilt_v8_path=v8/libc_v8.a \
|
||||
-Dgit_commit=$(git rev-parse --short HEAD)
|
||||
|
||||
FROM ubuntu:22.04
|
||||
FROM debian:stable-slim
|
||||
|
||||
RUN apt-get update -yq && \
|
||||
apt-get install -yq tini
|
||||
|
||||
FROM debian:stable-slim
|
||||
|
||||
# copy ca certificates
|
||||
COPY --from=0 /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
|
||||
COPY --from=0 /browser/zig-out/bin/lightpanda /bin/lightpanda
|
||||
COPY --from=1 /usr/bin/tini /usr/bin/tini
|
||||
|
||||
CMD ["/bin/lightpanda", "--host", "0.0.0.0", "--port", "3245"]
|
||||
EXPOSE 9222/tcp
|
||||
|
||||
# Lightpanda install only some signal handlers, and PID 1 doesn't have a default SIGTERM signal handler.
|
||||
# Using "tini" as PID1 ensures that signals work as expected, so e.g. "docker stop" will not hang.
|
||||
# (See https://github.com/krallin/tini#why-tini).
|
||||
ENTRYPOINT ["/usr/bin/tini", "--"]
|
||||
CMD ["/bin/lightpanda", "serve", "--host", "0.0.0.0", "--port", "9222", "--log_level", "info"]
|
||||
|
||||
@@ -5,15 +5,6 @@ List](https://spdx.org/licenses/).
|
||||
|
||||
The default license for this project is [AGPL-3.0-only](LICENSE).
|
||||
|
||||
## MIT
|
||||
|
||||
The following files are licensed under MIT:
|
||||
|
||||
```
|
||||
src/http/Client.zig
|
||||
src/polyfill/fetch.js
|
||||
```
|
||||
|
||||
The following directories and their subdirectories are licensed under their
|
||||
original upstream licenses:
|
||||
|
||||
|
||||
205
Makefile
205
Makefile
@@ -3,12 +3,17 @@
|
||||
|
||||
ZIG := zig
|
||||
BC := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
|
||||
# option test filter make test F="server"
|
||||
F=
|
||||
|
||||
# OS and ARCH
|
||||
kernel = $(shell uname -ms)
|
||||
ifeq ($(kernel), Darwin arm64)
|
||||
OS := macos
|
||||
ARCH := aarch64
|
||||
else ifeq ($(kernel), Darwin x86_64)
|
||||
OS := macos
|
||||
ARCH := x86_64
|
||||
else ifeq ($(kernel), Linux aarch64)
|
||||
OS := linux
|
||||
ARCH := aarch64
|
||||
@@ -29,7 +34,7 @@ endif
|
||||
|
||||
## Display this help screen
|
||||
help:
|
||||
@printf "\e[36m%-35s %s\e[0m\n" "Command" "Usage"
|
||||
@printf "\033[36m%-35s %s\033[0m\n" "Command" "Usage"
|
||||
@sed -n -e '/^## /{'\
|
||||
-e 's/## //g;'\
|
||||
-e 'h;'\
|
||||
@@ -42,181 +47,75 @@ help:
|
||||
|
||||
# $(ZIG) commands
|
||||
# ------------
|
||||
.PHONY: build build-dev run run-release shell test bench download-zig wpt
|
||||
.PHONY: build build-v8-snapshot build-dev run run-release shell test bench wpt data end2end
|
||||
|
||||
zig_version = $(shell grep 'recommended_zig_version = "' "vendor/zig-js-runtime/build.zig" | cut -d'"' -f2)
|
||||
## Build v8 snapshot
|
||||
build-v8-snapshot:
|
||||
@printf "\033[36mBuilding v8 snapshot (release safe)...\033[0m\n"
|
||||
@$(ZIG) build -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
@printf "\033[33mBuild OK\033[0m\n"
|
||||
|
||||
## Download the zig recommended version
|
||||
download-zig:
|
||||
$(eval url = "https://ziglang.org/download/$(zig_version)/zig-$(OS)-$(ARCH)-$(zig_version).tar.xz")
|
||||
$(eval dest = "/tmp/zig-$(OS)-$(ARCH)-$(zig_version).tar.xz")
|
||||
@printf "\e[36mDownload zig version $(zig_version)...\e[0m\n"
|
||||
@curl -o "$(dest)" -L "$(url)" || (printf "\e[33mBuild ERROR\e[0m\n"; exit 1;)
|
||||
@printf "\e[33mDownloaded $(dest)\e[0m\n"
|
||||
|
||||
## Build in release-safe mode
|
||||
build:
|
||||
@printf "\e[36mBuilding (release safe)...\e[0m\n"
|
||||
@$(ZIG) build -Doptimize=ReleaseSafe -Dengine=v8 || (printf "\e[33mBuild ERROR\e[0m\n"; exit 1;)
|
||||
@printf "\e[33mBuild OK\e[0m\n"
|
||||
## Build in release-fast mode
|
||||
build: build-v8-snapshot
|
||||
@printf "\033[36mBuilding (release safe)...\033[0m\n"
|
||||
@$(ZIG) build -Doptimize=ReleaseFast -Dsnapshot_path=../../snapshot.bin -Dgit_commit=$$(git rev-parse --short HEAD) || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
@printf "\033[33mBuild OK\033[0m\n"
|
||||
|
||||
## Build in debug mode
|
||||
build-dev:
|
||||
@printf "\e[36mBuilding (debug)...\e[0m\n"
|
||||
@$(ZIG) build -Dengine=v8 || (printf "\e[33mBuild ERROR\e[0m\n"; exit 1;)
|
||||
@printf "\e[33mBuild OK\e[0m\n"
|
||||
@printf "\033[36mBuilding (debug)...\033[0m\n"
|
||||
@$(ZIG) build -Dgit_commit=$$(git rev-parse --short HEAD) || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
@printf "\033[33mBuild OK\033[0m\n"
|
||||
|
||||
## Run the server in release mode
|
||||
run: build
|
||||
@printf "\033[36mRunning...\033[0m\n"
|
||||
@./zig-out/bin/lightpanda || (printf "\033[33mRun ERROR\033[0m\n"; exit 1;)
|
||||
|
||||
## Run the server in debug mode
|
||||
run: build
|
||||
@printf "\e[36mRunning...\e[0m\n"
|
||||
@./zig-out/bin/lightpanda || (printf "\e[33mRun ERROR\e[0m\n"; exit 1;)
|
||||
run-debug: build-dev
|
||||
@printf "\033[36mRunning...\033[0m\n"
|
||||
@./zig-out/bin/lightpanda || (printf "\033[33mRun ERROR\033[0m\n"; exit 1;)
|
||||
|
||||
## Run a JS shell in debug mode
|
||||
shell:
|
||||
@printf "\e[36mBuilding shell...\e[0m\n"
|
||||
@$(ZIG) build shell -Dengine=v8 || (printf "\e[33mBuild ERROR\e[0m\n"; exit 1;)
|
||||
@printf "\033[36mBuilding shell...\033[0m\n"
|
||||
@$(ZIG) build shell || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
|
||||
## Run WPT tests
|
||||
wpt:
|
||||
@printf "\e[36mBuilding wpt...\e[0m\n"
|
||||
@$(ZIG) build wpt -Dengine=v8 -- --safe $(filter-out $@,$(MAKECMDGOALS)) || (printf "\e[33mBuild ERROR\e[0m\n"; exit 1;)
|
||||
@printf "\033[36mBuilding wpt...\033[0m\n"
|
||||
@$(ZIG) build wpt -- $(filter-out $@,$(MAKECMDGOALS)) || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
|
||||
wpt-summary:
|
||||
@printf "\e[36mBuilding wpt...\e[0m\n"
|
||||
@$(ZIG) build wpt -Dengine=v8 -- --safe --summary $(filter-out $@,$(MAKECMDGOALS)) || (printf "\e[33mBuild ERROR\e[0m\n"; exit 1;)
|
||||
@printf "\033[36mBuilding wpt...\033[0m\n"
|
||||
@$(ZIG) build wpt -- --summary $(filter-out $@,$(MAKECMDGOALS)) || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
|
||||
## Test
|
||||
## Test - `grep` is used to filter out the huge compile command on build
|
||||
ifeq ($(OS), macos)
|
||||
test:
|
||||
@printf "\e[36mTesting...\e[0m\n"
|
||||
@$(ZIG) build test -Dengine=v8 || (printf "\e[33mTest ERROR\e[0m\n"; exit 1;)
|
||||
@printf "\e[33mTest OK\e[0m\n"
|
||||
@script -q /dev/null sh -c 'TEST_FILTER="${F}" $(ZIG) build test -freference-trace' 2>&1 \
|
||||
| grep --line-buffered -v "^/.*zig test -freference-trace"
|
||||
else
|
||||
test:
|
||||
@script -qec 'TEST_FILTER="${F}" $(ZIG) build test -freference-trace' /dev/null 2>&1 \
|
||||
| grep --line-buffered -v "^/.*zig test -freference-trace"
|
||||
endif
|
||||
|
||||
## Run demo/runner end to end tests
|
||||
end2end:
|
||||
@test -d ../demo
|
||||
cd ../demo && go run runner/main.go
|
||||
|
||||
# Install and build required dependencies commands
|
||||
# ------------
|
||||
.PHONY: install-submodule
|
||||
.PHONY: install-zig-js-runtime install-zig-js-runtime-dev install-libiconv
|
||||
.PHONY: _install-netsurf install-netsurf clean-netsurf test-netsurf install-netsurf-dev
|
||||
.PHONY: install-mimalloc install-mimalloc-dev clean-mimalloc
|
||||
.PHONY: install-dev install
|
||||
.PHONY: install
|
||||
|
||||
## Install and build dependencies for release
|
||||
install: install-submodule install-zig-js-runtime install-libiconv install-netsurf install-mimalloc
|
||||
install: install-submodule
|
||||
|
||||
## Install and build dependencies for dev
|
||||
install-dev: install-submodule install-zig-js-runtime-dev install-libiconv install-netsurf-dev install-mimalloc-dev
|
||||
|
||||
install-netsurf-dev: _install-netsurf
|
||||
install-netsurf-dev: OPTCFLAGS := -O0 -g -DNDEBUG
|
||||
|
||||
install-netsurf: _install-netsurf
|
||||
install-netsurf: OPTCFLAGS := -DNDEBUG
|
||||
|
||||
BC_NS := $(BC)vendor/netsurf/out/$(OS)-$(ARCH)
|
||||
ICONV := $(BC)vendor/libiconv/out/$(OS)-$(ARCH)
|
||||
# TODO: add Linux iconv path (I guess it depends on the distro)
|
||||
# TODO: this way of linking libiconv is not ideal. We should have a more generic way
|
||||
# and stick to a specif version. Maybe build from source. Anyway not now.
|
||||
_install-netsurf: clean-netsurf
|
||||
@printf "\e[36mInstalling NetSurf...\e[0m\n" && \
|
||||
ls $(ICONV)/lib/libiconv.a 1> /dev/null || (printf "\e[33mERROR: you need to execute 'make install-libiconv'\e[0m\n"; exit 1;) && \
|
||||
mkdir -p $(BC_NS) && \
|
||||
cp -R vendor/netsurf/share $(BC_NS) && \
|
||||
export PREFIX=$(BC_NS) && \
|
||||
export OPTLDFLAGS="-L$(ICONV)/lib" && \
|
||||
export OPTCFLAGS="$(OPTCFLAGS) -I$(ICONV)/include" && \
|
||||
printf "\e[33mInstalling libwapcaplet...\e[0m\n" && \
|
||||
cd vendor/netsurf/libwapcaplet && \
|
||||
BUILDDIR=$(BC_NS)/build/libwapcaplet make install && \
|
||||
cd ../libparserutils && \
|
||||
printf "\e[33mInstalling libparserutils...\e[0m\n" && \
|
||||
BUILDDIR=$(BC_NS)/build/libparserutils make install && \
|
||||
cd ../libhubbub && \
|
||||
printf "\e[33mInstalling libhubbub...\e[0m\n" && \
|
||||
BUILDDIR=$(BC_NS)/build/libhubbub make install && \
|
||||
rm src/treebuilder/autogenerated-element-type.c && \
|
||||
cd ../libdom && \
|
||||
printf "\e[33mInstalling libdom...\e[0m\n" && \
|
||||
BUILDDIR=$(BC_NS)/build/libdom make install && \
|
||||
printf "\e[33mRunning libdom example...\e[0m\n" && \
|
||||
cd examples && \
|
||||
zig cc \
|
||||
-I$(ICONV)/include \
|
||||
-I$(BC_NS)/include \
|
||||
-L$(ICONV)/lib \
|
||||
-L$(BC_NS)/lib \
|
||||
-liconv \
|
||||
-ldom \
|
||||
-lhubbub \
|
||||
-lparserutils \
|
||||
-lwapcaplet \
|
||||
-o a.out \
|
||||
dom-structure-dump.c \
|
||||
$(ICONV)/lib/libiconv.a && \
|
||||
./a.out > /dev/null && \
|
||||
rm a.out && \
|
||||
printf "\e[36mDone NetSurf $(OS)\e[0m\n"
|
||||
|
||||
clean-netsurf:
|
||||
@printf "\e[36mCleaning NetSurf build...\e[0m\n" && \
|
||||
rm -Rf $(BC_NS)
|
||||
|
||||
test-netsurf:
|
||||
@printf "\e[36mTesting NetSurf...\e[0m\n" && \
|
||||
export PREFIX=$(BC_NS) && \
|
||||
export LDFLAGS="-L$(ICONV)/lib -L$(BC_NS)/lib" && \
|
||||
export CFLAGS="-I$(ICONV)/include -I$(BC_NS)/include" && \
|
||||
cd vendor/netsurf/libdom && \
|
||||
BUILDDIR=$(BC_NS)/build/libdom make test
|
||||
|
||||
download-libiconv:
|
||||
ifeq ("$(wildcard vendor/libiconv/libiconv-1.17)","")
|
||||
@mkdir -p vendor/libiconv
|
||||
@cd vendor/libiconv && \
|
||||
curl https://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.17.tar.gz | tar -xvzf -
|
||||
endif
|
||||
|
||||
install-libiconv: download-libiconv clean-libiconv
|
||||
@cd vendor/libiconv/libiconv-1.17 && \
|
||||
./configure --prefix=$(ICONV) --enable-static && \
|
||||
make && make install
|
||||
|
||||
clean-libiconv:
|
||||
ifneq ("$(wildcard vendor/libiconv/libiconv-1.17/Makefile)","")
|
||||
@cd vendor/libiconv/libiconv-1.17 && \
|
||||
make clean
|
||||
endif
|
||||
|
||||
install-zig-js-runtime-dev:
|
||||
@cd vendor/zig-js-runtime && \
|
||||
make install-dev
|
||||
|
||||
install-zig-js-runtime:
|
||||
@cd vendor/zig-js-runtime && \
|
||||
make install
|
||||
|
||||
.PHONY: _build_mimalloc
|
||||
|
||||
MIMALLOC := $(BC)vendor/mimalloc/out/$(OS)-$(ARCH)
|
||||
_build_mimalloc: clean-mimalloc
|
||||
@mkdir -p $(MIMALLOC)/build && \
|
||||
cd $(MIMALLOC)/build && \
|
||||
cmake -DMI_BUILD_SHARED=OFF -DMI_BUILD_OBJECT=OFF -DMI_BUILD_TESTS=OFF -DMI_OVERRIDE=OFF $(OPTS) ../../.. && \
|
||||
make && \
|
||||
mkdir -p $(MIMALLOC)/lib
|
||||
|
||||
install-mimalloc-dev: _build_mimalloc
|
||||
install-mimalloc-dev: OPTS=-DCMAKE_BUILD_TYPE=Debug
|
||||
install-mimalloc-dev:
|
||||
@cd $(MIMALLOC) && \
|
||||
mv build/libmimalloc-debug.a lib/libmimalloc.a
|
||||
|
||||
install-mimalloc: _build_mimalloc
|
||||
install-mimalloc:
|
||||
@cd $(MIMALLOC) && \
|
||||
mv build/libmimalloc.a lib/libmimalloc.a
|
||||
|
||||
clean-mimalloc:
|
||||
@rm -Rf $(MIMALLOC)/build
|
||||
data:
|
||||
cd src/data && go run public_suffix_list_gen.go > public_suffix_list.zig
|
||||
|
||||
## Init and update git submodule
|
||||
install-submodule:
|
||||
|
||||
269
README.md
269
README.md
@@ -7,112 +7,192 @@
|
||||
<p align="center"><a href="https://lightpanda.io/">lightpanda.io</a></p>
|
||||
|
||||
<div align="center">
|
||||
<br />
|
||||
|
||||
[](https://github.com/lightpanda-io/browser/blob/main/LICENSE)
|
||||
[](https://twitter.com/lightpanda_io)
|
||||
[](https://github.com/lightpanda-io/browser)
|
||||
|
||||
</div>
|
||||
|
||||
Lightpanda is the open-source browser made for headless usage:
|
||||
|
||||
- Javascript execution
|
||||
- Support of the Web APIs (partial, WIP)
|
||||
- Compatible with Playwright, Puppeteer through CDP (WIP)
|
||||
- Support of Web APIs (partial, WIP)
|
||||
- Compatible with Playwright[^1], Puppeteer, chromedp through [CDP](https://chromedevtools.github.io/devtools-protocol/)
|
||||
|
||||
Fast scraping and web automation with minimal memory footprint:
|
||||
Fast web automation for AI agents, LLM training, scraping and testing:
|
||||
|
||||
- Ultra-low memory footprint (9x less than Chrome)
|
||||
- Blazingly fast execution (11x faster than Chrome) & instant startup
|
||||
- Exceptionally fast execution (11x faster than Chrome)
|
||||
- Instant startup
|
||||
|
||||
<img width=500px src="https://cdn.lightpanda.io/assets/images/benchmark_2024-12-04.png">
|
||||
[<img width="350px" src="https://cdn.lightpanda.io/assets/images/github/execution-time.svg">
|
||||
](https://github.com/lightpanda-io/demo)
|
||||
 
|
||||
[<img width="350px" src="https://cdn.lightpanda.io/assets/images/github/memory-frame.svg">
|
||||
](https://github.com/lightpanda-io/demo)
|
||||
</div>
|
||||
|
||||
See [benchmark details](https://github.com/lightpanda-io/demo).
|
||||
_Puppeteer requesting 100 pages from a local website on a AWS EC2 m5.large instance.
|
||||
See [benchmark details](https://github.com/lightpanda-io/demo)._
|
||||
|
||||
## Why?
|
||||
[^1]: **Playwright support disclaimer:**
|
||||
Due to the nature of Playwright, a script that works with the current version of the browser may not function correctly with a future version. Playwright uses an intermediate JavaScript layer that selects an execution strategy based on the browser's available features. If Lightpanda adds a new [Web API](https://developer.mozilla.org/en-US/docs/Web/API), Playwright may choose to execute different code for the same script. This new code path could attempt to use features that are not yet implemented. Lightpanda makes an effort to add compatibility tests, but we can't cover all scenarios. If you encounter an issue, please create a [GitHub issue](https://github.com/lightpanda-io/browser/issues) and include the last known working version of the script.
|
||||
|
||||
### Javascript execution is mandatory for the modern web
|
||||
## Quick start
|
||||
|
||||
Back in the good old times, grabbing a webpage was as easy as making an HTTP request, cURL-like. It’s not possible anymore, because Javascript is everywhere, like it or not:
|
||||
### Install
|
||||
**Install from the nightly builds**
|
||||
|
||||
- Ajax, Single Page App, Infinite loading, “click to display”, instant search, etc.
|
||||
- JS web frameworks: React, Vue, Angular & others
|
||||
You can download the last binary from the [nightly
|
||||
builds](https://github.com/lightpanda-io/browser/releases/tag/nightly) for
|
||||
Linux x86_64 and MacOS aarch64.
|
||||
|
||||
### Chrome is not the right tool
|
||||
*For Linux*
|
||||
```console
|
||||
curl -L -o lightpanda https://github.com/lightpanda-io/browser/releases/download/nightly/lightpanda-x86_64-linux && \
|
||||
chmod a+x ./lightpanda
|
||||
```
|
||||
|
||||
So if we need Javascript, why not use a real web browser. Let’s take a huge desktop application, hack it, and run it on the server, right? Hundreds or thousands of instances of Chrome if you use it at scale. Are you sure it’s such a good idea?
|
||||
*For MacOS*
|
||||
```console
|
||||
curl -L -o lightpanda https://github.com/lightpanda-io/browser/releases/download/nightly/lightpanda-aarch64-macos && \
|
||||
chmod a+x ./lightpanda
|
||||
```
|
||||
|
||||
- Heavy on RAM and CPU, expensive to run
|
||||
- Hard to package, deploy and maintain at scale
|
||||
- Bloated, lots of features are not useful in headless usage
|
||||
*For Windows + WSL2*
|
||||
|
||||
### Lightpanda is built for performance
|
||||
The Lightpanda browser is compatible to run on windows inside WSL. Follow the Linux instruction for installation from a WSL terminal.
|
||||
It is recommended to install clients like Puppeteer on the Windows host.
|
||||
|
||||
If we want both Javascript and performance, for a real headless browser, we need to start from scratch. Not yet another iteration of Chromium, really from a blank page. Crazy right? But that’s we did:
|
||||
**Install from Docker**
|
||||
|
||||
- Not based on Chromium, Blink or WebKit
|
||||
- Low-level system programming language (Zig) with optimisations in mind
|
||||
- Opinionated, without graphical rendering
|
||||
Lightpanda provides [official Docker
|
||||
images](https://hub.docker.com/r/lightpanda/browser) for both Linux amd64 and
|
||||
arm64 architectures.
|
||||
The following command fetches the Docker image and starts a new container exposing Lightpanda's CDP server on port `9222`.
|
||||
```console
|
||||
docker run -d --name lightpanda -p 9222:9222 lightpanda/browser:nightly
|
||||
```
|
||||
|
||||
### Dump a URL
|
||||
|
||||
```console
|
||||
./lightpanda fetch --dump https://lightpanda.io
|
||||
```
|
||||
```console
|
||||
info(browser): GET https://lightpanda.io/ http.Status.ok
|
||||
info(browser): fetch script https://api.website.lightpanda.io/js/script.js: http.Status.ok
|
||||
info(browser): eval remote https://api.website.lightpanda.io/js/script.js: TypeError: Cannot read properties of undefined (reading 'pushState')
|
||||
<!DOCTYPE html>
|
||||
```
|
||||
|
||||
### Start a CDP server
|
||||
|
||||
```console
|
||||
./lightpanda serve --host 127.0.0.1 --port 9222
|
||||
```
|
||||
```console
|
||||
info(websocket): starting blocking worker to listen on 127.0.0.1:9222
|
||||
info(server): accepting new conn...
|
||||
```
|
||||
|
||||
Once the CDP server started, you can run a Puppeteer script by configuring the
|
||||
`browserWSEndpoint`.
|
||||
|
||||
```js
|
||||
'use strict'
|
||||
|
||||
import puppeteer from 'puppeteer-core';
|
||||
|
||||
// use browserWSEndpoint to pass the Lightpanda's CDP server address.
|
||||
const browser = await puppeteer.connect({
|
||||
browserWSEndpoint: "ws://127.0.0.1:9222",
|
||||
});
|
||||
|
||||
// The rest of your script remains the same.
|
||||
const context = await browser.createBrowserContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
// Dump all the links from the page.
|
||||
await page.goto('https://wikipedia.com/');
|
||||
|
||||
const links = await page.evaluate(() => {
|
||||
return Array.from(document.querySelectorAll('a')).map(row => {
|
||||
return row.getAttribute('href');
|
||||
});
|
||||
});
|
||||
|
||||
console.log(links);
|
||||
|
||||
await page.close();
|
||||
await context.close();
|
||||
await browser.disconnect();
|
||||
```
|
||||
|
||||
### Telemetry
|
||||
By default, Lightpanda collects and sends usage telemetry. This can be disabled by setting an environment variable `LIGHTPANDA_DISABLE_TELEMETRY=true`. You can read Lightpanda's privacy policy at: [https://lightpanda.io/privacy-policy](https://lightpanda.io/privacy-policy).
|
||||
|
||||
## Status
|
||||
|
||||
Lightpanda is still a work in progress and is currently at a Beta stage.
|
||||
Lightpanda is in Beta and currently a work in progress. Stability and coverage are improving and many websites now work.
|
||||
You may still encounter errors or crashes. Please open an issue with specifics if so.
|
||||
|
||||
Here are the key features we have implemented:
|
||||
|
||||
- [x] HTTP loader
|
||||
- [x] HTML parser and DOM tree
|
||||
- [x] Javascript support (v8)
|
||||
- [x] Basic DOM APIs
|
||||
- [x] HTTP loader ([Libcurl](https://curl.se/libcurl/))
|
||||
- [x] HTML parser ([html5ever](https://github.com/servo/html5ever))
|
||||
- [x] DOM tree
|
||||
- [x] Javascript support ([v8](https://v8.dev/))
|
||||
- [x] DOM APIs
|
||||
- [x] Ajax
|
||||
- [x] XHR API
|
||||
- [x] Fetch API
|
||||
- [x] DOM dump
|
||||
- [x] Basic CDP/websockets server
|
||||
- [x] CDP/websockets server
|
||||
- [x] Click
|
||||
- [x] Input form
|
||||
- [x] Cookies
|
||||
- [x] Custom HTTP headers
|
||||
- [x] Proxy support
|
||||
- [x] Network interception
|
||||
|
||||
NOTE: There are hundreds of Web APIs. Developing a browser, even just for headless mode, is a huge task. It's more about coverage than a _working/not working_ binary situation.
|
||||
NOTE: There are hundreds of Web APIs. Developing a browser (even just for headless mode) is a huge task. Coverage will increase over time.
|
||||
|
||||
You can also follow the progress of our Javascript support in our dedicated [zig-js-runtime](https://github.com/lightpanda-io/zig-js-runtime#development) project.
|
||||
|
||||
## Install
|
||||
|
||||
We do provide [nighly builds](https://github.com/lightpanda-io/browser/releases/tag/nightly) for Linux x86_64 and MacOS aarch64.
|
||||
|
||||
## Build from sources
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Lightpanda is written with [Zig](https://ziglang.org/) `0.13.0`. You have to
|
||||
Lightpanda is written with [Zig](https://ziglang.org/) `0.15.2`. You have to
|
||||
install it with the right version in order to build the project.
|
||||
|
||||
Lightpanda also depends on
|
||||
[zig-js-runtime](https://github.com/lightpanda-io/zig-js-runtime/) (with v8),
|
||||
[Netsurf libs](https://www.netsurf-browser.org/) and
|
||||
[Mimalloc](https://microsoft.github.io/mimalloc).
|
||||
[Libcurl](https://curl.se/libcurl/) and [html5ever](https://github.com/servo/html5ever).
|
||||
|
||||
To be able to build the v8 engine for zig-js-runtime, you have to install some libs:
|
||||
|
||||
For Debian/Ubuntu based Linux:
|
||||
For **Debian/Ubuntu based Linux**:
|
||||
|
||||
```
|
||||
sudo apt install xz-utils \
|
||||
python3 ca-certificates git \
|
||||
pkg-config libglib2.0-dev \
|
||||
gperf libexpat1-dev \
|
||||
cmake clang
|
||||
sudo apt install xz-utils ca-certificates \
|
||||
clang make curl git
|
||||
```
|
||||
You also need to [install Rust](https://rust-lang.org/tools/install/).
|
||||
|
||||
For systems with [**Nix**](https://nixos.org/download/), you can use the devShell:
|
||||
```
|
||||
nix develop
|
||||
```
|
||||
|
||||
For MacOS, you only need cmake:
|
||||
|
||||
For **MacOS**, you need cmake and [Rust](https://rust-lang.org/tools/install/).
|
||||
```
|
||||
brew install cmake
|
||||
```
|
||||
|
||||
### Install and build dependencies
|
||||
|
||||
#### All in one build
|
||||
|
||||
You can run `make install` to install deps all in one (or `make install-dev` if you need the development versions).
|
||||
|
||||
Be aware that the build task is very long and cpu consuming, as you will build from sources all dependancies, including the v8 Javascript engine.
|
||||
|
||||
#### Step by step build dependancy
|
||||
### Install Git submodules
|
||||
|
||||
The project uses git submodules for dependencies.
|
||||
|
||||
@@ -122,41 +202,31 @@ To init or update the submodules in the `vendor/` directory:
|
||||
make install-submodule
|
||||
```
|
||||
|
||||
**Netsurf libs**
|
||||
This is an alias for `git submodule init && git submodule update`.
|
||||
|
||||
Netsurf libs are used for HTML parsing and DOM tree generation.
|
||||
### Build and run
|
||||
|
||||
You an build the entire browser with `make build` or `make build-dev` for debug
|
||||
env.
|
||||
|
||||
But you can directly use the zig command: `zig build run`.
|
||||
|
||||
#### Embed v8 snapshot
|
||||
|
||||
Lighpanda uses v8 snapshot. By default, it is created on startup but you can
|
||||
embed it by using the following commands:
|
||||
|
||||
Generate the snapshot.
|
||||
```
|
||||
make install-netsurf
|
||||
zig build snapshot_creator -- src/snapshot.bin
|
||||
```
|
||||
|
||||
For dev env, use `make install-netsurf-dev`.
|
||||
|
||||
**Mimalloc**
|
||||
|
||||
Mimalloc is used as a C memory allocator.
|
||||
|
||||
Build using the snapshot binary.
|
||||
```
|
||||
make install-mimalloc
|
||||
zig build -Dsnapshot_path=../../snapshot.bin
|
||||
```
|
||||
|
||||
For dev env, use `make install-mimalloc-dev`.
|
||||
|
||||
Note: when Mimalloc is built in dev mode, you can dump memory stats with the
|
||||
env var `MIMALLOC_SHOW_STATS=1`. See
|
||||
[https://microsoft.github.io/mimalloc/environment.html](https://microsoft.github.io/mimalloc/environment.html).
|
||||
|
||||
**zig-js-runtime**
|
||||
|
||||
Our own Zig/Javascript runtime, which includes the v8 Javascript engine.
|
||||
|
||||
This build task is very long and cpu consuming, as you will build v8 from sources.
|
||||
|
||||
```
|
||||
make install-zig-js-runtime
|
||||
```
|
||||
|
||||
For dev env, use `make iinstall-zig-js-runtime-dev`.
|
||||
See [#1279](https://github.com/lightpanda-io/browser/pull/1279) for more details.
|
||||
|
||||
## Test
|
||||
|
||||
@@ -164,6 +234,20 @@ For dev env, use `make iinstall-zig-js-runtime-dev`.
|
||||
|
||||
You can test Lightpanda by running `make test`.
|
||||
|
||||
### End to end tests
|
||||
|
||||
To run end to end tests, you need to clone the [demo
|
||||
repository](https://github.com/lightpanda-io/demo) into `../demo` dir.
|
||||
|
||||
You have to install the [demo's node
|
||||
requirements](https://github.com/lightpanda-io/demo?tab=readme-ov-file#dependencies-1)
|
||||
|
||||
You also need to install [Go](https://go.dev) > v1.24.
|
||||
|
||||
```
|
||||
make end2end
|
||||
```
|
||||
|
||||
### Web Platform Tests
|
||||
|
||||
Lightpanda is tested against the standardized [Web Platform
|
||||
@@ -205,3 +289,28 @@ Lightpanda accepts pull requests through GitHub.
|
||||
|
||||
You have to sign our [CLA](CLA.md) during the pull request process otherwise
|
||||
we're not able to accept your contributions.
|
||||
|
||||
## Why?
|
||||
|
||||
### Javascript execution is mandatory for the modern web
|
||||
|
||||
In the good old days, scraping a webpage was as easy as making an HTTP request, cURL-like. It’s not possible anymore, because Javascript is everywhere, like it or not:
|
||||
|
||||
- Ajax, Single Page App, infinite loading, “click to display”, instant search, etc.
|
||||
- JS web frameworks: React, Vue, Angular & others
|
||||
|
||||
### Chrome is not the right tool
|
||||
|
||||
If we need Javascript, why not use a real web browser? Take a huge desktop application, hack it, and run it on the server. Hundreds or thousands of instances of Chrome if you use it at scale. Are you sure it’s such a good idea?
|
||||
|
||||
- Heavy on RAM and CPU, expensive to run
|
||||
- Hard to package, deploy and maintain at scale
|
||||
- Bloated, lots of features are not useful in headless usage
|
||||
|
||||
### Lightpanda is built for performance
|
||||
|
||||
If we want both Javascript and performance in a true headless browser, we need to start from scratch. Not another iteration of Chromium, really from a blank page. Crazy right? But that’s what we did:
|
||||
|
||||
- Not based on Chromium, Blink or WebKit
|
||||
- Low-level system programming language (Zig) with optimisations in mind
|
||||
- Opinionated: without graphical rendering
|
||||
|
||||
852
build.zig
852
build.zig
@@ -18,234 +18,726 @@
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const jsruntime_path = "vendor/zig-js-runtime/";
|
||||
const jsruntime = @import("vendor/zig-js-runtime/build.zig");
|
||||
const jsruntime_pkgs = jsruntime.packages(jsruntime_path);
|
||||
|
||||
/// Do not rename this constant. It is scanned by some scripts to determine
|
||||
/// which zig version to install.
|
||||
const recommended_zig_version = jsruntime.recommended_zig_version;
|
||||
|
||||
pub fn build(b: *std.Build) !void {
|
||||
switch (comptime builtin.zig_version.order(std.SemanticVersion.parse(recommended_zig_version) catch unreachable)) {
|
||||
.eq => {},
|
||||
.lt => {
|
||||
@compileError("The minimum version of Zig required to compile is '" ++ recommended_zig_version ++ "', found '" ++ builtin.zig_version_string ++ "'.");
|
||||
},
|
||||
.gt => {
|
||||
std.debug.print(
|
||||
"WARNING: Recommended Zig version '{s}', but found '{s}', build may fail...\n\n",
|
||||
.{ recommended_zig_version, builtin.zig_version_string },
|
||||
);
|
||||
},
|
||||
}
|
||||
const Build = std.Build;
|
||||
|
||||
pub fn build(b: *Build) !void {
|
||||
const target = b.standardTargetOptions(.{});
|
||||
const mode = b.standardOptimizeOption(.{});
|
||||
const optimize = b.standardOptimizeOption(.{});
|
||||
|
||||
const options = jsruntime.buildOptions(b);
|
||||
const manifest = Manifest.init(b);
|
||||
|
||||
const git_commit = b.option([]const u8, "git_commit", "Current git commit");
|
||||
const prebuilt_v8_path = b.option([]const u8, "prebuilt_v8_path", "Path to prebuilt libc_v8.a");
|
||||
const snapshot_path = b.option([]const u8, "snapshot_path", "Path to v8 snapshot");
|
||||
|
||||
var opts = b.addOptions();
|
||||
opts.addOption([]const u8, "version", manifest.version);
|
||||
opts.addOption([]const u8, "git_commit", git_commit orelse "dev");
|
||||
opts.addOption(?[]const u8, "snapshot_path", snapshot_path);
|
||||
|
||||
const enable_tsan = b.option(bool, "tsan", "Enable Thread Sanitizer");
|
||||
const enable_csan = b.option(std.zig.SanitizeC, "csan", "Enable C Sanitizers");
|
||||
|
||||
const lightpanda_module = blk: {
|
||||
const mod = b.addModule("lightpanda", .{
|
||||
.root_source_file = b.path("src/lightpanda.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
.link_libc = true,
|
||||
.link_libcpp = true,
|
||||
.sanitize_c = enable_csan,
|
||||
.sanitize_thread = enable_tsan,
|
||||
});
|
||||
|
||||
try addDependencies(b, mod, opts, prebuilt_v8_path);
|
||||
|
||||
break :blk mod;
|
||||
};
|
||||
|
||||
{
|
||||
// browser
|
||||
// -------
|
||||
|
||||
// compile and install
|
||||
const exe = b.addExecutable(.{
|
||||
.name = "lightpanda",
|
||||
.use_llvm = true,
|
||||
.root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
.target = target,
|
||||
.optimize = mode,
|
||||
.optimize = optimize,
|
||||
.sanitize_c = enable_csan,
|
||||
.sanitize_thread = enable_tsan,
|
||||
.imports = &.{
|
||||
.{ .name = "lightpanda", .module = lightpanda_module },
|
||||
},
|
||||
}),
|
||||
});
|
||||
try common(b, exe, options);
|
||||
b.installArtifact(exe);
|
||||
|
||||
// run
|
||||
const run_cmd = b.addRunArtifact(exe);
|
||||
if (b.args) |args| {
|
||||
run_cmd.addArgs(args);
|
||||
}
|
||||
|
||||
// step
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
|
||||
// shell
|
||||
// -----
|
||||
|
||||
// compile and install
|
||||
const shell = b.addExecutable(.{
|
||||
.name = "lightpanda-shell",
|
||||
.root_source_file = b.path("src/main_shell.zig"),
|
||||
.target = target,
|
||||
.optimize = mode,
|
||||
});
|
||||
try common(b, shell, options);
|
||||
try jsruntime_pkgs.add_shell(shell);
|
||||
|
||||
// run
|
||||
const shell_cmd = b.addRunArtifact(shell);
|
||||
if (b.args) |args| {
|
||||
shell_cmd.addArgs(args);
|
||||
}
|
||||
|
||||
// step
|
||||
const shell_step = b.step("shell", "Run JS shell");
|
||||
shell_step.dependOn(&shell_cmd.step);
|
||||
{
|
||||
// snapshot creator
|
||||
const exe = b.addExecutable(.{
|
||||
.name = "lightpanda-snapshot-creator",
|
||||
.use_llvm = true,
|
||||
.root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/main_snapshot_creator.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
.imports = &.{
|
||||
.{ .name = "lightpanda", .module = lightpanda_module },
|
||||
},
|
||||
}),
|
||||
});
|
||||
b.installArtifact(exe);
|
||||
|
||||
const run_cmd = b.addRunArtifact(exe);
|
||||
if (b.args) |args| {
|
||||
run_cmd.addArgs(args);
|
||||
}
|
||||
const run_step = b.step("snapshot_creator", "Generate a v8 snapshot");
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
}
|
||||
|
||||
{
|
||||
// test
|
||||
// ----
|
||||
|
||||
// compile
|
||||
const tests = b.addTest(.{
|
||||
.root_source_file = b.path("src/run_tests.zig"),
|
||||
.test_runner = b.path("src/test_runner.zig"),
|
||||
.target = target,
|
||||
.optimize = mode,
|
||||
.root_module = lightpanda_module,
|
||||
.use_llvm = true,
|
||||
.test_runner = .{ .path = b.path("src/test_runner.zig"), .mode = .simple },
|
||||
});
|
||||
try common(b, tests, options);
|
||||
|
||||
// add jsruntime pretty deps
|
||||
tests.root_module.addAnonymousImport("pretty", .{
|
||||
.root_source_file = b.path("vendor/zig-js-runtime/src/pretty.zig"),
|
||||
});
|
||||
|
||||
const run_tests = b.addRunArtifact(tests);
|
||||
if (b.args) |args| {
|
||||
run_tests.addArgs(args);
|
||||
}
|
||||
|
||||
// step
|
||||
const test_step = b.step("test", "Run unit tests");
|
||||
test_step.dependOn(&run_tests.step);
|
||||
}
|
||||
|
||||
{
|
||||
// ZIGDOM
|
||||
// browser
|
||||
const exe = b.addExecutable(.{
|
||||
.name = "legacy_test",
|
||||
.use_llvm = true,
|
||||
.root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/main_legacy_test.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
.sanitize_c = enable_csan,
|
||||
.sanitize_thread = enable_tsan,
|
||||
.imports = &.{
|
||||
.{ .name = "lightpanda", .module = lightpanda_module },
|
||||
},
|
||||
}),
|
||||
});
|
||||
b.installArtifact(exe);
|
||||
|
||||
const run_cmd = b.addRunArtifact(exe);
|
||||
if (b.args) |args| {
|
||||
run_cmd.addArgs(args);
|
||||
}
|
||||
const run_step = b.step("legacy_test", "Run the app");
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
}
|
||||
|
||||
{
|
||||
// wpt
|
||||
// -----
|
||||
|
||||
// compile and install
|
||||
const wpt = b.addExecutable(.{
|
||||
const exe = b.addExecutable(.{
|
||||
.name = "lightpanda-wpt",
|
||||
.use_llvm = true,
|
||||
.root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/main_wpt.zig"),
|
||||
.target = target,
|
||||
.optimize = mode,
|
||||
.optimize = optimize,
|
||||
.sanitize_c = enable_csan,
|
||||
.sanitize_thread = enable_tsan,
|
||||
.imports = &.{
|
||||
.{ .name = "lightpanda", .module = lightpanda_module },
|
||||
},
|
||||
}),
|
||||
});
|
||||
try common(b, wpt, options);
|
||||
b.installArtifact(exe);
|
||||
|
||||
// run
|
||||
const wpt_cmd = b.addRunArtifact(wpt);
|
||||
const run_cmd = b.addRunArtifact(exe);
|
||||
if (b.args) |args| {
|
||||
wpt_cmd.addArgs(args);
|
||||
run_cmd.addArgs(args);
|
||||
}
|
||||
const run_step = b.step("wpt", "Run WPT tests");
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
}
|
||||
// step
|
||||
const wpt_step = b.step("wpt", "WPT tests");
|
||||
wpt_step.dependOn(&wpt_cmd.step);
|
||||
}
|
||||
|
||||
fn common(
|
||||
b: *std.Build,
|
||||
step: *std.Build.Step.Compile,
|
||||
options: jsruntime.Options,
|
||||
) !void {
|
||||
const target = step.root_module.resolved_target.?;
|
||||
const jsruntimemod = try jsruntime_pkgs.module(
|
||||
b,
|
||||
options,
|
||||
step.root_module.optimize.?,
|
||||
target,
|
||||
);
|
||||
step.root_module.addImport("jsruntime", jsruntimemod);
|
||||
fn addDependencies(b: *Build, mod: *Build.Module, opts: *Build.Step.Options, prebuilt_v8_path: ?[]const u8) !void {
|
||||
mod.addImport("build_config", opts.createModule());
|
||||
|
||||
const netsurf = try moduleNetSurf(b, target);
|
||||
netsurf.addImport("jsruntime", jsruntimemod);
|
||||
step.root_module.addImport("netsurf", netsurf);
|
||||
|
||||
const asyncio = b.addModule("asyncio", .{
|
||||
.root_source_file = b.path("vendor/zig-async-io/src/lib.zig"),
|
||||
});
|
||||
step.root_module.addImport("asyncio", asyncio);
|
||||
|
||||
const tlsmod = b.addModule("tls", .{
|
||||
.root_source_file = b.path("vendor/tls.zig/src/main.zig"),
|
||||
});
|
||||
step.root_module.addImport("tls", tlsmod);
|
||||
|
||||
const wsmod = b.addModule("websocket", .{
|
||||
.root_source_file = b.path("vendor/websocket.zig/src/websocket.zig"),
|
||||
});
|
||||
step.root_module.addImport("websocket", wsmod);
|
||||
}
|
||||
|
||||
fn moduleNetSurf(b: *std.Build, target: std.Build.ResolvedTarget) !*std.Build.Module {
|
||||
const mod = b.addModule("netsurf", .{
|
||||
.root_source_file = b.path("src/netsurf/netsurf.zig"),
|
||||
const target = mod.resolved_target.?;
|
||||
const dep_opts = .{
|
||||
.target = target,
|
||||
});
|
||||
|
||||
const os = target.result.os.tag;
|
||||
const arch = target.result.cpu.arch;
|
||||
|
||||
// iconv
|
||||
const libiconv_lib_path = try std.fmt.allocPrint(
|
||||
mod.owner.allocator,
|
||||
"vendor/libiconv/out/{s}-{s}/lib/libiconv.a",
|
||||
.{ @tagName(os), @tagName(arch) },
|
||||
);
|
||||
const libiconv_include_path = try std.fmt.allocPrint(
|
||||
mod.owner.allocator,
|
||||
"vendor/libiconv/out/{s}-{s}/lib/libiconv.a",
|
||||
.{ @tagName(os), @tagName(arch) },
|
||||
);
|
||||
mod.addObjectFile(b.path(libiconv_lib_path));
|
||||
mod.addIncludePath(b.path(libiconv_include_path));
|
||||
|
||||
// mimalloc
|
||||
mod.addImport("mimalloc", (try moduleMimalloc(b, target)));
|
||||
|
||||
// netsurf libs
|
||||
const ns = "vendor/netsurf";
|
||||
const ns_include_path = try std.fmt.allocPrint(
|
||||
mod.owner.allocator,
|
||||
ns ++ "/out/{s}-{s}/include",
|
||||
.{ @tagName(os), @tagName(arch) },
|
||||
);
|
||||
mod.addIncludePath(b.path(ns_include_path));
|
||||
|
||||
const libs: [4][]const u8 = .{
|
||||
"libdom",
|
||||
"libhubbub",
|
||||
"libparserutils",
|
||||
"libwapcaplet",
|
||||
.optimize = mod.optimize.?,
|
||||
.prebuilt_v8_path = prebuilt_v8_path,
|
||||
.cache_root = b.pathFromRoot(".lp-cache"),
|
||||
};
|
||||
inline for (libs) |lib| {
|
||||
const ns_lib_path = try std.fmt.allocPrint(
|
||||
mod.owner.allocator,
|
||||
ns ++ "/out/{s}-{s}/lib/" ++ lib ++ ".a",
|
||||
.{ @tagName(os), @tagName(arch) },
|
||||
);
|
||||
mod.addObjectFile(b.path(ns_lib_path));
|
||||
mod.addIncludePath(b.path(ns ++ "/" ++ lib ++ "/src"));
|
||||
|
||||
mod.addIncludePath(b.path("vendor/lightpanda"));
|
||||
|
||||
{
|
||||
// html5ever
|
||||
|
||||
// Build step to install html5ever dependency.
|
||||
const html5ever_argv = blk: {
|
||||
const argv: []const []const u8 = &.{
|
||||
"cargo",
|
||||
"build",
|
||||
// Seems cargo can figure out required paths out of Cargo.toml.
|
||||
"--manifest-path",
|
||||
"src/html5ever/Cargo.toml",
|
||||
// TODO: We can prefer `--artifact-dir` once it become stable.
|
||||
"--target-dir",
|
||||
b.getInstallPath(.prefix, "html5ever"),
|
||||
// This must be the last argument.
|
||||
"--release",
|
||||
};
|
||||
|
||||
break :blk switch (mod.optimize.?) {
|
||||
// Prefer dev build on debug option.
|
||||
.Debug => argv[0 .. argv.len - 1],
|
||||
else => argv,
|
||||
};
|
||||
};
|
||||
const html5ever_exec_cargo = b.addSystemCommand(html5ever_argv);
|
||||
const html5ever_step = b.step("html5ever", "Install html5ever dependency (requires cargo)");
|
||||
html5ever_step.dependOn(&html5ever_exec_cargo.step);
|
||||
opts.step.dependOn(html5ever_step);
|
||||
|
||||
const html5ever_obj = switch (mod.optimize.?) {
|
||||
.Debug => b.getInstallPath(.prefix, "html5ever/debug/liblitefetch_html5ever.a"),
|
||||
// Release builds.
|
||||
else => b.getInstallPath(.prefix, "html5ever/release/liblitefetch_html5ever.a"),
|
||||
};
|
||||
|
||||
mod.addObjectFile(.{ .cwd_relative = html5ever_obj });
|
||||
}
|
||||
|
||||
return mod;
|
||||
{
|
||||
// v8
|
||||
const v8_opts = b.addOptions();
|
||||
v8_opts.addOption(bool, "inspector_subtype", false);
|
||||
|
||||
const v8_mod = b.dependency("v8", dep_opts).module("v8");
|
||||
v8_mod.addOptions("default_exports", v8_opts);
|
||||
mod.addImport("v8", v8_mod);
|
||||
}
|
||||
|
||||
fn moduleMimalloc(b: *std.Build, target: std.Build.ResolvedTarget) !*std.Build.Module {
|
||||
const mod = b.addModule("mimalloc", .{
|
||||
.root_source_file = b.path("src/mimalloc/mimalloc.zig"),
|
||||
{
|
||||
//curl
|
||||
{
|
||||
const is_linux = target.result.os.tag == .linux;
|
||||
if (is_linux) {
|
||||
mod.addCMacro("HAVE_LINUX_TCP_H", "1");
|
||||
mod.addCMacro("HAVE_MSG_NOSIGNAL", "1");
|
||||
mod.addCMacro("HAVE_GETHOSTBYNAME_R", "1");
|
||||
}
|
||||
mod.addCMacro("_FILE_OFFSET_BITS", "64");
|
||||
mod.addCMacro("BUILDING_LIBCURL", "1");
|
||||
mod.addCMacro("CURL_DISABLE_AWS", "1");
|
||||
mod.addCMacro("CURL_DISABLE_DICT", "1");
|
||||
mod.addCMacro("CURL_DISABLE_DOH", "1");
|
||||
mod.addCMacro("CURL_DISABLE_FILE", "1");
|
||||
mod.addCMacro("CURL_DISABLE_FTP", "1");
|
||||
mod.addCMacro("CURL_DISABLE_GOPHER", "1");
|
||||
mod.addCMacro("CURL_DISABLE_KERBEROS", "1");
|
||||
mod.addCMacro("CURL_DISABLE_IMAP", "1");
|
||||
mod.addCMacro("CURL_DISABLE_IPFS", "1");
|
||||
mod.addCMacro("CURL_DISABLE_LDAP", "1");
|
||||
mod.addCMacro("CURL_DISABLE_LDAPS", "1");
|
||||
mod.addCMacro("CURL_DISABLE_MQTT", "1");
|
||||
mod.addCMacro("CURL_DISABLE_NTLM", "1");
|
||||
mod.addCMacro("CURL_DISABLE_PROGRESS_METER", "1");
|
||||
mod.addCMacro("CURL_DISABLE_POP3", "1");
|
||||
mod.addCMacro("CURL_DISABLE_RTSP", "1");
|
||||
mod.addCMacro("CURL_DISABLE_SMB", "1");
|
||||
mod.addCMacro("CURL_DISABLE_SMTP", "1");
|
||||
mod.addCMacro("CURL_DISABLE_TELNET", "1");
|
||||
mod.addCMacro("CURL_DISABLE_TFTP", "1");
|
||||
mod.addCMacro("CURL_EXTERN_SYMBOL", "__attribute__ ((__visibility__ (\"default\"))");
|
||||
mod.addCMacro("CURL_OS", if (is_linux) "\"Linux\"" else "\"mac\"");
|
||||
mod.addCMacro("CURL_STATICLIB", "1");
|
||||
mod.addCMacro("ENABLE_IPV6", "1");
|
||||
mod.addCMacro("HAVE_ALARM", "1");
|
||||
mod.addCMacro("HAVE_ALLOCA_H", "1");
|
||||
mod.addCMacro("HAVE_ARPA_INET_H", "1");
|
||||
mod.addCMacro("HAVE_ARPA_TFTP_H", "1");
|
||||
mod.addCMacro("HAVE_ASSERT_H", "1");
|
||||
mod.addCMacro("HAVE_BASENAME", "1");
|
||||
mod.addCMacro("HAVE_BOOL_T", "1");
|
||||
mod.addCMacro("HAVE_BROTLI", "1");
|
||||
mod.addCMacro("HAVE_BUILTIN_AVAILABLE", "1");
|
||||
mod.addCMacro("HAVE_CLOCK_GETTIME_MONOTONIC", "1");
|
||||
mod.addCMacro("HAVE_DLFCN_H", "1");
|
||||
mod.addCMacro("HAVE_ERRNO_H", "1");
|
||||
mod.addCMacro("HAVE_FCNTL", "1");
|
||||
mod.addCMacro("HAVE_FCNTL_H", "1");
|
||||
mod.addCMacro("HAVE_FCNTL_O_NONBLOCK", "1");
|
||||
mod.addCMacro("HAVE_FREEADDRINFO", "1");
|
||||
mod.addCMacro("HAVE_FSETXATTR", "1");
|
||||
mod.addCMacro("HAVE_FSETXATTR_5", "1");
|
||||
mod.addCMacro("HAVE_FTRUNCATE", "1");
|
||||
mod.addCMacro("HAVE_GETADDRINFO", "1");
|
||||
mod.addCMacro("HAVE_GETEUID", "1");
|
||||
mod.addCMacro("HAVE_GETHOSTBYNAME", "1");
|
||||
mod.addCMacro("HAVE_GETHOSTBYNAME_R_6", "1");
|
||||
mod.addCMacro("HAVE_GETHOSTNAME", "1");
|
||||
mod.addCMacro("HAVE_GETPEERNAME", "1");
|
||||
mod.addCMacro("HAVE_GETPPID", "1");
|
||||
mod.addCMacro("HAVE_GETPPID", "1");
|
||||
mod.addCMacro("HAVE_GETPROTOBYNAME", "1");
|
||||
mod.addCMacro("HAVE_GETPWUID", "1");
|
||||
mod.addCMacro("HAVE_GETPWUID_R", "1");
|
||||
mod.addCMacro("HAVE_GETRLIMIT", "1");
|
||||
mod.addCMacro("HAVE_GETSOCKNAME", "1");
|
||||
mod.addCMacro("HAVE_GETTIMEOFDAY", "1");
|
||||
mod.addCMacro("HAVE_GMTIME_R", "1");
|
||||
mod.addCMacro("HAVE_IDN2_H", "1");
|
||||
mod.addCMacro("HAVE_IF_NAMETOINDEX", "1");
|
||||
mod.addCMacro("HAVE_IFADDRS_H", "1");
|
||||
mod.addCMacro("HAVE_INET_ADDR", "1");
|
||||
mod.addCMacro("HAVE_INET_PTON", "1");
|
||||
mod.addCMacro("HAVE_INTTYPES_H", "1");
|
||||
mod.addCMacro("HAVE_IOCTL", "1");
|
||||
mod.addCMacro("HAVE_IOCTL_FIONBIO", "1");
|
||||
mod.addCMacro("HAVE_IOCTL_SIOCGIFADDR", "1");
|
||||
mod.addCMacro("HAVE_LDAP_URL_PARSE", "1");
|
||||
mod.addCMacro("HAVE_LIBGEN_H", "1");
|
||||
mod.addCMacro("HAVE_LIBZ", "1");
|
||||
mod.addCMacro("HAVE_LL", "1");
|
||||
mod.addCMacro("HAVE_LOCALE_H", "1");
|
||||
mod.addCMacro("HAVE_LOCALTIME_R", "1");
|
||||
mod.addCMacro("HAVE_LONGLONG", "1");
|
||||
mod.addCMacro("HAVE_MALLOC_H", "1");
|
||||
mod.addCMacro("HAVE_MEMORY_H", "1");
|
||||
mod.addCMacro("HAVE_NET_IF_H", "1");
|
||||
mod.addCMacro("HAVE_NETDB_H", "1");
|
||||
mod.addCMacro("HAVE_NETINET_IN_H", "1");
|
||||
mod.addCMacro("HAVE_NETINET_TCP_H", "1");
|
||||
mod.addCMacro("HAVE_PIPE", "1");
|
||||
mod.addCMacro("HAVE_POLL", "1");
|
||||
mod.addCMacro("HAVE_POLL_FINE", "1");
|
||||
mod.addCMacro("HAVE_POLL_H", "1");
|
||||
mod.addCMacro("HAVE_POSIX_STRERROR_R", "1");
|
||||
mod.addCMacro("HAVE_PTHREAD_H", "1");
|
||||
mod.addCMacro("HAVE_PWD_H", "1");
|
||||
mod.addCMacro("HAVE_RECV", "1");
|
||||
mod.addCMacro("HAVE_SA_FAMILY_T", "1");
|
||||
mod.addCMacro("HAVE_SELECT", "1");
|
||||
mod.addCMacro("HAVE_SEND", "1");
|
||||
mod.addCMacro("HAVE_SETJMP_H", "1");
|
||||
mod.addCMacro("HAVE_SETLOCALE", "1");
|
||||
mod.addCMacro("HAVE_SETRLIMIT", "1");
|
||||
mod.addCMacro("HAVE_SETSOCKOPT", "1");
|
||||
mod.addCMacro("HAVE_SIGACTION", "1");
|
||||
mod.addCMacro("HAVE_SIGINTERRUPT", "1");
|
||||
mod.addCMacro("HAVE_SIGNAL", "1");
|
||||
mod.addCMacro("HAVE_SIGNAL_H", "1");
|
||||
mod.addCMacro("HAVE_SIGSETJMP", "1");
|
||||
mod.addCMacro("HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID", "1");
|
||||
mod.addCMacro("HAVE_SOCKET", "1");
|
||||
mod.addCMacro("HAVE_STDBOOL_H", "1");
|
||||
mod.addCMacro("HAVE_STDINT_H", "1");
|
||||
mod.addCMacro("HAVE_STDIO_H", "1");
|
||||
mod.addCMacro("HAVE_STDLIB_H", "1");
|
||||
mod.addCMacro("HAVE_STRCASECMP", "1");
|
||||
mod.addCMacro("HAVE_STRDUP", "1");
|
||||
mod.addCMacro("HAVE_STRERROR_R", "1");
|
||||
mod.addCMacro("HAVE_STRING_H", "1");
|
||||
mod.addCMacro("HAVE_STRINGS_H", "1");
|
||||
mod.addCMacro("HAVE_STRSTR", "1");
|
||||
mod.addCMacro("HAVE_STRTOK_R", "1");
|
||||
mod.addCMacro("HAVE_STRTOLL", "1");
|
||||
mod.addCMacro("HAVE_STRUCT_SOCKADDR_STORAGE", "1");
|
||||
mod.addCMacro("HAVE_STRUCT_TIMEVAL", "1");
|
||||
mod.addCMacro("HAVE_SYS_IOCTL_H", "1");
|
||||
mod.addCMacro("HAVE_SYS_PARAM_H", "1");
|
||||
mod.addCMacro("HAVE_SYS_POLL_H", "1");
|
||||
mod.addCMacro("HAVE_SYS_RESOURCE_H", "1");
|
||||
mod.addCMacro("HAVE_SYS_SELECT_H", "1");
|
||||
mod.addCMacro("HAVE_SYS_SOCKET_H", "1");
|
||||
mod.addCMacro("HAVE_SYS_STAT_H", "1");
|
||||
mod.addCMacro("HAVE_SYS_TIME_H", "1");
|
||||
mod.addCMacro("HAVE_SYS_TYPES_H", "1");
|
||||
mod.addCMacro("HAVE_SYS_UIO_H", "1");
|
||||
mod.addCMacro("HAVE_SYS_UN_H", "1");
|
||||
mod.addCMacro("HAVE_TERMIO_H", "1");
|
||||
mod.addCMacro("HAVE_TERMIOS_H", "1");
|
||||
mod.addCMacro("HAVE_TIME_H", "1");
|
||||
mod.addCMacro("HAVE_UNAME", "1");
|
||||
mod.addCMacro("HAVE_UNISTD_H", "1");
|
||||
mod.addCMacro("HAVE_UTIME", "1");
|
||||
mod.addCMacro("HAVE_UTIME_H", "1");
|
||||
mod.addCMacro("HAVE_UTIMES", "1");
|
||||
mod.addCMacro("HAVE_VARIADIC_MACROS_C99", "1");
|
||||
mod.addCMacro("HAVE_VARIADIC_MACROS_GCC", "1");
|
||||
mod.addCMacro("HAVE_ZLIB_H", "1");
|
||||
mod.addCMacro("RANDOM_FILE", "\"/dev/urandom\"");
|
||||
mod.addCMacro("RECV_TYPE_ARG1", "int");
|
||||
mod.addCMacro("RECV_TYPE_ARG2", "void *");
|
||||
mod.addCMacro("RECV_TYPE_ARG3", "size_t");
|
||||
mod.addCMacro("RECV_TYPE_ARG4", "int");
|
||||
mod.addCMacro("RECV_TYPE_RETV", "ssize_t");
|
||||
mod.addCMacro("SEND_QUAL_ARG2", "const");
|
||||
mod.addCMacro("SEND_TYPE_ARG1", "int");
|
||||
mod.addCMacro("SEND_TYPE_ARG2", "void *");
|
||||
mod.addCMacro("SEND_TYPE_ARG3", "size_t");
|
||||
mod.addCMacro("SEND_TYPE_ARG4", "int");
|
||||
mod.addCMacro("SEND_TYPE_RETV", "ssize_t");
|
||||
mod.addCMacro("SIZEOF_CURL_OFF_T", "8");
|
||||
mod.addCMacro("SIZEOF_INT", "4");
|
||||
mod.addCMacro("SIZEOF_LONG", "8");
|
||||
mod.addCMacro("SIZEOF_OFF_T", "8");
|
||||
mod.addCMacro("SIZEOF_SHORT", "2");
|
||||
mod.addCMacro("SIZEOF_SIZE_T", "8");
|
||||
mod.addCMacro("SIZEOF_TIME_T", "8");
|
||||
mod.addCMacro("STDC_HEADERS", "1");
|
||||
mod.addCMacro("TIME_WITH_SYS_TIME", "1");
|
||||
mod.addCMacro("USE_NGHTTP2", "1");
|
||||
mod.addCMacro("USE_OPENSSL", "1");
|
||||
mod.addCMacro("OPENSSL_IS_BORINGSSL", "1");
|
||||
mod.addCMacro("USE_THREADS_POSIX", "1");
|
||||
mod.addCMacro("USE_UNIX_SOCKETS", "1");
|
||||
}
|
||||
|
||||
try buildZlib(b, mod);
|
||||
try buildBrotli(b, mod);
|
||||
const boringssl_dep = b.dependency("boringssl-zig", .{
|
||||
.target = target,
|
||||
.optimize = mod.optimize.?,
|
||||
.force_pic = true,
|
||||
});
|
||||
|
||||
const os = target.result.os.tag;
|
||||
const arch = target.result.cpu.arch;
|
||||
const ssl = boringssl_dep.artifact("ssl");
|
||||
ssl.bundle_ubsan_rt = false;
|
||||
const crypto = boringssl_dep.artifact("crypto");
|
||||
crypto.bundle_ubsan_rt = false;
|
||||
|
||||
const mimalloc = "vendor/mimalloc";
|
||||
const lib_path = try std.fmt.allocPrint(
|
||||
mod.owner.allocator,
|
||||
mimalloc ++ "/out/{s}-{s}/lib/libmimalloc.a",
|
||||
.{ @tagName(os), @tagName(arch) },
|
||||
);
|
||||
mod.addObjectFile(b.path(lib_path));
|
||||
mod.addIncludePath(b.path(mimalloc ++ "/include"));
|
||||
mod.linkLibrary(ssl);
|
||||
mod.linkLibrary(crypto);
|
||||
try buildNghttp2(b, mod);
|
||||
try buildCurl(b, mod);
|
||||
|
||||
return mod;
|
||||
switch (target.result.os.tag) {
|
||||
.macos => {
|
||||
// needed for proxying on mac
|
||||
mod.addSystemFrameworkPath(.{ .cwd_relative = "/System/Library/Frameworks" });
|
||||
mod.linkFramework("CoreFoundation", .{});
|
||||
mod.linkFramework("SystemConfiguration", .{});
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn buildZlib(b: *Build, m: *Build.Module) !void {
|
||||
const zlib = b.addLibrary(.{
|
||||
.name = "zlib",
|
||||
.root_module = m,
|
||||
});
|
||||
|
||||
const root = "vendor/zlib/";
|
||||
zlib.installHeader(b.path(root ++ "zlib.h"), "zlib.h");
|
||||
zlib.installHeader(b.path(root ++ "zconf.h"), "zconf.h");
|
||||
zlib.addCSourceFiles(.{ .flags = &.{
|
||||
"-DHAVE_SYS_TYPES_H",
|
||||
"-DHAVE_STDINT_H",
|
||||
"-DHAVE_STDDEF_H",
|
||||
}, .files = &.{
|
||||
root ++ "adler32.c",
|
||||
root ++ "compress.c",
|
||||
root ++ "crc32.c",
|
||||
root ++ "deflate.c",
|
||||
root ++ "gzclose.c",
|
||||
root ++ "gzlib.c",
|
||||
root ++ "gzread.c",
|
||||
root ++ "gzwrite.c",
|
||||
root ++ "inflate.c",
|
||||
root ++ "infback.c",
|
||||
root ++ "inftrees.c",
|
||||
root ++ "inffast.c",
|
||||
root ++ "trees.c",
|
||||
root ++ "uncompr.c",
|
||||
root ++ "zutil.c",
|
||||
} });
|
||||
}
|
||||
|
||||
fn buildBrotli(b: *Build, m: *Build.Module) !void {
|
||||
const brotli = b.addLibrary(.{
|
||||
.name = "brotli",
|
||||
.root_module = m,
|
||||
});
|
||||
|
||||
const root = "vendor/brotli/c/";
|
||||
brotli.addIncludePath(b.path(root ++ "include"));
|
||||
brotli.addCSourceFiles(.{ .flags = &.{}, .files = &.{
|
||||
root ++ "common/constants.c",
|
||||
root ++ "common/context.c",
|
||||
root ++ "common/dictionary.c",
|
||||
root ++ "common/platform.c",
|
||||
root ++ "common/shared_dictionary.c",
|
||||
root ++ "common/transform.c",
|
||||
root ++ "dec/bit_reader.c",
|
||||
root ++ "dec/decode.c",
|
||||
root ++ "dec/huffman.c",
|
||||
root ++ "dec/prefix.c",
|
||||
root ++ "dec/state.c",
|
||||
root ++ "dec/static_init.c",
|
||||
} });
|
||||
}
|
||||
|
||||
fn buildNghttp2(b: *Build, m: *Build.Module) !void {
|
||||
const nghttp2 = b.addLibrary(.{
|
||||
.name = "nghttp2",
|
||||
.root_module = m,
|
||||
});
|
||||
|
||||
const root = "vendor/nghttp2/";
|
||||
nghttp2.addIncludePath(b.path(root ++ "lib"));
|
||||
nghttp2.addIncludePath(b.path(root ++ "lib/includes"));
|
||||
nghttp2.addCSourceFiles(.{ .flags = &.{
|
||||
"-DNGHTTP2_STATICLIB",
|
||||
"-DHAVE_NETINET_IN",
|
||||
"-DHAVE_TIME_H",
|
||||
}, .files = &.{
|
||||
root ++ "lib/sfparse.c",
|
||||
root ++ "lib/nghttp2_alpn.c",
|
||||
root ++ "lib/nghttp2_buf.c",
|
||||
root ++ "lib/nghttp2_callbacks.c",
|
||||
root ++ "lib/nghttp2_debug.c",
|
||||
root ++ "lib/nghttp2_extpri.c",
|
||||
root ++ "lib/nghttp2_frame.c",
|
||||
root ++ "lib/nghttp2_hd.c",
|
||||
root ++ "lib/nghttp2_hd_huffman.c",
|
||||
root ++ "lib/nghttp2_hd_huffman_data.c",
|
||||
root ++ "lib/nghttp2_helper.c",
|
||||
root ++ "lib/nghttp2_http.c",
|
||||
root ++ "lib/nghttp2_map.c",
|
||||
root ++ "lib/nghttp2_mem.c",
|
||||
root ++ "lib/nghttp2_option.c",
|
||||
root ++ "lib/nghttp2_outbound_item.c",
|
||||
root ++ "lib/nghttp2_pq.c",
|
||||
root ++ "lib/nghttp2_priority_spec.c",
|
||||
root ++ "lib/nghttp2_queue.c",
|
||||
root ++ "lib/nghttp2_rcbuf.c",
|
||||
root ++ "lib/nghttp2_session.c",
|
||||
root ++ "lib/nghttp2_stream.c",
|
||||
root ++ "lib/nghttp2_submit.c",
|
||||
root ++ "lib/nghttp2_version.c",
|
||||
root ++ "lib/nghttp2_ratelim.c",
|
||||
root ++ "lib/nghttp2_time.c",
|
||||
} });
|
||||
}
|
||||
|
||||
fn buildCurl(b: *Build, m: *Build.Module) !void {
|
||||
const curl = b.addLibrary(.{
|
||||
.name = "curl",
|
||||
.root_module = m,
|
||||
});
|
||||
|
||||
const root = "vendor/curl/";
|
||||
|
||||
curl.addIncludePath(b.path(root ++ "lib"));
|
||||
curl.addIncludePath(b.path(root ++ "include"));
|
||||
curl.addIncludePath(b.path("vendor/zlib"));
|
||||
|
||||
curl.addCSourceFiles(.{
|
||||
.flags = &.{},
|
||||
.files = &.{
|
||||
root ++ "lib/altsvc.c",
|
||||
root ++ "lib/amigaos.c",
|
||||
root ++ "lib/asyn-ares.c",
|
||||
root ++ "lib/asyn-base.c",
|
||||
root ++ "lib/asyn-thrdd.c",
|
||||
root ++ "lib/bufq.c",
|
||||
root ++ "lib/bufref.c",
|
||||
root ++ "lib/cf-h1-proxy.c",
|
||||
root ++ "lib/cf-h2-proxy.c",
|
||||
root ++ "lib/cf-haproxy.c",
|
||||
root ++ "lib/cf-https-connect.c",
|
||||
root ++ "lib/cf-socket.c",
|
||||
root ++ "lib/cfilters.c",
|
||||
root ++ "lib/conncache.c",
|
||||
root ++ "lib/connect.c",
|
||||
root ++ "lib/content_encoding.c",
|
||||
root ++ "lib/cookie.c",
|
||||
root ++ "lib/cshutdn.c",
|
||||
root ++ "lib/curl_addrinfo.c",
|
||||
root ++ "lib/curl_des.c",
|
||||
root ++ "lib/curl_endian.c",
|
||||
root ++ "lib/curl_fnmatch.c",
|
||||
root ++ "lib/curl_get_line.c",
|
||||
root ++ "lib/curl_gethostname.c",
|
||||
root ++ "lib/curl_gssapi.c",
|
||||
root ++ "lib/curl_memrchr.c",
|
||||
root ++ "lib/curl_ntlm_core.c",
|
||||
root ++ "lib/curl_range.c",
|
||||
root ++ "lib/curl_rtmp.c",
|
||||
root ++ "lib/curl_sasl.c",
|
||||
root ++ "lib/curl_sha512_256.c",
|
||||
root ++ "lib/curl_sspi.c",
|
||||
root ++ "lib/curl_threads.c",
|
||||
root ++ "lib/curl_trc.c",
|
||||
root ++ "lib/cw-out.c",
|
||||
root ++ "lib/cw-pause.c",
|
||||
root ++ "lib/dict.c",
|
||||
root ++ "lib/doh.c",
|
||||
root ++ "lib/dynhds.c",
|
||||
root ++ "lib/easy.c",
|
||||
root ++ "lib/easygetopt.c",
|
||||
root ++ "lib/easyoptions.c",
|
||||
root ++ "lib/escape.c",
|
||||
root ++ "lib/fake_addrinfo.c",
|
||||
root ++ "lib/file.c",
|
||||
root ++ "lib/fileinfo.c",
|
||||
root ++ "lib/fopen.c",
|
||||
root ++ "lib/formdata.c",
|
||||
root ++ "lib/ftp.c",
|
||||
root ++ "lib/ftplistparser.c",
|
||||
root ++ "lib/getenv.c",
|
||||
root ++ "lib/getinfo.c",
|
||||
root ++ "lib/gopher.c",
|
||||
root ++ "lib/hash.c",
|
||||
root ++ "lib/headers.c",
|
||||
root ++ "lib/hmac.c",
|
||||
root ++ "lib/hostip.c",
|
||||
root ++ "lib/hostip4.c",
|
||||
root ++ "lib/hostip6.c",
|
||||
root ++ "lib/hsts.c",
|
||||
root ++ "lib/http.c",
|
||||
root ++ "lib/http1.c",
|
||||
root ++ "lib/http2.c",
|
||||
root ++ "lib/http_aws_sigv4.c",
|
||||
root ++ "lib/http_chunks.c",
|
||||
root ++ "lib/http_digest.c",
|
||||
root ++ "lib/http_negotiate.c",
|
||||
root ++ "lib/http_ntlm.c",
|
||||
root ++ "lib/http_proxy.c",
|
||||
root ++ "lib/httpsrr.c",
|
||||
root ++ "lib/idn.c",
|
||||
root ++ "lib/if2ip.c",
|
||||
root ++ "lib/imap.c",
|
||||
root ++ "lib/krb5.c",
|
||||
root ++ "lib/ldap.c",
|
||||
root ++ "lib/llist.c",
|
||||
root ++ "lib/macos.c",
|
||||
root ++ "lib/md4.c",
|
||||
root ++ "lib/md5.c",
|
||||
root ++ "lib/memdebug.c",
|
||||
root ++ "lib/mime.c",
|
||||
root ++ "lib/mprintf.c",
|
||||
root ++ "lib/mqtt.c",
|
||||
root ++ "lib/multi.c",
|
||||
root ++ "lib/multi_ev.c",
|
||||
root ++ "lib/netrc.c",
|
||||
root ++ "lib/noproxy.c",
|
||||
root ++ "lib/openldap.c",
|
||||
root ++ "lib/parsedate.c",
|
||||
root ++ "lib/pingpong.c",
|
||||
root ++ "lib/pop3.c",
|
||||
root ++ "lib/progress.c",
|
||||
root ++ "lib/psl.c",
|
||||
root ++ "lib/rand.c",
|
||||
root ++ "lib/rename.c",
|
||||
root ++ "lib/request.c",
|
||||
root ++ "lib/rtsp.c",
|
||||
root ++ "lib/select.c",
|
||||
root ++ "lib/sendf.c",
|
||||
root ++ "lib/setopt.c",
|
||||
root ++ "lib/sha256.c",
|
||||
root ++ "lib/share.c",
|
||||
root ++ "lib/slist.c",
|
||||
root ++ "lib/smb.c",
|
||||
root ++ "lib/smtp.c",
|
||||
root ++ "lib/socketpair.c",
|
||||
root ++ "lib/socks.c",
|
||||
root ++ "lib/socks_gssapi.c",
|
||||
root ++ "lib/socks_sspi.c",
|
||||
root ++ "lib/speedcheck.c",
|
||||
root ++ "lib/splay.c",
|
||||
root ++ "lib/strcase.c",
|
||||
root ++ "lib/strdup.c",
|
||||
root ++ "lib/strequal.c",
|
||||
root ++ "lib/strerror.c",
|
||||
root ++ "lib/system_win32.c",
|
||||
root ++ "lib/telnet.c",
|
||||
root ++ "lib/tftp.c",
|
||||
root ++ "lib/transfer.c",
|
||||
root ++ "lib/uint-bset.c",
|
||||
root ++ "lib/uint-hash.c",
|
||||
root ++ "lib/uint-spbset.c",
|
||||
root ++ "lib/uint-table.c",
|
||||
root ++ "lib/url.c",
|
||||
root ++ "lib/urlapi.c",
|
||||
root ++ "lib/version.c",
|
||||
root ++ "lib/ws.c",
|
||||
root ++ "lib/curlx/base64.c",
|
||||
root ++ "lib/curlx/dynbuf.c",
|
||||
root ++ "lib/curlx/inet_ntop.c",
|
||||
root ++ "lib/curlx/nonblock.c",
|
||||
root ++ "lib/curlx/strparse.c",
|
||||
root ++ "lib/curlx/timediff.c",
|
||||
root ++ "lib/curlx/timeval.c",
|
||||
root ++ "lib/curlx/wait.c",
|
||||
root ++ "lib/curlx/warnless.c",
|
||||
root ++ "lib/vquic/curl_ngtcp2.c",
|
||||
root ++ "lib/vquic/curl_osslq.c",
|
||||
root ++ "lib/vquic/curl_quiche.c",
|
||||
root ++ "lib/vquic/vquic.c",
|
||||
root ++ "lib/vquic/vquic-tls.c",
|
||||
root ++ "lib/vauth/cleartext.c",
|
||||
root ++ "lib/vauth/cram.c",
|
||||
root ++ "lib/vauth/digest.c",
|
||||
root ++ "lib/vauth/digest_sspi.c",
|
||||
root ++ "lib/vauth/gsasl.c",
|
||||
root ++ "lib/vauth/krb5_gssapi.c",
|
||||
root ++ "lib/vauth/krb5_sspi.c",
|
||||
root ++ "lib/vauth/ntlm.c",
|
||||
root ++ "lib/vauth/ntlm_sspi.c",
|
||||
root ++ "lib/vauth/oauth2.c",
|
||||
root ++ "lib/vauth/spnego_gssapi.c",
|
||||
root ++ "lib/vauth/spnego_sspi.c",
|
||||
root ++ "lib/vauth/vauth.c",
|
||||
root ++ "lib/vtls/cipher_suite.c",
|
||||
root ++ "lib/vtls/openssl.c",
|
||||
root ++ "lib/vtls/hostcheck.c",
|
||||
root ++ "lib/vtls/keylog.c",
|
||||
root ++ "lib/vtls/vtls.c",
|
||||
root ++ "lib/vtls/vtls_scache.c",
|
||||
root ++ "lib/vtls/x509asn1.c",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const Manifest = struct {
|
||||
version: []const u8,
|
||||
minimum_zig_version: []const u8,
|
||||
|
||||
fn init(b: *std.Build) Manifest {
|
||||
const input = @embedFile("build.zig.zon");
|
||||
|
||||
var diagnostics: std.zon.parse.Diagnostics = .{};
|
||||
defer diagnostics.deinit(b.allocator);
|
||||
|
||||
return std.zon.parse.fromSlice(Manifest, b.allocator, input, &diagnostics, .{
|
||||
.free_on_error = true,
|
||||
.ignore_unknown_fields = true,
|
||||
}) catch |err| {
|
||||
switch (err) {
|
||||
error.OutOfMemory => @panic("OOM"),
|
||||
error.ParseZon => {
|
||||
std.debug.print("Parse diagnostics:\n{f}\n", .{diagnostics});
|
||||
std.process.exit(1);
|
||||
},
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
18
build.zig.zon
Normal file
18
build.zig.zon
Normal file
@@ -0,0 +1,18 @@
|
||||
.{
|
||||
.name = .browser,
|
||||
.paths = .{""},
|
||||
.version = "0.0.0",
|
||||
.fingerprint = 0xda130f3af836cea0, // Changing this has security and trust implications.
|
||||
.minimum_zig_version = "0.15.2",
|
||||
.dependencies = .{
|
||||
.v8 = .{
|
||||
.url = "https://github.com/lightpanda-io/zig-v8-fork/archive/d6b5f89cfc7feece29359e8c848bb916e8ecfab6.tar.gz",
|
||||
.hash = "v8-0.0.0-xddH6_0gBABrJc5cL6-P2wGvvweTTCgWdpmClr9r-C-s",
|
||||
},
|
||||
//.v8 = .{ .path = "../zig-v8-fork" },
|
||||
.@"boringssl-zig" = .{
|
||||
.url = "git+https://github.com/Syndica/boringssl-zig.git#c53df00d06b02b755ad88bbf4d1202ed9687b096",
|
||||
.hash = "boringssl-0.1.0-VtJeWehMAAA4RNnwRnzEvKcS9rjsR1QVRw1uJrwXxmVK",
|
||||
},
|
||||
},
|
||||
}
|
||||
219
flake.lock
generated
Normal file
219
flake.lock
generated
Normal file
@@ -0,0 +1,219 @@
|
||||
{
|
||||
"nodes": {
|
||||
"fenix": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
],
|
||||
"rust-analyzer-src": "rust-analyzer-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1763016383,
|
||||
"narHash": "sha256-eYmo7FNvm3q08iROzwIi8i9dWuUbJJl3uLR3OLnSmdI=",
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"rev": "0fad5c0e5c531358e7174cd666af4608f08bc3ba",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-compat": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1696426674,
|
||||
"narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=",
|
||||
"owner": "edolstra",
|
||||
"repo": "flake-compat",
|
||||
"rev": "0f9255e01c2351cc7d116c072cb317785dd33b33",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "edolstra",
|
||||
"repo": "flake-compat",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1731533236,
|
||||
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-utils_2": {
|
||||
"inputs": {
|
||||
"systems": "systems_2"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1705309234,
|
||||
"narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"gitignore": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"zlsPkg",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1709087332,
|
||||
"narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "gitignore.nix",
|
||||
"rev": "637db329424fd7e46cf4185293b9cc8c88c95394",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "hercules-ci",
|
||||
"repo": "gitignore.nix",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1763043403,
|
||||
"narHash": "sha256-DgCTbHdIpzbXSlQlOZEWj8oPt2lrRMlSk03oIstvkVQ=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "75e04ecd084f93d4105ce68c07dac7656291fe2e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nixos",
|
||||
"ref": "release-25.05",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"fenix": "fenix",
|
||||
"flake-utils": "flake-utils",
|
||||
"nixpkgs": "nixpkgs",
|
||||
"zigPkgs": "zigPkgs",
|
||||
"zlsPkg": "zlsPkg"
|
||||
}
|
||||
},
|
||||
"rust-analyzer-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1762860488,
|
||||
"narHash": "sha256-rMfWMCOo/pPefM2We0iMBLi2kLBAnYoB9thi4qS7uk4=",
|
||||
"owner": "rust-lang",
|
||||
"repo": "rust-analyzer",
|
||||
"rev": "2efc80078029894eec0699f62ec8d5c1a56af763",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "rust-lang",
|
||||
"ref": "nightly",
|
||||
"repo": "rust-analyzer",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"systems_2": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"zigPkgs": {
|
||||
"inputs": {
|
||||
"flake-compat": "flake-compat",
|
||||
"flake-utils": "flake-utils_2",
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1762907712,
|
||||
"narHash": "sha256-VNW/+VYIg6N4b9Iq+F0YZmm22n74IdFS7hsPLblWuOY=",
|
||||
"owner": "mitchellh",
|
||||
"repo": "zig-overlay",
|
||||
"rev": "d16453ee78765e49527c56d23386cead799b6b53",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "mitchellh",
|
||||
"repo": "zig-overlay",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"zlsPkg": {
|
||||
"inputs": {
|
||||
"gitignore": "gitignore",
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
],
|
||||
"zig-overlay": [
|
||||
"zigPkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1756048867,
|
||||
"narHash": "sha256-GFzSHUljcxy7sM1PaabbkQUdUnLwpherekPWJFxXtnk=",
|
||||
"owner": "zigtools",
|
||||
"repo": "zls",
|
||||
"rev": "ce6c8f02c78e622421cfc2405c67c5222819ec03",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "zigtools",
|
||||
"ref": "0.15.0",
|
||||
"repo": "zls",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
85
flake.nix
Normal file
85
flake.nix
Normal file
@@ -0,0 +1,85 @@
|
||||
{
|
||||
description = "headless browser designed for AI and automation";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:nixos/nixpkgs/release-25.05";
|
||||
|
||||
zigPkgs.url = "github:mitchellh/zig-overlay";
|
||||
zigPkgs.inputs.nixpkgs.follows = "nixpkgs";
|
||||
|
||||
zlsPkg.url = "github:zigtools/zls/0.15.0";
|
||||
zlsPkg.inputs.zig-overlay.follows = "zigPkgs";
|
||||
zlsPkg.inputs.nixpkgs.follows = "nixpkgs";
|
||||
|
||||
fenix = {
|
||||
url = "github:nix-community/fenix";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
};
|
||||
|
||||
outputs =
|
||||
{
|
||||
nixpkgs,
|
||||
zigPkgs,
|
||||
zlsPkg,
|
||||
fenix,
|
||||
flake-utils,
|
||||
...
|
||||
}:
|
||||
flake-utils.lib.eachDefaultSystem (
|
||||
system:
|
||||
let
|
||||
overlays = [
|
||||
(final: prev: {
|
||||
zigpkgs = zigPkgs.packages.${prev.system};
|
||||
zls = zlsPkg.packages.${prev.system}.default;
|
||||
})
|
||||
];
|
||||
|
||||
pkgs = import nixpkgs {
|
||||
inherit system overlays;
|
||||
};
|
||||
|
||||
rustToolchain = fenix.packages.${system}.stable.toolchain;
|
||||
|
||||
# We need crtbeginS.o for building.
|
||||
crtFiles = pkgs.runCommand "crt-files" { } ''
|
||||
mkdir -p $out/lib
|
||||
cp -r ${pkgs.gcc.cc}/lib/gcc $out/lib/gcc
|
||||
'';
|
||||
|
||||
# This build pipeline is very unhappy without an FHS-compliant env.
|
||||
fhs = pkgs.buildFHSEnv {
|
||||
name = "fhs-shell";
|
||||
multiArch = true;
|
||||
targetPkgs =
|
||||
pkgs: with pkgs; [
|
||||
# Build Tools
|
||||
zigpkgs."0.15.2"
|
||||
zls
|
||||
rustToolchain
|
||||
python3
|
||||
pkg-config
|
||||
cmake
|
||||
gperf
|
||||
|
||||
# GCC
|
||||
gcc
|
||||
gcc.cc.lib
|
||||
crtFiles
|
||||
|
||||
# Libaries
|
||||
expat.dev
|
||||
glib.dev
|
||||
glibc.dev
|
||||
zlib
|
||||
];
|
||||
};
|
||||
in
|
||||
{
|
||||
devShells.default = fhs.env;
|
||||
}
|
||||
);
|
||||
}
|
||||
139
src/App.zig
Normal file
139
src/App.zig
Normal file
@@ -0,0 +1,139 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const log = @import("log.zig");
|
||||
const Http = @import("http/Http.zig");
|
||||
const Snapshot = @import("browser/js/Snapshot.zig");
|
||||
const Platform = @import("browser/js/Platform.zig");
|
||||
|
||||
const Notification = @import("Notification.zig");
|
||||
const Telemetry = @import("telemetry/telemetry.zig").Telemetry;
|
||||
|
||||
// Container for global state / objects that various parts of the system
|
||||
// might need.
|
||||
const App = @This();
|
||||
|
||||
http: Http,
|
||||
config: Config,
|
||||
platform: Platform,
|
||||
snapshot: Snapshot,
|
||||
telemetry: Telemetry,
|
||||
allocator: Allocator,
|
||||
app_dir_path: ?[]const u8,
|
||||
notification: *Notification,
|
||||
shutdown: bool = false,
|
||||
|
||||
pub const RunMode = enum {
|
||||
help,
|
||||
fetch,
|
||||
serve,
|
||||
version,
|
||||
};
|
||||
|
||||
pub const Config = struct {
|
||||
run_mode: RunMode,
|
||||
tls_verify_host: bool = true,
|
||||
http_proxy: ?[:0]const u8 = null,
|
||||
proxy_bearer_token: ?[:0]const u8 = null,
|
||||
http_timeout_ms: ?u31 = null,
|
||||
http_connect_timeout_ms: ?u31 = null,
|
||||
http_max_host_open: ?u8 = null,
|
||||
http_max_concurrent: ?u8 = null,
|
||||
user_agent: [:0]const u8,
|
||||
};
|
||||
|
||||
pub fn init(allocator: Allocator, config: Config) !*App {
|
||||
const app = try allocator.create(App);
|
||||
errdefer allocator.destroy(app);
|
||||
|
||||
app.config = config;
|
||||
app.allocator = allocator;
|
||||
|
||||
app.notification = try Notification.init(allocator, null);
|
||||
errdefer app.notification.deinit();
|
||||
|
||||
app.http = try Http.init(allocator, .{
|
||||
.max_host_open = config.http_max_host_open orelse 4,
|
||||
.max_concurrent = config.http_max_concurrent orelse 10,
|
||||
.timeout_ms = config.http_timeout_ms orelse 5000,
|
||||
.connect_timeout_ms = config.http_connect_timeout_ms orelse 0,
|
||||
.http_proxy = config.http_proxy,
|
||||
.tls_verify_host = config.tls_verify_host,
|
||||
.proxy_bearer_token = config.proxy_bearer_token,
|
||||
.user_agent = config.user_agent,
|
||||
});
|
||||
errdefer app.http.deinit();
|
||||
|
||||
app.platform = try Platform.init();
|
||||
errdefer app.platform.deinit();
|
||||
|
||||
app.snapshot = try Snapshot.load(allocator);
|
||||
errdefer app.snapshot.deinit(allocator);
|
||||
|
||||
app.app_dir_path = getAndMakeAppDir(allocator);
|
||||
|
||||
app.telemetry = try Telemetry.init(app, config.run_mode);
|
||||
errdefer app.telemetry.deinit();
|
||||
|
||||
try app.telemetry.register(app.notification);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
pub fn deinit(self: *App) void {
|
||||
if (@atomicRmw(bool, &self.shutdown, .Xchg, true, .monotonic)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const allocator = self.allocator;
|
||||
if (self.app_dir_path) |app_dir_path| {
|
||||
allocator.free(app_dir_path);
|
||||
self.app_dir_path = null;
|
||||
}
|
||||
self.telemetry.deinit();
|
||||
self.notification.deinit();
|
||||
self.http.deinit();
|
||||
self.snapshot.deinit(allocator);
|
||||
self.platform.deinit();
|
||||
|
||||
allocator.destroy(self);
|
||||
}
|
||||
|
||||
fn getAndMakeAppDir(allocator: Allocator) ?[]const u8 {
|
||||
if (@import("builtin").is_test) {
|
||||
return allocator.dupe(u8, "/tmp") catch unreachable;
|
||||
}
|
||||
const app_dir_path = std.fs.getAppDataDir(allocator, "lightpanda") catch |err| {
|
||||
log.warn(.app, "get data dir", .{ .err = err });
|
||||
return null;
|
||||
};
|
||||
|
||||
std.fs.cwd().makePath(app_dir_path) catch |err| switch (err) {
|
||||
error.PathAlreadyExists => return app_dir_path,
|
||||
else => {
|
||||
allocator.free(app_dir_path);
|
||||
log.warn(.app, "create data dir", .{ .err = err, .path = app_dir_path });
|
||||
return null;
|
||||
},
|
||||
};
|
||||
return app_dir_path;
|
||||
}
|
||||
412
src/Notification.zig
Normal file
412
src/Notification.zig
Normal file
@@ -0,0 +1,412 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
const log = @import("log.zig");
|
||||
const Page = @import("browser/Page.zig");
|
||||
const Transfer = @import("http/Client.zig").Transfer;
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const List = std.DoublyLinkedList;
|
||||
|
||||
// Allows code to register for and emit events.
|
||||
// Keeps two lists
|
||||
// 1 - for a given event type, a linked list of all the listeners
|
||||
// 2 - for a given listener, a list of all it's registration
|
||||
// The 2nd one is so that a listener can unregister all of it's listeners
|
||||
// (there's currently no need for a listener to unregister only 1 or more
|
||||
// specific listener).
|
||||
//
|
||||
// Scoping is important. Imagine we created a global singleton registry, and our
|
||||
// CDP code registers for the "network_bytes_sent" event, because it needs to
|
||||
// send messages to the client when this happens. Our HTTP client could then
|
||||
// emit a "network_bytes_sent" message. It would be easy, and it would work.
|
||||
// That is, it would work until the Telemetry code makes an HTTP request, and
|
||||
// because everything's just one big global, that gets picked up by the
|
||||
// registered CDP listener, and the telemetry network activity gets sent to the
|
||||
// CDP client.
|
||||
//
|
||||
// To avoid this, one way or another, we need scoping. We could still have
|
||||
// a global registry but every "register" and every "emit" has some type of
|
||||
// "scope". This would have a run-time cost and still require some coordination
|
||||
// between components to share a common scope.
|
||||
//
|
||||
// Instead, the approach that we take is to have a notification instance per
|
||||
// scope. This makes some things harder, but we only plan on having 2
|
||||
// notification instances at a given time: one in a Browser and one in the App.
|
||||
// What about something like Telemetry, which lives outside of a Browser but
|
||||
// still cares about Browser-events (like .page_navigate)? When the Browser
|
||||
// notification is created, a `notification_created` event is raised in the
|
||||
// App's notification, which Telemetry is registered for. This allows Telemetry
|
||||
// to register for events in the Browser notification. See the Telemetry's
|
||||
// register function.
|
||||
const Notification = @This();
|
||||
// Every event type (which are hard-coded), has a list of Listeners.
|
||||
// When the event happens, we dispatch to those listener.
|
||||
event_listeners: EventListeners,
|
||||
|
||||
// list of listeners for a specified receiver
|
||||
// @intFromPtr(receiver) -> [listener1, listener2, ...]
|
||||
// Used when `unregisterAll` is called.
|
||||
listeners: std.AutoHashMapUnmanaged(usize, std.ArrayListUnmanaged(*Listener)),
|
||||
|
||||
allocator: Allocator,
|
||||
mem_pool: std.heap.MemoryPool(Listener),
|
||||
|
||||
const EventListeners = struct {
|
||||
page_remove: List = .{},
|
||||
page_created: List = .{},
|
||||
page_navigate: List = .{},
|
||||
page_navigated: List = .{},
|
||||
page_network_idle: List = .{},
|
||||
page_network_almost_idle: List = .{},
|
||||
http_request_fail: List = .{},
|
||||
http_request_start: List = .{},
|
||||
http_request_intercept: List = .{},
|
||||
http_request_done: List = .{},
|
||||
http_request_auth_required: List = .{},
|
||||
http_response_data: List = .{},
|
||||
http_response_header_done: List = .{},
|
||||
notification_created: List = .{},
|
||||
};
|
||||
|
||||
const Events = union(enum) {
|
||||
page_remove: PageRemove,
|
||||
page_created: *Page,
|
||||
page_navigate: *const PageNavigate,
|
||||
page_navigated: *const PageNavigated,
|
||||
page_network_idle: *const PageNetworkIdle,
|
||||
page_network_almost_idle: *const PageNetworkAlmostIdle,
|
||||
http_request_fail: *const RequestFail,
|
||||
http_request_start: *const RequestStart,
|
||||
http_request_intercept: *const RequestIntercept,
|
||||
http_request_auth_required: *const RequestAuthRequired,
|
||||
http_request_done: *const RequestDone,
|
||||
http_response_data: *const ResponseData,
|
||||
http_response_header_done: *const ResponseHeaderDone,
|
||||
notification_created: *Notification,
|
||||
};
|
||||
const EventType = std.meta.FieldEnum(Events);
|
||||
|
||||
pub const PageRemove = struct {};
|
||||
|
||||
pub const PageNavigate = struct {
|
||||
req_id: usize,
|
||||
timestamp: u64,
|
||||
url: [:0]const u8,
|
||||
opts: Page.NavigateOpts,
|
||||
};
|
||||
|
||||
pub const PageNavigated = struct {
|
||||
req_id: usize,
|
||||
timestamp: u64,
|
||||
url: [:0]const u8,
|
||||
opts: Page.NavigatedOpts,
|
||||
};
|
||||
|
||||
pub const PageNetworkIdle = struct {
|
||||
timestamp: u64,
|
||||
};
|
||||
|
||||
pub const PageNetworkAlmostIdle = struct {
|
||||
timestamp: u64,
|
||||
};
|
||||
|
||||
pub const RequestStart = struct {
|
||||
transfer: *Transfer,
|
||||
};
|
||||
|
||||
pub const RequestIntercept = struct {
|
||||
transfer: *Transfer,
|
||||
wait_for_interception: *bool,
|
||||
};
|
||||
|
||||
pub const RequestAuthRequired = struct {
|
||||
transfer: *Transfer,
|
||||
wait_for_interception: *bool,
|
||||
};
|
||||
|
||||
pub const ResponseData = struct {
|
||||
data: []const u8,
|
||||
transfer: *Transfer,
|
||||
};
|
||||
|
||||
pub const ResponseHeaderDone = struct {
|
||||
transfer: *Transfer,
|
||||
};
|
||||
|
||||
pub const RequestDone = struct {
|
||||
transfer: *Transfer,
|
||||
};
|
||||
|
||||
pub const RequestFail = struct {
|
||||
transfer: *Transfer,
|
||||
err: anyerror,
|
||||
};
|
||||
|
||||
pub fn init(allocator: Allocator, parent: ?*Notification) !*Notification {
|
||||
|
||||
// This is put on the heap because we want to raise a .notification_created
|
||||
// event, so that, something like Telemetry, can receive the
|
||||
// .page_navigate event on all notification instances. That can only work
|
||||
// if we dispatch .notification_created with a *Notification.
|
||||
const notification = try allocator.create(Notification);
|
||||
errdefer allocator.destroy(notification);
|
||||
|
||||
notification.* = .{
|
||||
.listeners = .{},
|
||||
.event_listeners = .{},
|
||||
.allocator = allocator,
|
||||
.mem_pool = std.heap.MemoryPool(Listener).init(allocator),
|
||||
};
|
||||
|
||||
if (parent) |pn| {
|
||||
pn.dispatch(.notification_created, notification);
|
||||
}
|
||||
|
||||
return notification;
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Notification) void {
|
||||
const allocator = self.allocator;
|
||||
|
||||
var it = self.listeners.valueIterator();
|
||||
while (it.next()) |listener| {
|
||||
listener.deinit(allocator);
|
||||
}
|
||||
self.listeners.deinit(allocator);
|
||||
self.mem_pool.deinit();
|
||||
allocator.destroy(self);
|
||||
}
|
||||
|
||||
pub fn register(self: *Notification, comptime event: EventType, receiver: anytype, func: EventFunc(event)) !void {
|
||||
var list = &@field(self.event_listeners, @tagName(event));
|
||||
|
||||
var listener = try self.mem_pool.create();
|
||||
errdefer self.mem_pool.destroy(listener);
|
||||
|
||||
listener.* = .{
|
||||
.node = .{},
|
||||
.list = list,
|
||||
.receiver = receiver,
|
||||
.event = event,
|
||||
.func = @ptrCast(func),
|
||||
.struct_name = @typeName(@typeInfo(@TypeOf(receiver)).pointer.child),
|
||||
};
|
||||
|
||||
const allocator = self.allocator;
|
||||
const gop = try self.listeners.getOrPut(allocator, @intFromPtr(receiver));
|
||||
if (gop.found_existing == false) {
|
||||
gop.value_ptr.* = .{};
|
||||
}
|
||||
try gop.value_ptr.append(allocator, listener);
|
||||
|
||||
// we don't add this until we've successfully added the entry to
|
||||
// self.listeners
|
||||
list.append(&listener.node);
|
||||
}
|
||||
|
||||
pub fn unregister(self: *Notification, comptime event: EventType, receiver: anytype) void {
|
||||
var listeners = self.listeners.getPtr(@intFromPtr(receiver)) orelse return;
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < listeners.items.len) {
|
||||
const listener = listeners.items[i];
|
||||
if (listener.event != event) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
listener.list.remove(&listener.node);
|
||||
self.mem_pool.destroy(listener);
|
||||
_ = listeners.swapRemove(i);
|
||||
}
|
||||
|
||||
if (listeners.items.len == 0) {
|
||||
listeners.deinit(self.allocator);
|
||||
const removed = self.listeners.remove(@intFromPtr(receiver));
|
||||
std.debug.assert(removed == true);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unregisterAll(self: *Notification, receiver: *anyopaque) void {
|
||||
var kv = self.listeners.fetchRemove(@intFromPtr(receiver)) orelse return;
|
||||
for (kv.value.items) |listener| {
|
||||
listener.list.remove(&listener.node);
|
||||
self.mem_pool.destroy(listener);
|
||||
}
|
||||
kv.value.deinit(self.allocator);
|
||||
}
|
||||
|
||||
pub fn dispatch(self: *Notification, comptime event: EventType, data: ArgType(event)) void {
|
||||
const list = &@field(self.event_listeners, @tagName(event));
|
||||
|
||||
var node = list.first;
|
||||
while (node) |n| {
|
||||
const listener: *Listener = @fieldParentPtr("node", n);
|
||||
const func: EventFunc(event) = @ptrCast(@alignCast(listener.func));
|
||||
func(listener.receiver, data) catch |err| {
|
||||
log.err(.app, "dispatch error", .{
|
||||
.err = err,
|
||||
.event = event,
|
||||
.source = "notification",
|
||||
.listener = listener.struct_name,
|
||||
});
|
||||
};
|
||||
node = n.next;
|
||||
}
|
||||
}
|
||||
|
||||
// Given an event type enum, returns the type of arg the event emits
|
||||
fn ArgType(comptime event: Notification.EventType) type {
|
||||
inline for (std.meta.fields(Notification.Events)) |f| {
|
||||
if (std.mem.eql(u8, f.name, @tagName(event))) {
|
||||
return f.type;
|
||||
}
|
||||
}
|
||||
unreachable;
|
||||
}
|
||||
|
||||
// Given an event type enum, returns the listening function type
|
||||
fn EventFunc(comptime event: Notification.EventType) type {
|
||||
return *const fn (*anyopaque, ArgType(event)) anyerror!void;
|
||||
}
|
||||
|
||||
// A listener. This is 1 receiver, with its function, and the linked list
|
||||
// node that goes in the appropriate EventListeners list.
|
||||
const Listener = struct {
|
||||
// the receiver of the event, i.e. the self parameter to `func`
|
||||
receiver: *anyopaque,
|
||||
|
||||
// the function to call
|
||||
func: *const anyopaque,
|
||||
|
||||
// For logging slightly better error
|
||||
struct_name: []const u8,
|
||||
|
||||
event: Notification.EventType,
|
||||
|
||||
// intrusive linked list node
|
||||
node: List.Node,
|
||||
|
||||
// The event list this listener belongs to.
|
||||
// We need this in order to be able to remove the node from the list
|
||||
list: *List,
|
||||
};
|
||||
|
||||
const testing = std.testing;
|
||||
test "Notification" {
|
||||
var notifier = try Notification.init(testing.allocator, null);
|
||||
defer notifier.deinit();
|
||||
|
||||
// noop
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.req_id = 1,
|
||||
.timestamp = 4,
|
||||
.url = undefined,
|
||||
.opts = .{},
|
||||
});
|
||||
|
||||
var tc = TestClient{};
|
||||
|
||||
try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.req_id = 1,
|
||||
.timestamp = 4,
|
||||
.url = undefined,
|
||||
.opts = .{},
|
||||
});
|
||||
try testing.expectEqual(4, tc.page_navigate);
|
||||
|
||||
notifier.unregisterAll(&tc);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.req_id = 1,
|
||||
.timestamp = 10,
|
||||
.url = undefined,
|
||||
.opts = .{},
|
||||
});
|
||||
try testing.expectEqual(4, tc.page_navigate);
|
||||
|
||||
try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
|
||||
try notifier.register(.page_navigated, &tc, TestClient.pageNavigated);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.req_id = 1,
|
||||
.timestamp = 10,
|
||||
.url = undefined,
|
||||
.opts = .{},
|
||||
});
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 6, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(14, tc.page_navigate);
|
||||
try testing.expectEqual(6, tc.page_navigated);
|
||||
|
||||
notifier.unregisterAll(&tc);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.req_id = 1,
|
||||
.timestamp = 100,
|
||||
.url = undefined,
|
||||
.opts = .{},
|
||||
});
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(14, tc.page_navigate);
|
||||
try testing.expectEqual(6, tc.page_navigated);
|
||||
|
||||
{
|
||||
// unregister
|
||||
try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
|
||||
try notifier.register(.page_navigated, &tc, TestClient.pageNavigated);
|
||||
notifier.dispatch(.page_navigate, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(114, tc.page_navigate);
|
||||
try testing.expectEqual(1006, tc.page_navigated);
|
||||
|
||||
notifier.unregister(.page_navigate, &tc);
|
||||
notifier.dispatch(.page_navigate, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(114, tc.page_navigate);
|
||||
try testing.expectEqual(2006, tc.page_navigated);
|
||||
|
||||
notifier.unregister(.page_navigated, &tc);
|
||||
notifier.dispatch(.page_navigate, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(114, tc.page_navigate);
|
||||
try testing.expectEqual(2006, tc.page_navigated);
|
||||
|
||||
// already unregistered, try anyways
|
||||
notifier.unregister(.page_navigated, &tc);
|
||||
notifier.dispatch(.page_navigate, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(114, tc.page_navigate);
|
||||
try testing.expectEqual(2006, tc.page_navigated);
|
||||
}
|
||||
}
|
||||
|
||||
const TestClient = struct {
|
||||
page_navigate: u64 = 0,
|
||||
page_navigated: u64 = 0,
|
||||
|
||||
fn pageNavigate(ptr: *anyopaque, data: *const Notification.PageNavigate) !void {
|
||||
const self: *TestClient = @ptrCast(@alignCast(ptr));
|
||||
self.page_navigate += data.timestamp;
|
||||
}
|
||||
|
||||
fn pageNavigated(ptr: *anyopaque, data: *const Notification.PageNavigated) !void {
|
||||
const self: *TestClient = @ptrCast(@alignCast(ptr));
|
||||
self.page_navigated += data.timestamp;
|
||||
}
|
||||
};
|
||||
1470
src/Server.zig
Normal file
1470
src/Server.zig
Normal file
File diff suppressed because it is too large
Load Diff
107
src/Sighandler.zig
Normal file
107
src/Sighandler.zig
Normal file
@@ -0,0 +1,107 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
//! This structure processes operating system signals (SIGINT, SIGTERM)
|
||||
//! and runs callbacks to clean up the system gracefully.
|
||||
//!
|
||||
//! The structure does not clear the memory allocated in the arena,
|
||||
//! clear the entire arena when exiting the program.
|
||||
const std = @import("std");
|
||||
const assert = std.debug.assert;
|
||||
const Allocator = std.mem.Allocator;
|
||||
const lp = @import("lightpanda");
|
||||
|
||||
const log = lp.log;
|
||||
|
||||
const SigHandler = @This();
|
||||
|
||||
arena: Allocator,
|
||||
|
||||
sigset: std.posix.sigset_t = undefined,
|
||||
handle_thread: ?std.Thread = null,
|
||||
|
||||
attempt: u32 = 0,
|
||||
listeners: std.ArrayList(Listener) = .empty,
|
||||
|
||||
pub const Listener = struct {
|
||||
args: []const u8,
|
||||
start: *const fn (context: *const anyopaque) void,
|
||||
};
|
||||
|
||||
pub fn install(self: *SigHandler) !void {
|
||||
// Block SIGINT and SIGTERM for the current thread and all created from it
|
||||
self.sigset = std.posix.sigemptyset();
|
||||
std.posix.sigaddset(&self.sigset, std.posix.SIG.INT);
|
||||
std.posix.sigaddset(&self.sigset, std.posix.SIG.TERM);
|
||||
std.posix.sigaddset(&self.sigset, std.posix.SIG.QUIT);
|
||||
std.posix.sigprocmask(std.posix.SIG.BLOCK, &self.sigset, null);
|
||||
|
||||
self.handle_thread = try std.Thread.spawn(.{ .allocator = self.arena }, SigHandler.sighandle, .{self});
|
||||
self.handle_thread.?.detach();
|
||||
}
|
||||
|
||||
pub fn on(self: *SigHandler, func: anytype, args: std.meta.ArgsTuple(@TypeOf(func))) !void {
|
||||
assert(@typeInfo(@TypeOf(func)).@"fn".return_type.? == void);
|
||||
|
||||
const Args = @TypeOf(args);
|
||||
const TypeErased = struct {
|
||||
fn start(context: *const anyopaque) void {
|
||||
const args_casted: *const Args = @ptrCast(@alignCast(context));
|
||||
@call(.auto, func, args_casted.*);
|
||||
}
|
||||
};
|
||||
|
||||
const buffer = try self.arena.alignedAlloc(u8, .of(Args), @sizeOf(Args));
|
||||
errdefer self.arena.free(buffer);
|
||||
|
||||
const bytes: []const u8 = @ptrCast((&args)[0..1]);
|
||||
@memcpy(buffer, bytes);
|
||||
|
||||
try self.listeners.append(self.arena, .{
|
||||
.args = buffer,
|
||||
.start = TypeErased.start,
|
||||
});
|
||||
}
|
||||
|
||||
fn sighandle(self: *SigHandler) noreturn {
|
||||
while (true) {
|
||||
var sig: c_int = 0;
|
||||
|
||||
const rc = std.c.sigwait(&self.sigset, &sig);
|
||||
if (rc != 0) {
|
||||
log.err(.app, "Unable to process signal {}", .{rc});
|
||||
std.process.exit(1);
|
||||
}
|
||||
|
||||
switch (sig) {
|
||||
std.posix.SIG.INT, std.posix.SIG.TERM => {
|
||||
if (self.attempt > 1) {
|
||||
std.process.exit(1);
|
||||
}
|
||||
self.attempt += 1;
|
||||
|
||||
log.info(.app, "Received termination signal...", .{});
|
||||
for (self.listeners.items) |*item| {
|
||||
item.start(item.args.ptr);
|
||||
}
|
||||
continue;
|
||||
},
|
||||
else => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
142
src/TestHTTPServer.zig
Normal file
142
src/TestHTTPServer.zig
Normal file
@@ -0,0 +1,142 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
const TestHTTPServer = @This();
|
||||
|
||||
shutdown: bool,
|
||||
listener: ?std.net.Server,
|
||||
handler: Handler,
|
||||
|
||||
const Handler = *const fn (req: *std.http.Server.Request) anyerror!void;
|
||||
|
||||
pub fn init(handler: Handler) TestHTTPServer {
|
||||
return .{
|
||||
.shutdown = true,
|
||||
.listener = null,
|
||||
.handler = handler,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *TestHTTPServer) void {
|
||||
self.shutdown = true;
|
||||
if (self.listener) |*listener| {
|
||||
listener.deinit();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(self: *TestHTTPServer, wg: *std.Thread.WaitGroup) !void {
|
||||
const address = try std.net.Address.parseIp("127.0.0.1", 9582);
|
||||
|
||||
self.listener = try address.listen(.{ .reuse_address = true });
|
||||
var listener = &self.listener.?;
|
||||
|
||||
wg.finish();
|
||||
|
||||
while (true) {
|
||||
const conn = listener.accept() catch |err| {
|
||||
if (self.shutdown) {
|
||||
return;
|
||||
}
|
||||
return err;
|
||||
};
|
||||
const thrd = try std.Thread.spawn(.{}, handleConnection, .{ self, conn });
|
||||
thrd.detach();
|
||||
}
|
||||
}
|
||||
|
||||
fn handleConnection(self: *TestHTTPServer, conn: std.net.Server.Connection) !void {
|
||||
defer conn.stream.close();
|
||||
|
||||
var req_buf: [2048]u8 = undefined;
|
||||
var conn_reader = conn.stream.reader(&req_buf);
|
||||
var conn_writer = conn.stream.writer(&req_buf);
|
||||
|
||||
var http_server = std.http.Server.init(conn_reader.interface(), &conn_writer.interface);
|
||||
|
||||
while (true) {
|
||||
var req = http_server.receiveHead() catch |err| switch (err) {
|
||||
error.ReadFailed => continue,
|
||||
error.HttpConnectionClosing => continue,
|
||||
else => {
|
||||
std.debug.print("Test HTTP Server error: {}\n", .{err});
|
||||
return err;
|
||||
},
|
||||
};
|
||||
|
||||
self.handler(&req) catch |err| {
|
||||
std.debug.print("test http error '{s}': {}\n", .{ req.head.target, err });
|
||||
try req.respond("server error", .{ .status = .internal_server_error });
|
||||
return;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sendFile(req: *std.http.Server.Request, file_path: []const u8) !void {
|
||||
var file = std.fs.cwd().openFile(file_path, .{}) catch |err| switch (err) {
|
||||
error.FileNotFound => return req.respond("server error", .{ .status = .not_found }),
|
||||
else => return err,
|
||||
};
|
||||
defer file.close();
|
||||
|
||||
const stat = try file.stat();
|
||||
var send_buffer: [4096]u8 = undefined;
|
||||
|
||||
var res = try req.respondStreaming(&send_buffer, .{
|
||||
.content_length = stat.size,
|
||||
.respond_options = .{
|
||||
.extra_headers = &.{
|
||||
.{ .name = "content-type", .value = getContentType(file_path) },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
var read_buffer: [4096]u8 = undefined;
|
||||
var reader = file.reader(&read_buffer);
|
||||
_ = try res.writer.sendFileAll(&reader, .unlimited);
|
||||
try res.writer.flush();
|
||||
try res.end();
|
||||
}
|
||||
|
||||
fn getContentType(file_path: []const u8) []const u8 {
|
||||
if (std.mem.endsWith(u8, file_path, ".js")) {
|
||||
return "application/json";
|
||||
}
|
||||
|
||||
if (std.mem.endsWith(u8, file_path, ".html")) {
|
||||
return "text/html";
|
||||
}
|
||||
|
||||
if (std.mem.endsWith(u8, file_path, ".htm")) {
|
||||
return "text/html";
|
||||
}
|
||||
|
||||
if (std.mem.endsWith(u8, file_path, ".xml")) {
|
||||
// some wpt tests do this
|
||||
return "text/xml";
|
||||
}
|
||||
|
||||
if (std.mem.endsWith(u8, file_path, ".mjs")) {
|
||||
// mjs are ECMAScript modules
|
||||
return "application/json";
|
||||
}
|
||||
|
||||
std.debug.print("TestHTTPServer asked to serve an unknown file type: {s}\n", .{file_path});
|
||||
return "text/html";
|
||||
}
|
||||
114
src/browser/Browser.zig
Normal file
114
src/browser/Browser.zig
Normal file
@@ -0,0 +1,114 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const ArenaAllocator = std.heap.ArenaAllocator;
|
||||
|
||||
const js = @import("js/js.zig");
|
||||
const log = @import("../log.zig");
|
||||
const App = @import("../App.zig");
|
||||
const HttpClient = @import("../http/Client.zig");
|
||||
const Notification = @import("../Notification.zig");
|
||||
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
const Session = @import("Session.zig");
|
||||
|
||||
// Browser is an instance of the browser.
|
||||
// You can create multiple browser instances.
|
||||
// A browser contains only one session.
|
||||
const Browser = @This();
|
||||
|
||||
env: js.Env,
|
||||
app: *App,
|
||||
session: ?Session,
|
||||
allocator: Allocator,
|
||||
http_client: *HttpClient,
|
||||
call_arena: ArenaAllocator,
|
||||
page_arena: ArenaAllocator,
|
||||
session_arena: ArenaAllocator,
|
||||
transfer_arena: ArenaAllocator,
|
||||
notification: *Notification,
|
||||
|
||||
pub fn init(app: *App) !Browser {
|
||||
const allocator = app.allocator;
|
||||
|
||||
var env = try js.Env.init(allocator, &app.platform, &app.snapshot);
|
||||
errdefer env.deinit();
|
||||
|
||||
const notification = try Notification.init(allocator, app.notification);
|
||||
app.http.client.notification = notification;
|
||||
app.http.client.next_request_id = 0; // Should we track ids in CDP only?
|
||||
errdefer notification.deinit();
|
||||
|
||||
return .{
|
||||
.app = app,
|
||||
.env = env,
|
||||
.session = null,
|
||||
.allocator = allocator,
|
||||
.notification = notification,
|
||||
.http_client = app.http.client,
|
||||
.call_arena = ArenaAllocator.init(allocator),
|
||||
.page_arena = ArenaAllocator.init(allocator),
|
||||
.session_arena = ArenaAllocator.init(allocator),
|
||||
.transfer_arena = ArenaAllocator.init(allocator),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Browser) void {
|
||||
self.closeSession();
|
||||
self.env.deinit();
|
||||
self.call_arena.deinit();
|
||||
self.page_arena.deinit();
|
||||
self.session_arena.deinit();
|
||||
self.transfer_arena.deinit();
|
||||
self.http_client.notification = null;
|
||||
self.notification.deinit();
|
||||
}
|
||||
|
||||
pub fn newSession(self: *Browser) !*Session {
|
||||
self.closeSession();
|
||||
self.session = @as(Session, undefined);
|
||||
const session = &self.session.?;
|
||||
try Session.init(session, self);
|
||||
return session;
|
||||
}
|
||||
|
||||
pub fn closeSession(self: *Browser) void {
|
||||
if (self.session) |*session| {
|
||||
session.deinit();
|
||||
self.session = null;
|
||||
_ = self.session_arena.reset(.{ .retain_with_limit = 1 * 1024 * 1024 });
|
||||
self.env.lowMemoryNotification();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn runMicrotasks(self: *const Browser) void {
|
||||
self.env.runMicrotasks();
|
||||
}
|
||||
|
||||
pub fn runMessageLoop(self: *const Browser) void {
|
||||
while (self.env.pumpMessageLoop()) {
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.browser, "pumpMessageLoop", .{});
|
||||
}
|
||||
}
|
||||
self.env.runIdleTasks();
|
||||
}
|
||||
516
src/browser/EventManager.zig
Normal file
516
src/browser/EventManager.zig
Normal file
@@ -0,0 +1,516 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const log = @import("../log.zig");
|
||||
const String = @import("../string.zig").String;
|
||||
|
||||
const js = @import("js/js.zig");
|
||||
const Page = @import("Page.zig");
|
||||
|
||||
const Node = @import("webapi/Node.zig");
|
||||
const Event = @import("webapi/Event.zig");
|
||||
const EventTarget = @import("webapi/EventTarget.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const IS_DEBUG = builtin.mode == .Debug;
|
||||
|
||||
pub const EventManager = @This();
|
||||
|
||||
page: *Page,
|
||||
arena: Allocator,
|
||||
listener_pool: std.heap.MemoryPool(Listener),
|
||||
list_pool: std.heap.MemoryPool(std.DoublyLinkedList),
|
||||
lookup: std.AutoHashMapUnmanaged(usize, *std.DoublyLinkedList),
|
||||
dispatch_depth: usize,
|
||||
deferred_removals: std.ArrayList(struct { list: *std.DoublyLinkedList, listener: *Listener }),
|
||||
|
||||
pub fn init(page: *Page) EventManager {
|
||||
return .{
|
||||
.page = page,
|
||||
.lookup = .{},
|
||||
.arena = page.arena,
|
||||
.list_pool = std.heap.MemoryPool(std.DoublyLinkedList).init(page.arena),
|
||||
.listener_pool = std.heap.MemoryPool(Listener).init(page.arena),
|
||||
.dispatch_depth = 0,
|
||||
.deferred_removals = .{},
|
||||
};
|
||||
}
|
||||
|
||||
pub const RegisterOptions = struct {
|
||||
once: bool = false,
|
||||
capture: bool = false,
|
||||
passive: bool = false,
|
||||
signal: ?*@import("webapi/AbortSignal.zig") = null,
|
||||
};
|
||||
|
||||
pub const Callback = union(enum) {
|
||||
function: js.Function,
|
||||
object: js.Object,
|
||||
};
|
||||
|
||||
pub fn register(self: *EventManager, target: *EventTarget, typ: []const u8, callback: Callback, opts: RegisterOptions) !void {
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.event, "eventManager.register", .{ .type = typ, .capture = opts.capture, .once = opts.once, .target = target });
|
||||
}
|
||||
|
||||
// If a signal is provided and already aborted, don't register the listener
|
||||
if (opts.signal) |signal| {
|
||||
if (signal.getAborted()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const gop = try self.lookup.getOrPut(self.arena, @intFromPtr(target));
|
||||
if (gop.found_existing) {
|
||||
// check for duplicate callbacks already registered
|
||||
var node = gop.value_ptr.*.first;
|
||||
while (node) |n| {
|
||||
const listener: *Listener = @alignCast(@fieldParentPtr("node", n));
|
||||
if (listener.typ.eqlSlice(typ)) {
|
||||
const is_duplicate = switch (callback) {
|
||||
.object => |obj| listener.function.eqlObject(obj),
|
||||
.function => |func| listener.function.eqlFunction(func),
|
||||
};
|
||||
if (is_duplicate and listener.capture == opts.capture) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
node = n.next;
|
||||
}
|
||||
} else {
|
||||
gop.value_ptr.* = try self.list_pool.create();
|
||||
gop.value_ptr.*.* = .{};
|
||||
}
|
||||
|
||||
const func = switch (callback) {
|
||||
.function => |f| Function{ .value = f },
|
||||
.object => |o| Function{ .object = o },
|
||||
};
|
||||
|
||||
const listener = try self.listener_pool.create();
|
||||
listener.* = .{
|
||||
.node = .{},
|
||||
.once = opts.once,
|
||||
.capture = opts.capture,
|
||||
.passive = opts.passive,
|
||||
.function = func,
|
||||
.signal = opts.signal,
|
||||
.typ = try String.init(self.arena, typ, .{}),
|
||||
};
|
||||
// append the listener to the list of listeners for this target
|
||||
gop.value_ptr.*.append(&listener.node);
|
||||
}
|
||||
|
||||
pub fn remove(self: *EventManager, target: *EventTarget, typ: []const u8, callback: Callback, use_capture: bool) void {
|
||||
const list = self.lookup.get(@intFromPtr(target)) orelse return;
|
||||
if (findListener(list, typ, callback, use_capture)) |listener| {
|
||||
self.removeListener(list, listener);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dispatch(self: *EventManager, target: *EventTarget, event: *Event) !void {
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.event, "eventManager.dispatch", .{ .type = event._type_string.str(), .bubbles = event._bubbles });
|
||||
}
|
||||
|
||||
event._target = target;
|
||||
event._dispatch_target = target; // Store original target for composedPath()
|
||||
var was_handled = false;
|
||||
|
||||
defer if (was_handled) {
|
||||
self.page.js.runMicrotasks();
|
||||
};
|
||||
|
||||
switch (target._type) {
|
||||
.node => |node| try self.dispatchNode(node, event, &was_handled),
|
||||
.xhr,
|
||||
.window,
|
||||
.abort_signal,
|
||||
.media_query_list,
|
||||
.message_port,
|
||||
.text_track_cue,
|
||||
.navigation,
|
||||
.screen,
|
||||
.screen_orientation,
|
||||
.generic,
|
||||
=> {
|
||||
const list = self.lookup.get(@intFromPtr(target)) orelse return;
|
||||
try self.dispatchAll(list, target, event, &was_handled);
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// There are a lot of events that can be attached via addEventListener or as
|
||||
// a property, like the XHR events, or window.onload. You might think that the
|
||||
// property is just a shortcut for calling addEventListener, but they are distinct.
|
||||
// An event set via property cannot be removed by removeEventListener. If you
|
||||
// set both the property and add a listener, they both execute.
|
||||
const DispatchWithFunctionOptions = struct {
|
||||
context: []const u8,
|
||||
inject_target: bool = true,
|
||||
};
|
||||
pub fn dispatchWithFunction(self: *EventManager, target: *EventTarget, event: *Event, function_: ?js.Function, comptime opts: DispatchWithFunctionOptions) !void {
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.event, "dispatchWithFunction", .{ .type = event._type_string.str(), .context = opts.context, .has_function = function_ != null });
|
||||
}
|
||||
|
||||
if (comptime opts.inject_target) {
|
||||
event._target = target;
|
||||
event._dispatch_target = target; // Store original target for composedPath()
|
||||
}
|
||||
|
||||
var was_dispatched = false;
|
||||
defer if (was_dispatched) {
|
||||
self.page.js.runMicrotasks();
|
||||
};
|
||||
|
||||
if (function_) |func| {
|
||||
event._current_target = target;
|
||||
if (func.callWithThis(void, target, .{event})) {
|
||||
was_dispatched = true;
|
||||
} else |err| {
|
||||
// a non-JS error
|
||||
log.warn(.event, opts.context, .{ .err = err });
|
||||
}
|
||||
}
|
||||
|
||||
const list = self.lookup.get(@intFromPtr(target)) orelse return;
|
||||
try self.dispatchAll(list, target, event, &was_dispatched);
|
||||
}
|
||||
|
||||
fn dispatchNode(self: *EventManager, target: *Node, event: *Event, was_handled: *bool) !void {
|
||||
const ShadowRoot = @import("webapi/ShadowRoot.zig");
|
||||
|
||||
// Defer runs even on early return - ensures event phase is reset
|
||||
// and default actions execute (unless prevented)
|
||||
defer {
|
||||
event._event_phase = .none;
|
||||
|
||||
// Execute default action if not prevented
|
||||
if (event._prevent_default) {
|
||||
// can't return in a defer (╯°□°)╯︵ ┻━┻
|
||||
} else if (event._type_string.eqlSlice("click")) {
|
||||
self.page.handleClick(target) catch |err| {
|
||||
log.warn(.event, "page.click", .{ .err = err });
|
||||
};
|
||||
} else if (event._type_string.eqlSlice("keydown")) {
|
||||
self.page.handleKeydown(target, event) catch |err| {
|
||||
log.warn(.event, "page.keydown", .{ .err = err });
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
var path_len: usize = 0;
|
||||
var path_buffer: [128]*EventTarget = undefined;
|
||||
|
||||
var node: ?*Node = target;
|
||||
while (node) |n| {
|
||||
if (path_len >= path_buffer.len) break;
|
||||
path_buffer[path_len] = n.asEventTarget();
|
||||
path_len += 1;
|
||||
|
||||
// Check if this node is a shadow root
|
||||
if (n.is(ShadowRoot)) |shadow| {
|
||||
event._needs_retargeting = true;
|
||||
|
||||
// If event is not composed, stop at shadow boundary
|
||||
if (!event._composed) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Otherwise, jump to the shadow host and continue
|
||||
node = shadow._host.asNode();
|
||||
continue;
|
||||
}
|
||||
|
||||
node = n._parent;
|
||||
}
|
||||
|
||||
// Even though the window isn't part of the DOM, events always propagate
|
||||
// through it in the capture phase (unless we stopped at a shadow boundary)
|
||||
if (path_len < path_buffer.len) {
|
||||
path_buffer[path_len] = self.page.window.asEventTarget();
|
||||
path_len += 1;
|
||||
}
|
||||
|
||||
const path = path_buffer[0..path_len];
|
||||
|
||||
// Phase 1: Capturing phase (root → target, excluding target)
|
||||
// This happens for all events, regardless of bubbling
|
||||
event._event_phase = .capturing_phase;
|
||||
var i: usize = path_len;
|
||||
while (i > 1) {
|
||||
i -= 1;
|
||||
const current_target = path[i];
|
||||
if (self.lookup.get(@intFromPtr(current_target))) |list| {
|
||||
try self.dispatchPhase(list, current_target, event, was_handled, true);
|
||||
if (event._stop_propagation) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: At target
|
||||
event._event_phase = .at_target;
|
||||
const target_et = target.asEventTarget();
|
||||
if (self.lookup.get(@intFromPtr(target_et))) |list| {
|
||||
try self.dispatchPhase(list, target_et, event, was_handled, null);
|
||||
if (event._stop_propagation) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 3: Bubbling phase (target → root, excluding target)
|
||||
// This only happens if the event bubbles
|
||||
if (event._bubbles) {
|
||||
event._event_phase = .bubbling_phase;
|
||||
for (path[1..]) |current_target| {
|
||||
if (self.lookup.get(@intFromPtr(current_target))) |list| {
|
||||
try self.dispatchPhase(list, current_target, event, was_handled, false);
|
||||
if (event._stop_propagation) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_target: *EventTarget, event: *Event, was_handled: *bool, comptime capture_only: ?bool) !void {
|
||||
const page = self.page;
|
||||
const typ = event._type_string;
|
||||
|
||||
// Track dispatch depth for deferred removal
|
||||
self.dispatch_depth += 1;
|
||||
defer {
|
||||
const dispatch_depth = self.dispatch_depth;
|
||||
// Only destroy deferred listeners when we exit the outermost dispatch
|
||||
if (dispatch_depth == 1) {
|
||||
for (self.deferred_removals.items) |removal| {
|
||||
removal.list.remove(&removal.listener.node);
|
||||
self.listener_pool.destroy(removal.listener);
|
||||
}
|
||||
self.deferred_removals.clearRetainingCapacity();
|
||||
} else {
|
||||
self.dispatch_depth = dispatch_depth - 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Use the last listener in the list as sentinel - listeners added during dispatch will be after it
|
||||
const last_node = list.last orelse return;
|
||||
const last_listener: *Listener = @alignCast(@fieldParentPtr("node", last_node));
|
||||
|
||||
// Iterate through the list, stopping after we've encountered the last_listener
|
||||
var node = list.first;
|
||||
var is_done = false;
|
||||
while (node) |n| {
|
||||
if (is_done) {
|
||||
break;
|
||||
}
|
||||
|
||||
const listener: *Listener = @alignCast(@fieldParentPtr("node", n));
|
||||
is_done = (listener == last_listener);
|
||||
node = n.next;
|
||||
|
||||
// Skip non-matching listeners
|
||||
if (!listener.typ.eql(typ)) {
|
||||
continue;
|
||||
}
|
||||
if (comptime capture_only) |capture| {
|
||||
if (listener.capture != capture) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip removed listeners
|
||||
if (listener.removed) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If the listener has an aborted signal, remove it and skip
|
||||
if (listener.signal) |signal| {
|
||||
if (signal.getAborted()) {
|
||||
self.removeListener(list, listener);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove "once" listeners BEFORE calling them so nested dispatches don't see them
|
||||
if (listener.once) {
|
||||
self.removeListener(list, listener);
|
||||
}
|
||||
|
||||
was_handled.* = true;
|
||||
event._current_target = current_target;
|
||||
|
||||
// Compute adjusted target for shadow DOM retargeting (only if needed)
|
||||
const original_target = event._target;
|
||||
if (event._needs_retargeting) {
|
||||
event._target = getAdjustedTarget(original_target, current_target);
|
||||
}
|
||||
|
||||
switch (listener.function) {
|
||||
.value => |value| try value.callWithThis(void, current_target, .{event}),
|
||||
.string => |string| {
|
||||
const str = try page.call_arena.dupeZ(u8, string.str());
|
||||
try self.page.js.eval(str, null);
|
||||
},
|
||||
.object => |obj| {
|
||||
if (try obj.getFunction("handleEvent")) |handleEvent| {
|
||||
try handleEvent.callWithThis(void, obj, .{event});
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
// Restore original target (only if we changed it)
|
||||
if (event._needs_retargeting) {
|
||||
event._target = original_target;
|
||||
}
|
||||
|
||||
if (event._stop_immediate_propagation) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Non-Node dispatching (XHR, Window without propagation)
|
||||
fn dispatchAll(self: *EventManager, list: *std.DoublyLinkedList, current_target: *EventTarget, event: *Event, was_handled: *bool) !void {
|
||||
return self.dispatchPhase(list, current_target, event, was_handled, null);
|
||||
}
|
||||
|
||||
fn removeListener(self: *EventManager, list: *std.DoublyLinkedList, listener: *Listener) void {
|
||||
// If we're in a dispatch, defer removal to avoid invalidating iteration
|
||||
if (self.dispatch_depth > 0) {
|
||||
listener.removed = true;
|
||||
self.deferred_removals.append(self.arena, .{ .list = list, .listener = listener }) catch unreachable;
|
||||
} else {
|
||||
// Outside dispatch, remove immediately
|
||||
list.remove(&listener.node);
|
||||
self.listener_pool.destroy(listener);
|
||||
}
|
||||
}
|
||||
|
||||
fn findListener(list: *const std.DoublyLinkedList, typ: []const u8, callback: Callback, capture: bool) ?*Listener {
|
||||
var node = list.first;
|
||||
while (node) |n| {
|
||||
node = n.next;
|
||||
const listener: *Listener = @alignCast(@fieldParentPtr("node", n));
|
||||
const matches = switch (callback) {
|
||||
.object => |obj| listener.function.eqlObject(obj),
|
||||
.function => |func| listener.function.eqlFunction(func),
|
||||
};
|
||||
if (!matches) {
|
||||
continue;
|
||||
}
|
||||
if (listener.capture != capture) {
|
||||
continue;
|
||||
}
|
||||
if (!listener.typ.eqlSlice(typ)) {
|
||||
continue;
|
||||
}
|
||||
return listener;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const Listener = struct {
|
||||
typ: String,
|
||||
once: bool,
|
||||
capture: bool,
|
||||
passive: bool,
|
||||
function: Function,
|
||||
signal: ?*@import("webapi/AbortSignal.zig") = null,
|
||||
node: std.DoublyLinkedList.Node,
|
||||
removed: bool = false,
|
||||
};
|
||||
|
||||
const Function = union(enum) {
|
||||
value: js.Function,
|
||||
string: String,
|
||||
object: js.Object,
|
||||
|
||||
fn eqlFunction(self: Function, func: js.Function) bool {
|
||||
return switch (self) {
|
||||
.value => |v| return v.id == func.id,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn eqlObject(self: Function, obj: js.Object) bool {
|
||||
return switch (self) {
|
||||
.object => |o| return o.getId() == obj.getId(),
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Computes the adjusted target for shadow DOM event retargeting
|
||||
// Returns the lowest shadow-including ancestor of original_target that is
|
||||
// also an ancestor-or-self of current_target
|
||||
fn getAdjustedTarget(original_target: ?*EventTarget, current_target: *EventTarget) ?*EventTarget {
|
||||
const ShadowRoot = @import("webapi/ShadowRoot.zig");
|
||||
|
||||
const orig_node = switch ((original_target orelse return null)._type) {
|
||||
.node => |n| n,
|
||||
else => return original_target,
|
||||
};
|
||||
const curr_node = switch (current_target._type) {
|
||||
.node => |n| n,
|
||||
else => return original_target,
|
||||
};
|
||||
|
||||
// Walk up from original target, checking if we can reach current target
|
||||
var node: ?*Node = orig_node;
|
||||
while (node) |n| {
|
||||
// Check if current_target is an ancestor of n (or n itself)
|
||||
if (isAncestorOrSelf(curr_node, n)) {
|
||||
return n.asEventTarget();
|
||||
}
|
||||
|
||||
// Cross shadow boundary if needed
|
||||
if (n.is(ShadowRoot)) |shadow| {
|
||||
node = shadow._host.asNode();
|
||||
continue;
|
||||
}
|
||||
|
||||
node = n._parent;
|
||||
}
|
||||
|
||||
return original_target;
|
||||
}
|
||||
|
||||
// Check if ancestor is an ancestor of (or the same as) node
|
||||
// WITHOUT crossing shadow boundaries (just regular DOM tree)
|
||||
fn isAncestorOrSelf(ancestor: *Node, node: *Node) bool {
|
||||
if (ancestor == node) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var current: ?*Node = node._parent;
|
||||
while (current) |n| {
|
||||
if (n == ancestor) {
|
||||
return true;
|
||||
}
|
||||
current = n._parent;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
488
src/browser/Factory.zig
Normal file
488
src/browser/Factory.zig
Normal file
@@ -0,0 +1,488 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const assert = std.debug.assert;
|
||||
const builtin = @import("builtin");
|
||||
const reflect = @import("reflect.zig");
|
||||
const IS_DEBUG = builtin.mode == .Debug;
|
||||
|
||||
const log = @import("../log.zig");
|
||||
const String = @import("../string.zig").String;
|
||||
|
||||
const SlabAllocator = @import("../slab.zig").SlabAllocator;
|
||||
|
||||
const Page = @import("Page.zig");
|
||||
const Node = @import("webapi/Node.zig");
|
||||
const Event = @import("webapi/Event.zig");
|
||||
const UIEvent = @import("webapi/event/UIEvent.zig");
|
||||
const Element = @import("webapi/Element.zig");
|
||||
const Document = @import("webapi/Document.zig");
|
||||
const EventTarget = @import("webapi/EventTarget.zig");
|
||||
const XMLHttpRequestEventTarget = @import("webapi/net/XMLHttpRequestEventTarget.zig");
|
||||
const Blob = @import("webapi/Blob.zig");
|
||||
const AbstractRange = @import("webapi/AbstractRange.zig");
|
||||
|
||||
const Factory = @This();
|
||||
_page: *Page,
|
||||
_slab: SlabAllocator,
|
||||
|
||||
fn PrototypeChain(comptime types: []const type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
memory: []u8,
|
||||
|
||||
fn totalSize() usize {
|
||||
var size: usize = 0;
|
||||
for (types) |T| {
|
||||
size = std.mem.alignForward(usize, size, @alignOf(T));
|
||||
size += @sizeOf(T);
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
fn maxAlign() std.mem.Alignment {
|
||||
var alignment: std.mem.Alignment = .@"1";
|
||||
|
||||
for (types) |T| {
|
||||
alignment = std.mem.Alignment.max(alignment, std.mem.Alignment.of(T));
|
||||
}
|
||||
|
||||
return alignment;
|
||||
}
|
||||
|
||||
fn getType(comptime index: usize) type {
|
||||
return types[index];
|
||||
}
|
||||
|
||||
fn allocate(allocator: std.mem.Allocator) !Self {
|
||||
const size = comptime Self.totalSize();
|
||||
const alignment = comptime Self.maxAlign();
|
||||
|
||||
const memory = try allocator.alignedAlloc(u8, alignment, size);
|
||||
return .{ .memory = memory };
|
||||
}
|
||||
|
||||
fn get(self: *const Self, comptime index: usize) *getType(index) {
|
||||
var offset: usize = 0;
|
||||
inline for (types, 0..) |T, i| {
|
||||
offset = std.mem.alignForward(usize, offset, @alignOf(T));
|
||||
|
||||
if (i == index) {
|
||||
return @as(*T, @ptrCast(@alignCast(self.memory.ptr + offset)));
|
||||
}
|
||||
offset += @sizeOf(T);
|
||||
}
|
||||
unreachable;
|
||||
}
|
||||
|
||||
fn set(self: *const Self, comptime index: usize, value: getType(index)) void {
|
||||
const ptr = self.get(index);
|
||||
ptr.* = value;
|
||||
}
|
||||
|
||||
fn setRoot(self: *const Self, comptime T: type) void {
|
||||
const ptr = self.get(0);
|
||||
ptr.* = .{ ._type = unionInit(T, self.get(1)) };
|
||||
}
|
||||
|
||||
fn setMiddle(self: *const Self, comptime index: usize, comptime T: type) void {
|
||||
assert(index >= 1);
|
||||
assert(index < types.len);
|
||||
|
||||
const ptr = self.get(index);
|
||||
ptr.* = .{ ._proto = self.get(index - 1), ._type = unionInit(T, self.get(index + 1)) };
|
||||
}
|
||||
|
||||
fn setMiddleWithValue(self: *const Self, comptime index: usize, comptime T: type, value: anytype) void {
|
||||
assert(index >= 1);
|
||||
|
||||
const ptr = self.get(index);
|
||||
ptr.* = .{ ._proto = self.get(index - 1), ._type = unionInit(T, value) };
|
||||
}
|
||||
|
||||
fn setLeaf(self: *const Self, comptime index: usize, value: anytype) void {
|
||||
assert(index >= 1);
|
||||
|
||||
const ptr = self.get(index);
|
||||
ptr.* = value;
|
||||
ptr._proto = self.get(index - 1);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn AutoPrototypeChain(comptime types: []const type) type {
|
||||
return struct {
|
||||
fn create(allocator: std.mem.Allocator, leaf_value: anytype) !*@TypeOf(leaf_value) {
|
||||
const chain = try PrototypeChain(types).allocate(allocator);
|
||||
|
||||
const RootType = types[0];
|
||||
chain.setRoot(RootType.Type);
|
||||
|
||||
inline for (1..types.len - 1) |i| {
|
||||
const MiddleType = types[i];
|
||||
chain.setMiddle(i, MiddleType.Type);
|
||||
}
|
||||
|
||||
chain.setLeaf(types.len - 1, leaf_value);
|
||||
return chain.get(types.len - 1);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn init(page: *Page) Factory {
|
||||
return .{
|
||||
._page = page,
|
||||
._slab = SlabAllocator.init(page.arena, 128),
|
||||
};
|
||||
}
|
||||
|
||||
// this is a root object
|
||||
pub fn eventTarget(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
const chain = try PrototypeChain(
|
||||
&.{ EventTarget, @TypeOf(child) },
|
||||
).allocate(allocator);
|
||||
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = .{
|
||||
._type = unionInit(EventTarget.Type, chain.get(1)),
|
||||
};
|
||||
chain.setLeaf(1, child);
|
||||
|
||||
return chain.get(1);
|
||||
}
|
||||
|
||||
fn eventInit(typ: []const u8, value: anytype, page: *Page) !Event {
|
||||
// Round to 2ms for privacy (browsers do this)
|
||||
const raw_timestamp = @import("../datetime.zig").milliTimestamp(.monotonic);
|
||||
const time_stamp = (raw_timestamp / 2) * 2;
|
||||
|
||||
return .{
|
||||
._type = unionInit(Event.Type, value),
|
||||
._type_string = try String.init(page.arena, typ, .{}),
|
||||
._time_stamp = time_stamp,
|
||||
};
|
||||
}
|
||||
|
||||
// this is a root object
|
||||
pub fn event(self: *Factory, typ: []const u8, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, @TypeOf(child) },
|
||||
).allocate(allocator);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try eventInit(typ, chain.get(1), self._page);
|
||||
chain.setLeaf(1, child);
|
||||
|
||||
return chain.get(1);
|
||||
}
|
||||
|
||||
pub fn uiEvent(self: *Factory, typ: []const u8, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, UIEvent, @TypeOf(child) },
|
||||
).allocate(allocator);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try eventInit(typ, chain.get(1), self._page);
|
||||
chain.setMiddle(1, UIEvent.Type);
|
||||
chain.setLeaf(2, child);
|
||||
|
||||
return chain.get(2);
|
||||
}
|
||||
|
||||
pub fn blob(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
|
||||
// Special case: Blob has slice and mime fields, so we need manual setup
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Blob, @TypeOf(child) },
|
||||
).allocate(allocator);
|
||||
|
||||
const blob_ptr = chain.get(0);
|
||||
blob_ptr.* = .{
|
||||
._type = unionInit(Blob.Type, chain.get(1)),
|
||||
._slice = "",
|
||||
._mime = "",
|
||||
};
|
||||
chain.setLeaf(1, child);
|
||||
|
||||
return chain.get(1);
|
||||
}
|
||||
|
||||
pub fn abstractRange(self: *Factory, child: anytype, page: *Page) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
const chain = try PrototypeChain(&.{ AbstractRange, @TypeOf(child) }).allocate(allocator);
|
||||
|
||||
const doc = page.document.asNode();
|
||||
chain.set(0, AbstractRange{
|
||||
._type = unionInit(AbstractRange.Type, chain.get(1)),
|
||||
._end_offset = 0,
|
||||
._start_offset = 0,
|
||||
._end_container = doc,
|
||||
._start_container = doc,
|
||||
});
|
||||
chain.setLeaf(1, child);
|
||||
return chain.get(1);
|
||||
}
|
||||
|
||||
pub fn node(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
return try AutoPrototypeChain(
|
||||
&.{ EventTarget, Node, @TypeOf(child) },
|
||||
).create(allocator, child);
|
||||
}
|
||||
|
||||
pub fn document(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
return try AutoPrototypeChain(
|
||||
&.{ EventTarget, Node, Document, @TypeOf(child) },
|
||||
).create(allocator, child);
|
||||
}
|
||||
|
||||
pub fn documentFragment(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
return try AutoPrototypeChain(
|
||||
&.{ EventTarget, Node, Node.DocumentFragment, @TypeOf(child) },
|
||||
).create(allocator, child);
|
||||
}
|
||||
|
||||
pub fn element(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
return try AutoPrototypeChain(
|
||||
&.{ EventTarget, Node, Element, @TypeOf(child) },
|
||||
).create(allocator, child);
|
||||
}
|
||||
|
||||
pub fn htmlElement(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
return try AutoPrototypeChain(
|
||||
&.{ EventTarget, Node, Element, Element.Html, @TypeOf(child) },
|
||||
).create(allocator, child);
|
||||
}
|
||||
|
||||
pub fn htmlMediaElement(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
return try AutoPrototypeChain(
|
||||
&.{ EventTarget, Node, Element, Element.Html, Element.Html.Media, @TypeOf(child) },
|
||||
).create(allocator, child);
|
||||
}
|
||||
|
||||
pub fn svgElement(self: *Factory, tag_name: []const u8, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
const ChildT = @TypeOf(child);
|
||||
|
||||
if (ChildT == Element.Svg) {
|
||||
return self.element(child);
|
||||
}
|
||||
|
||||
const chain = try PrototypeChain(
|
||||
&.{ EventTarget, Node, Element, Element.Svg, ChildT },
|
||||
).allocate(allocator);
|
||||
|
||||
chain.setRoot(EventTarget.Type);
|
||||
chain.setMiddle(1, Node.Type);
|
||||
chain.setMiddle(2, Element.Type);
|
||||
|
||||
// will never allocate, can't fail
|
||||
const tag_name_str = String.init(self._page.arena, tag_name, .{}) catch unreachable;
|
||||
|
||||
// Manually set Element.Svg with the tag_name
|
||||
chain.set(3, .{
|
||||
._proto = chain.get(2),
|
||||
._tag_name = tag_name_str,
|
||||
._type = unionInit(Element.Svg.Type, chain.get(4)),
|
||||
});
|
||||
|
||||
chain.setLeaf(4, child);
|
||||
return chain.get(4);
|
||||
}
|
||||
|
||||
pub fn xhrEventTarget(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
|
||||
return try AutoPrototypeChain(
|
||||
&.{ EventTarget, XMLHttpRequestEventTarget, @TypeOf(child) },
|
||||
).create(allocator, child);
|
||||
}
|
||||
|
||||
pub fn textTrackCue(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
const TextTrackCue = @import("webapi/media/TextTrackCue.zig");
|
||||
|
||||
return try AutoPrototypeChain(
|
||||
&.{ EventTarget, TextTrackCue, @TypeOf(child) },
|
||||
).create(allocator, child);
|
||||
}
|
||||
|
||||
fn hasChainRoot(comptime T: type) bool {
|
||||
// Check if this is a root
|
||||
if (@hasDecl(T, "_prototype_root")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If no _proto field, we're at the top but not a recognized root
|
||||
if (!@hasField(T, "_proto")) return false;
|
||||
|
||||
// Get the _proto field's type and recurse
|
||||
const fields = @typeInfo(T).@"struct".fields;
|
||||
inline for (fields) |field| {
|
||||
if (std.mem.eql(u8, field.name, "_proto")) {
|
||||
const ProtoType = reflect.Struct(field.type);
|
||||
return hasChainRoot(ProtoType);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
fn isChainType(comptime T: type) bool {
|
||||
if (@hasField(T, "_proto")) return false;
|
||||
return comptime hasChainRoot(T);
|
||||
}
|
||||
|
||||
pub fn destroy(self: *Factory, value: anytype) void {
|
||||
const S = reflect.Struct(@TypeOf(value));
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
// We should always destroy from the leaf down.
|
||||
if (@hasDecl(S, "_prototype_root")) {
|
||||
// A Event{._type == .generic} (or any other similar types)
|
||||
// _should_ be destoyed directly. The _type = .generic is a pseudo
|
||||
// child
|
||||
if (S != Event or value._type != .generic) {
|
||||
log.fatal(.bug, "factory.destroy.event", .{ .type = @typeName(S) });
|
||||
unreachable;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (comptime isChainType(S)) {
|
||||
self.destroyChain(value, true, 0, std.mem.Alignment.@"1");
|
||||
} else {
|
||||
self.destroyStandalone(value);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn destroyStandalone(self: *Factory, value: anytype) void {
|
||||
const S = reflect.Struct(@TypeOf(value));
|
||||
assert(!@hasDecl(S, "_prototype_root"));
|
||||
|
||||
const allocator = self._slab.allocator();
|
||||
|
||||
if (@hasDecl(S, "deinit")) {
|
||||
// And it has a deinit, we'll call it
|
||||
switch (@typeInfo(@TypeOf(S.deinit)).@"fn".params.len) {
|
||||
1 => value.deinit(),
|
||||
2 => value.deinit(self._page),
|
||||
else => @compileLog(@typeName(S) ++ " has an invalid deinit function"),
|
||||
}
|
||||
}
|
||||
|
||||
allocator.destroy(value);
|
||||
}
|
||||
|
||||
fn destroyChain(
|
||||
self: *Factory,
|
||||
value: anytype,
|
||||
comptime first: bool,
|
||||
old_size: usize,
|
||||
old_align: std.mem.Alignment,
|
||||
) void {
|
||||
const S = reflect.Struct(@TypeOf(value));
|
||||
const allocator = self._slab.allocator();
|
||||
|
||||
// aligns the old size to the alignment of this element
|
||||
const current_size = std.mem.alignForward(usize, old_size, @alignOf(S));
|
||||
const alignment = std.mem.Alignment.fromByteUnits(@alignOf(S));
|
||||
|
||||
const new_align = std.mem.Alignment.max(old_align, alignment);
|
||||
const new_size = current_size + @sizeOf(S);
|
||||
|
||||
// This is initially called from a deinit. We don't want to call that
|
||||
// same deinit. So when this is the first time destroyChain is called
|
||||
// we don't call deinit (because we're in that deinit)
|
||||
if (!comptime first) {
|
||||
// But if it isn't the first time
|
||||
if (@hasDecl(S, "deinit")) {
|
||||
// And it has a deinit, we'll call it
|
||||
switch (@typeInfo(@TypeOf(S.deinit)).@"fn".params.len) {
|
||||
1 => value.deinit(),
|
||||
2 => value.deinit(self._page),
|
||||
else => @compileLog(@typeName(S) ++ " has an invalid deinit function"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (@hasField(S, "_proto")) {
|
||||
self.destroyChain(value._proto, false, new_size, new_align);
|
||||
} else if (@hasDecl(S, "JsApi")) {
|
||||
// Doesn't have a _proto, but has a JsApi.
|
||||
if (self._page.js.removeTaggedMapping(@intFromPtr(value))) |tagged| {
|
||||
allocator.destroy(tagged);
|
||||
}
|
||||
} else {
|
||||
// no proto so this is the head of the chain.
|
||||
// we use this as the ptr to the start of the chain.
|
||||
// and we have summed up the length.
|
||||
assert(@hasDecl(S, "_prototype_root"));
|
||||
|
||||
const memory_ptr: [*]const u8 = @ptrCast(value);
|
||||
const len = std.mem.alignForward(usize, new_size, new_align.toByteUnits());
|
||||
allocator.free(memory_ptr[0..len]);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn createT(self: *Factory, comptime T: type) !*T {
|
||||
const allocator = self._slab.allocator();
|
||||
return try allocator.create(T);
|
||||
}
|
||||
|
||||
pub fn create(self: *Factory, value: anytype) !*@TypeOf(value) {
|
||||
const ptr = try self.createT(@TypeOf(value));
|
||||
ptr.* = value;
|
||||
return ptr;
|
||||
}
|
||||
|
||||
fn unionInit(comptime T: type, value: anytype) T {
|
||||
const V = @TypeOf(value);
|
||||
const field_name = comptime unionFieldName(T, V);
|
||||
return @unionInit(T, field_name, value);
|
||||
}
|
||||
|
||||
// There can be friction between comptime and runtime. Comptime has to
|
||||
// account for all possible types, even if some runtime flow makes certain
|
||||
// cases impossible. At runtime, we always call `unionFieldName` with the
|
||||
// correct struct or pointer type. But at comptime time, `unionFieldName`
|
||||
// is called with both variants (S and *S). So we use reflect.Struct().
|
||||
// This only works because we never have a union with a field S and another
|
||||
// field *S.
|
||||
fn unionFieldName(comptime T: type, comptime V: type) []const u8 {
|
||||
inline for (@typeInfo(T).@"union".fields) |field| {
|
||||
if (reflect.Struct(field.type) == reflect.Struct(V)) {
|
||||
return field.name;
|
||||
}
|
||||
}
|
||||
@compileError(@typeName(V) ++ " is not a valid type for " ++ @typeName(T) ++ ".type");
|
||||
}
|
||||
530
src/browser/Mime.zig
Normal file
530
src/browser/Mime.zig
Normal file
@@ -0,0 +1,530 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
const Mime = @This();
|
||||
content_type: ContentType,
|
||||
params: []const u8 = "",
|
||||
// IANA defines max. charset value length as 40.
|
||||
// We keep 41 for null-termination since HTML parser expects in this format.
|
||||
charset: [41]u8 = default_charset,
|
||||
charset_len: usize = 5,
|
||||
|
||||
/// String "UTF-8" continued by null characters.
|
||||
pub const default_charset = .{ 'U', 'T', 'F', '-', '8' } ++ .{0} ** 36;
|
||||
|
||||
/// Mime with unknown Content-Type, empty params and empty charset.
|
||||
pub const unknown = Mime{ .content_type = .{ .unknown = {} } };
|
||||
|
||||
pub const ContentTypeEnum = enum {
|
||||
text_xml,
|
||||
text_html,
|
||||
text_javascript,
|
||||
text_plain,
|
||||
text_css,
|
||||
application_json,
|
||||
unknown,
|
||||
other,
|
||||
};
|
||||
|
||||
pub const ContentType = union(ContentTypeEnum) {
|
||||
text_xml: void,
|
||||
text_html: void,
|
||||
text_javascript: void,
|
||||
text_plain: void,
|
||||
text_css: void,
|
||||
application_json: void,
|
||||
unknown: void,
|
||||
other: struct { type: []const u8, sub_type: []const u8 },
|
||||
};
|
||||
|
||||
pub fn contentTypeString(mime: *const Mime) []const u8 {
|
||||
return switch (mime.content_type) {
|
||||
.text_xml => "text/xml",
|
||||
.text_html => "text/html",
|
||||
.text_javascript => "application/javascript",
|
||||
.text_plain => "text/plain",
|
||||
.text_css => "text/css",
|
||||
.application_json => "application/json",
|
||||
else => "",
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns the null-terminated charset value.
|
||||
pub fn charsetStringZ(mime: *const Mime) [:0]const u8 {
|
||||
return mime.charset[0..mime.charset_len :0];
|
||||
}
|
||||
|
||||
pub fn charsetString(mime: *const Mime) []const u8 {
|
||||
return mime.charset[0..mime.charset_len];
|
||||
}
|
||||
|
||||
/// Removes quotes of value if quotes are given.
|
||||
///
|
||||
/// Currently we don't validate the charset.
|
||||
/// See section 2.3 Naming Requirements:
|
||||
/// https://datatracker.ietf.org/doc/rfc2978/
|
||||
fn parseCharset(value: []const u8) error{ CharsetTooBig, Invalid }![]const u8 {
|
||||
// Cannot be larger than 40.
|
||||
// https://datatracker.ietf.org/doc/rfc2978/
|
||||
if (value.len > 40) return error.CharsetTooBig;
|
||||
|
||||
// If the first char is a quote, look for a pair.
|
||||
if (value[0] == '"') {
|
||||
if (value.len < 3 or value[value.len - 1] != '"') {
|
||||
return error.Invalid;
|
||||
}
|
||||
|
||||
return value[1 .. value.len - 1];
|
||||
}
|
||||
|
||||
// No quotes.
|
||||
return value;
|
||||
}
|
||||
|
||||
pub fn parse(input: []u8) !Mime {
|
||||
if (input.len > 255) {
|
||||
return error.TooBig;
|
||||
}
|
||||
|
||||
// Zig's trim API is broken. The return type is always `[]const u8`,
|
||||
// even if the input type is `[]u8`. @constCast is safe here.
|
||||
var normalized = @constCast(std.mem.trim(u8, input, &std.ascii.whitespace));
|
||||
_ = std.ascii.lowerString(normalized, normalized);
|
||||
|
||||
const content_type, const type_len = try parseContentType(normalized);
|
||||
if (type_len >= normalized.len) {
|
||||
return .{ .content_type = content_type };
|
||||
}
|
||||
|
||||
const params = trimLeft(normalized[type_len..]);
|
||||
|
||||
var charset: [41]u8 = undefined;
|
||||
var charset_len: usize = undefined;
|
||||
|
||||
var it = std.mem.splitScalar(u8, params, ';');
|
||||
while (it.next()) |attr| {
|
||||
const i = std.mem.indexOfScalarPos(u8, attr, 0, '=') orelse return error.Invalid;
|
||||
const name = trimLeft(attr[0..i]);
|
||||
|
||||
const value = trimRight(attr[i + 1 ..]);
|
||||
if (value.len == 0) {
|
||||
return error.Invalid;
|
||||
}
|
||||
|
||||
const attribute_name = std.meta.stringToEnum(enum {
|
||||
charset,
|
||||
}, name) orelse continue;
|
||||
|
||||
switch (attribute_name) {
|
||||
.charset => {
|
||||
if (value.len == 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
const attribute_value = try parseCharset(value);
|
||||
@memcpy(charset[0..attribute_value.len], attribute_value);
|
||||
// Null-terminate right after attribute value.
|
||||
charset[attribute_value.len] = 0;
|
||||
charset_len = attribute_value.len;
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return .{
|
||||
.params = params,
|
||||
.charset = charset,
|
||||
.charset_len = charset_len,
|
||||
.content_type = content_type,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn sniff(body: []const u8) ?Mime {
|
||||
// 0x0C is form feed
|
||||
const content = std.mem.trimLeft(u8, body, &.{ ' ', '\t', '\n', '\r', 0x0C });
|
||||
if (content.len == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (content[0] != '<') {
|
||||
if (std.mem.startsWith(u8, content, &.{ 0xEF, 0xBB, 0xBF })) {
|
||||
// UTF-8 BOM
|
||||
return .{ .content_type = .{ .text_plain = {} } };
|
||||
}
|
||||
if (std.mem.startsWith(u8, content, &.{ 0xFE, 0xFF })) {
|
||||
// UTF-16 big-endian BOM
|
||||
return .{ .content_type = .{ .text_plain = {} } };
|
||||
}
|
||||
if (std.mem.startsWith(u8, content, &.{ 0xFF, 0xFE })) {
|
||||
// UTF-16 little-endian BOM
|
||||
return .{ .content_type = .{ .text_plain = {} } };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// The longest prefix we have is "<!DOCTYPE HTML ", 15 bytes. If we're
|
||||
// here, we already know content[0] == '<', so we can skip that. So 14
|
||||
// bytes.
|
||||
|
||||
// +1 because we don't need the leading '<'
|
||||
var buf: [14]u8 = undefined;
|
||||
|
||||
const stripped = content[1..];
|
||||
const prefix_len = @min(stripped.len, buf.len);
|
||||
const prefix = std.ascii.lowerString(&buf, stripped[0..prefix_len]);
|
||||
|
||||
// we already know it starts with a <
|
||||
const known_prefixes = [_]struct { []const u8, ContentType }{
|
||||
.{ "!doctype html", .{ .text_html = {} } },
|
||||
.{ "html", .{ .text_html = {} } },
|
||||
.{ "script", .{ .text_html = {} } },
|
||||
.{ "iframe", .{ .text_html = {} } },
|
||||
.{ "h1", .{ .text_html = {} } },
|
||||
.{ "div", .{ .text_html = {} } },
|
||||
.{ "font", .{ .text_html = {} } },
|
||||
.{ "table", .{ .text_html = {} } },
|
||||
.{ "a", .{ .text_html = {} } },
|
||||
.{ "style", .{ .text_html = {} } },
|
||||
.{ "title", .{ .text_html = {} } },
|
||||
.{ "b", .{ .text_html = {} } },
|
||||
.{ "body", .{ .text_html = {} } },
|
||||
.{ "br", .{ .text_html = {} } },
|
||||
.{ "p", .{ .text_html = {} } },
|
||||
.{ "!--", .{ .text_html = {} } },
|
||||
.{ "xml", .{ .text_xml = {} } },
|
||||
};
|
||||
inline for (known_prefixes) |kp| {
|
||||
const known_prefix = kp.@"0";
|
||||
if (std.mem.startsWith(u8, prefix, known_prefix) and prefix.len > known_prefix.len) {
|
||||
const next = prefix[known_prefix.len];
|
||||
// a "tag-terminating-byte"
|
||||
if (next == ' ' or next == '>') {
|
||||
return .{ .content_type = kp.@"1" };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
pub fn isHTML(self: *const Mime) bool {
|
||||
return self.content_type == .text_html;
|
||||
}
|
||||
|
||||
// we expect value to be lowercase
|
||||
fn parseContentType(value: []const u8) !struct { ContentType, usize } {
|
||||
const end = std.mem.indexOfScalarPos(u8, value, 0, ';') orelse value.len;
|
||||
const type_name = trimRight(value[0..end]);
|
||||
const attribute_start = end + 1;
|
||||
|
||||
if (std.meta.stringToEnum(enum {
|
||||
@"text/xml",
|
||||
@"text/html",
|
||||
@"text/css",
|
||||
@"text/plain",
|
||||
|
||||
@"text/javascript",
|
||||
@"application/javascript",
|
||||
@"application/x-javascript",
|
||||
|
||||
@"application/json",
|
||||
}, type_name)) |known_type| {
|
||||
const ct: ContentType = switch (known_type) {
|
||||
.@"text/xml" => .{ .text_xml = {} },
|
||||
.@"text/html" => .{ .text_html = {} },
|
||||
.@"text/javascript", .@"application/javascript", .@"application/x-javascript" => .{ .text_javascript = {} },
|
||||
.@"text/plain" => .{ .text_plain = {} },
|
||||
.@"text/css" => .{ .text_css = {} },
|
||||
.@"application/json" => .{ .application_json = {} },
|
||||
};
|
||||
return .{ ct, attribute_start };
|
||||
}
|
||||
|
||||
const separator = std.mem.indexOfScalarPos(u8, type_name, 0, '/') orelse return error.Invalid;
|
||||
|
||||
const main_type = value[0..separator];
|
||||
const sub_type = trimRight(value[separator + 1 .. end]);
|
||||
|
||||
if (main_type.len == 0 or validType(main_type) == false) {
|
||||
return error.Invalid;
|
||||
}
|
||||
if (sub_type.len == 0 or validType(sub_type) == false) {
|
||||
return error.Invalid;
|
||||
}
|
||||
|
||||
return .{ .{ .other = .{
|
||||
.type = main_type,
|
||||
.sub_type = sub_type,
|
||||
} }, attribute_start };
|
||||
}
|
||||
|
||||
const VALID_CODEPOINTS = blk: {
|
||||
var v: [256]bool = undefined;
|
||||
for (0..256) |i| {
|
||||
v[i] = std.ascii.isAlphanumeric(i);
|
||||
}
|
||||
for ("!#$%&\\*+-.^'_`|~") |b| {
|
||||
v[b] = true;
|
||||
}
|
||||
break :blk v;
|
||||
};
|
||||
|
||||
fn validType(value: []const u8) bool {
|
||||
for (value) |b| {
|
||||
if (VALID_CODEPOINTS[b] == false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
fn trimLeft(s: []const u8) []const u8 {
|
||||
return std.mem.trimLeft(u8, s, &std.ascii.whitespace);
|
||||
}
|
||||
|
||||
fn trimRight(s: []const u8) []const u8 {
|
||||
return std.mem.trimRight(u8, s, &std.ascii.whitespace);
|
||||
}
|
||||
|
||||
const testing = @import("../testing.zig");
|
||||
test "Mime: invalid" {
|
||||
defer testing.reset();
|
||||
|
||||
const invalids = [_][]const u8{
|
||||
"",
|
||||
"text",
|
||||
"text /html",
|
||||
"text/ html",
|
||||
"text / html",
|
||||
"text/html other",
|
||||
"text/html; x",
|
||||
"text/html; x=",
|
||||
"text/html; x= ",
|
||||
"text/html; = ",
|
||||
"text/html;=",
|
||||
"text/html; charset=\"\"",
|
||||
"text/html; charset=\"",
|
||||
"text/html; charset=\"\\",
|
||||
};
|
||||
|
||||
for (invalids) |invalid| {
|
||||
const mutable_input = try testing.arena_allocator.dupe(u8, invalid);
|
||||
try testing.expectError(error.Invalid, Mime.parse(mutable_input));
|
||||
}
|
||||
}
|
||||
|
||||
test "Mime: parse common" {
|
||||
defer testing.reset();
|
||||
|
||||
try expect(.{ .content_type = .{ .text_xml = {} } }, "text/xml");
|
||||
try expect(.{ .content_type = .{ .text_html = {} } }, "text/html");
|
||||
try expect(.{ .content_type = .{ .text_plain = {} } }, "text/plain");
|
||||
|
||||
try expect(.{ .content_type = .{ .text_xml = {} } }, "text/xml;");
|
||||
try expect(.{ .content_type = .{ .text_html = {} } }, "text/html;");
|
||||
try expect(.{ .content_type = .{ .text_plain = {} } }, "text/plain;");
|
||||
|
||||
try expect(.{ .content_type = .{ .text_xml = {} } }, " \ttext/xml");
|
||||
try expect(.{ .content_type = .{ .text_html = {} } }, "text/html ");
|
||||
try expect(.{ .content_type = .{ .text_plain = {} } }, "text/plain \t\t");
|
||||
|
||||
try expect(.{ .content_type = .{ .text_xml = {} } }, "TEXT/xml");
|
||||
try expect(.{ .content_type = .{ .text_html = {} } }, "text/Html");
|
||||
try expect(.{ .content_type = .{ .text_plain = {} } }, "TEXT/PLAIN");
|
||||
|
||||
try expect(.{ .content_type = .{ .text_xml = {} } }, " TeXT/xml");
|
||||
try expect(.{ .content_type = .{ .text_html = {} } }, "teXt/HtML ;");
|
||||
try expect(.{ .content_type = .{ .text_plain = {} } }, "tExT/PlAiN;");
|
||||
|
||||
try expect(.{ .content_type = .{ .text_javascript = {} } }, "text/javascript");
|
||||
try expect(.{ .content_type = .{ .text_javascript = {} } }, "Application/JavaScript");
|
||||
try expect(.{ .content_type = .{ .text_javascript = {} } }, "application/x-javascript");
|
||||
|
||||
try expect(.{ .content_type = .{ .application_json = {} } }, "application/json");
|
||||
try expect(.{ .content_type = .{ .text_css = {} } }, "text/css");
|
||||
}
|
||||
|
||||
test "Mime: parse uncommon" {
|
||||
defer testing.reset();
|
||||
|
||||
const text_csv = Expectation{
|
||||
.content_type = .{ .other = .{ .type = "text", .sub_type = "csv" } },
|
||||
};
|
||||
try expect(text_csv, "text/csv");
|
||||
try expect(text_csv, "text/csv;");
|
||||
try expect(text_csv, " text/csv\t ");
|
||||
try expect(text_csv, " text/csv\t ;");
|
||||
|
||||
try expect(
|
||||
.{ .content_type = .{ .other = .{ .type = "text", .sub_type = "csv" } } },
|
||||
"Text/CSV",
|
||||
);
|
||||
}
|
||||
|
||||
test "Mime: parse charset" {
|
||||
defer testing.reset();
|
||||
|
||||
try expect(.{
|
||||
.content_type = .{ .text_xml = {} },
|
||||
.charset = "utf-8",
|
||||
.params = "charset=utf-8",
|
||||
}, "text/xml; charset=utf-8");
|
||||
|
||||
try expect(.{
|
||||
.content_type = .{ .text_xml = {} },
|
||||
.charset = "utf-8",
|
||||
.params = "charset=\"utf-8\"",
|
||||
}, "text/xml;charset=\"UTF-8\"");
|
||||
|
||||
try expect(.{
|
||||
.content_type = .{ .text_html = {} },
|
||||
.charset = "iso-8859-1",
|
||||
.params = "charset=\"iso-8859-1\"",
|
||||
}, "text/html; charset=\"iso-8859-1\"");
|
||||
|
||||
try expect(.{
|
||||
.content_type = .{ .text_html = {} },
|
||||
.charset = "iso-8859-1",
|
||||
.params = "charset=\"iso-8859-1\"",
|
||||
}, "text/html; charset=\"ISO-8859-1\"");
|
||||
|
||||
try expect(.{
|
||||
.content_type = .{ .text_xml = {} },
|
||||
.charset = "custom-non-standard-charset-value",
|
||||
.params = "charset=\"custom-non-standard-charset-value\"",
|
||||
}, "text/xml;charset=\"custom-non-standard-charset-value\"");
|
||||
}
|
||||
|
||||
test "Mime: isHTML" {
|
||||
defer testing.reset();
|
||||
|
||||
const assert = struct {
|
||||
fn assert(expected: bool, input: []const u8) !void {
|
||||
const mutable_input = try testing.arena_allocator.dupe(u8, input);
|
||||
var mime = try Mime.parse(mutable_input);
|
||||
try testing.expectEqual(expected, mime.isHTML());
|
||||
}
|
||||
}.assert;
|
||||
try assert(true, "text/html");
|
||||
try assert(true, "text/html;");
|
||||
try assert(true, "text/html; charset=utf-8");
|
||||
try assert(false, "text/htm"); // htm not html
|
||||
try assert(false, "text/plain");
|
||||
try assert(false, "over/9000");
|
||||
}
|
||||
|
||||
test "Mime: sniff" {
|
||||
try testing.expectEqual(null, Mime.sniff(""));
|
||||
try testing.expectEqual(null, Mime.sniff("<htm"));
|
||||
try testing.expectEqual(null, Mime.sniff("<html!"));
|
||||
try testing.expectEqual(null, Mime.sniff("<a_"));
|
||||
try testing.expectEqual(null, Mime.sniff("<!doctype html"));
|
||||
try testing.expectEqual(null, Mime.sniff("<!doctype html>"));
|
||||
try testing.expectEqual(null, Mime.sniff("\n <!doctype html>"));
|
||||
try testing.expectEqual(null, Mime.sniff("\n \t <font/>"));
|
||||
|
||||
const expectHTML = struct {
|
||||
fn expect(input: []const u8) !void {
|
||||
try testing.expectEqual(.text_html, std.meta.activeTag(Mime.sniff(input).?.content_type));
|
||||
}
|
||||
}.expect;
|
||||
|
||||
try expectHTML("<!doctype html ");
|
||||
try expectHTML("\n \t <!DOCTYPE HTML ");
|
||||
|
||||
try expectHTML("<html ");
|
||||
try expectHTML("\n \t <HtmL> even more stufff");
|
||||
|
||||
try expectHTML("<script>");
|
||||
try expectHTML("\n \t <SCRIpt >alert(document.cookies)</script>");
|
||||
|
||||
try expectHTML("<iframe>");
|
||||
try expectHTML(" \t <ifRAME >");
|
||||
|
||||
try expectHTML("<h1>");
|
||||
try expectHTML(" <H1>");
|
||||
|
||||
try expectHTML("<div>");
|
||||
try expectHTML("\n\r\r <DiV>");
|
||||
|
||||
try expectHTML("<font>");
|
||||
try expectHTML(" <fonT>");
|
||||
|
||||
try expectHTML("<table>");
|
||||
try expectHTML("\t\t<TAblE>");
|
||||
|
||||
try expectHTML("<a>");
|
||||
try expectHTML("\n\n<A>");
|
||||
|
||||
try expectHTML("<style>");
|
||||
try expectHTML(" \n\t <STyLE>");
|
||||
|
||||
try expectHTML("<title>");
|
||||
try expectHTML(" \n\t <TITLE>");
|
||||
|
||||
try expectHTML("<b>");
|
||||
try expectHTML(" \n\t <B>");
|
||||
|
||||
try expectHTML("<body>");
|
||||
try expectHTML(" \n\t <BODY>");
|
||||
|
||||
try expectHTML("<br>");
|
||||
try expectHTML(" \n\t <BR>");
|
||||
|
||||
try expectHTML("<p>");
|
||||
try expectHTML(" \n\t <P>");
|
||||
|
||||
try expectHTML("<!-->");
|
||||
try expectHTML(" \n\t <!-->");
|
||||
}
|
||||
|
||||
const Expectation = struct {
|
||||
content_type: Mime.ContentType,
|
||||
params: []const u8 = "",
|
||||
charset: ?[]const u8 = null,
|
||||
};
|
||||
|
||||
fn expect(expected: Expectation, input: []const u8) !void {
|
||||
const mutable_input = try testing.arena_allocator.dupe(u8, input);
|
||||
|
||||
const actual = try Mime.parse(mutable_input);
|
||||
try testing.expectEqual(
|
||||
std.meta.activeTag(expected.content_type),
|
||||
std.meta.activeTag(actual.content_type),
|
||||
);
|
||||
|
||||
switch (expected.content_type) {
|
||||
.other => |e| {
|
||||
const a = actual.content_type.other;
|
||||
try testing.expectEqual(e.type, a.type);
|
||||
try testing.expectEqual(e.sub_type, a.sub_type);
|
||||
},
|
||||
else => {}, // already asserted above
|
||||
}
|
||||
|
||||
try testing.expectEqual(expected.params, actual.params);
|
||||
|
||||
if (expected.charset) |ec| {
|
||||
// We remove the null characters for testing purposes here.
|
||||
try testing.expectEqual(ec, actual.charsetString());
|
||||
} else {
|
||||
const m: Mime = .unknown;
|
||||
try testing.expectEqual(m.charsetStringZ(), actual.charsetStringZ());
|
||||
}
|
||||
}
|
||||
2970
src/browser/Page.zig
Normal file
2970
src/browser/Page.zig
Normal file
File diff suppressed because it is too large
Load Diff
114
src/browser/Scheduler.zig
Normal file
114
src/browser/Scheduler.zig
Normal file
@@ -0,0 +1,114 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const log = @import("../log.zig");
|
||||
const milliTimestamp = @import("../datetime.zig").milliTimestamp;
|
||||
|
||||
const IS_DEBUG = builtin.mode == .Debug;
|
||||
|
||||
const Queue = std.PriorityQueue(Task, void, struct {
|
||||
fn compare(_: void, a: Task, b: Task) std.math.Order {
|
||||
const time_order = std.math.order(a.run_at, b.run_at);
|
||||
if (time_order != .eq) return time_order;
|
||||
// Break ties with sequence number to maintain FIFO order
|
||||
return std.math.order(a.sequence, b.sequence);
|
||||
}
|
||||
}.compare);
|
||||
|
||||
const Scheduler = @This();
|
||||
|
||||
_sequence: u64,
|
||||
low_priority: Queue,
|
||||
high_priority: Queue,
|
||||
|
||||
pub fn init(allocator: std.mem.Allocator) Scheduler {
|
||||
return .{
|
||||
._sequence = 0,
|
||||
.low_priority = Queue.init(allocator, {}),
|
||||
.high_priority = Queue.init(allocator, {}),
|
||||
};
|
||||
}
|
||||
|
||||
const AddOpts = struct {
|
||||
name: []const u8 = "",
|
||||
low_priority: bool = false,
|
||||
};
|
||||
pub fn add(self: *Scheduler, ctx: *anyopaque, cb: Callback, run_in_ms: u32, opts: AddOpts) !void {
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.scheduler, "scheduler.add", .{ .name = opts.name, .run_in_ms = run_in_ms, .low_priority = opts.low_priority });
|
||||
}
|
||||
var queue = if (opts.low_priority) &self.low_priority else &self.high_priority;
|
||||
const seq = self._sequence + 1;
|
||||
self._sequence = seq;
|
||||
return queue.add(.{
|
||||
.ctx = ctx,
|
||||
.callback = cb,
|
||||
.sequence = seq,
|
||||
.name = opts.name,
|
||||
.run_at = milliTimestamp(.monotonic) + run_in_ms,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn run(self: *Scheduler) !?u64 {
|
||||
_ = try self.runQueue(&self.low_priority);
|
||||
return self.runQueue(&self.high_priority);
|
||||
}
|
||||
|
||||
fn runQueue(self: *Scheduler, queue: *Queue) !?u64 {
|
||||
if (queue.count() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const now = milliTimestamp(.monotonic);
|
||||
|
||||
while (queue.peek()) |*task_| {
|
||||
if (task_.run_at > now) {
|
||||
return @intCast(task_.run_at - now);
|
||||
}
|
||||
var task = queue.remove();
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.scheduler, "scheduler.runTask", .{ .name = task.name });
|
||||
}
|
||||
|
||||
const repeat_in_ms = task.callback(task.ctx) catch |err| {
|
||||
log.warn(.scheduler, "task.callback", .{ .name = task.name, .err = err });
|
||||
continue;
|
||||
};
|
||||
|
||||
if (repeat_in_ms) |ms| {
|
||||
// Task cannot be repeated immediately, and they should know that
|
||||
std.debug.assert(ms != 0);
|
||||
task.run_at = now + ms;
|
||||
try self.low_priority.add(task);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const Task = struct {
|
||||
run_at: u64,
|
||||
sequence: u64,
|
||||
ctx: *anyopaque,
|
||||
name: []const u8,
|
||||
callback: Callback,
|
||||
};
|
||||
|
||||
const Callback = *const fn (ctx: *anyopaque) anyerror!?u32;
|
||||
1028
src/browser/ScriptManager.zig
Normal file
1028
src/browser/ScriptManager.zig
Normal file
File diff suppressed because it is too large
Load Diff
176
src/browser/Session.zig
Normal file
176
src/browser/Session.zig
Normal file
@@ -0,0 +1,176 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
const log = @import("../log.zig");
|
||||
|
||||
const js = @import("js/js.zig");
|
||||
const storage = @import("webapi/storage/storage.zig");
|
||||
const Navigation = @import("webapi/navigation/Navigation.zig");
|
||||
const History = @import("webapi/History.zig");
|
||||
|
||||
const Page = @import("Page.zig");
|
||||
const Browser = @import("Browser.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
// Session is like a browser's tab.
|
||||
// It owns the js env and the loader for all the pages of the session.
|
||||
// You can create successively multiple pages for a session, but you must
|
||||
// deinit a page before running another one.
|
||||
const Session = @This();
|
||||
|
||||
browser: *Browser,
|
||||
|
||||
// Used to create our Inspector and in the BrowserContext.
|
||||
arena: Allocator,
|
||||
|
||||
// The page's arena is unsuitable for data that has to existing while
|
||||
// navigating from one page to another. For example, if we're clicking
|
||||
// on an HREF, the URL exists in the original page (where the click
|
||||
// originated) but also has to exist in the new page.
|
||||
// While we could use the Session's arena, this could accumulate a lot of
|
||||
// memory if we do many navigation events. The `transfer_arena` is meant to
|
||||
// bridge the gap: existing long enough to store any data needed to end one
|
||||
// page and start another.
|
||||
transfer_arena: Allocator,
|
||||
|
||||
executor: js.ExecutionWorld,
|
||||
cookie_jar: storage.Cookie.Jar,
|
||||
storage_shed: storage.Shed,
|
||||
|
||||
history: History,
|
||||
navigation: Navigation,
|
||||
|
||||
page: ?*Page = null,
|
||||
|
||||
pub fn init(self: *Session, browser: *Browser) !void {
|
||||
var executor = try browser.env.newExecutionWorld();
|
||||
errdefer executor.deinit();
|
||||
|
||||
const allocator = browser.app.allocator;
|
||||
const session_allocator = browser.session_arena.allocator();
|
||||
|
||||
self.* = .{
|
||||
.browser = browser,
|
||||
.executor = executor,
|
||||
.storage_shed = .{},
|
||||
.arena = session_allocator,
|
||||
.cookie_jar = storage.Cookie.Jar.init(allocator),
|
||||
.navigation = .{},
|
||||
.history = .{},
|
||||
.transfer_arena = browser.transfer_arena.allocator(),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Session) void {
|
||||
if (self.page != null) {
|
||||
self.removePage();
|
||||
}
|
||||
self.cookie_jar.deinit();
|
||||
self.storage_shed.deinit(self.browser.app.allocator);
|
||||
self.executor.deinit();
|
||||
}
|
||||
|
||||
// NOTE: the caller is not the owner of the returned value,
|
||||
// the pointer on Page is just returned as a convenience
|
||||
pub fn createPage(self: *Session) !*Page {
|
||||
std.debug.assert(self.page == null);
|
||||
|
||||
const page_arena = &self.browser.page_arena;
|
||||
_ = page_arena.reset(.{ .retain_with_limit = 1 * 1024 * 1024 });
|
||||
|
||||
self.page = try Page.init(page_arena.allocator(), self.browser.call_arena.allocator(), self);
|
||||
const page = self.page.?;
|
||||
|
||||
// Creates a new NavigationEventTarget for this page.
|
||||
try self.navigation.onNewPage(page);
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.browser, "create page", .{});
|
||||
}
|
||||
// start JS env
|
||||
// Inform CDP the main page has been created such that additional context for other Worlds can be created as well
|
||||
self.browser.notification.dispatch(.page_created, page);
|
||||
|
||||
return page;
|
||||
}
|
||||
|
||||
pub fn removePage(self: *Session) void {
|
||||
// Inform CDP the page is going to be removed, allowing other worlds to remove themselves before the main one
|
||||
self.browser.notification.dispatch(.page_remove, .{});
|
||||
|
||||
std.debug.assert(self.page != null);
|
||||
|
||||
self.page.?.deinit();
|
||||
self.page = null;
|
||||
|
||||
self.navigation.onRemovePage();
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.browser, "remove page", .{});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn currentPage(self: *Session) ?*Page {
|
||||
return self.page orelse return null;
|
||||
}
|
||||
|
||||
pub const WaitResult = enum {
|
||||
done,
|
||||
no_page,
|
||||
cdp_socket,
|
||||
navigate,
|
||||
};
|
||||
|
||||
pub fn wait(self: *Session, wait_ms: u32) WaitResult {
|
||||
while (true) {
|
||||
const page = self.page orelse return .no_page;
|
||||
switch (page.wait(wait_ms)) {
|
||||
.navigate => self.processScheduledNavigation() catch return .done,
|
||||
else => |result| return result,
|
||||
}
|
||||
// if we've successfull navigated, we'll give the new page another
|
||||
// page.wait(wait_ms)
|
||||
}
|
||||
}
|
||||
|
||||
fn processScheduledNavigation(self: *Session) !void {
|
||||
const qn = self.page.?._queued_navigation.?;
|
||||
defer _ = self.browser.transfer_arena.reset(.{ .retain_with_limit = 8 * 1024 });
|
||||
|
||||
// This was already aborted on the page, but it would be pretty
|
||||
// bad if old requests went to the new page, so let's make double sure
|
||||
self.browser.http_client.abort();
|
||||
self.removePage();
|
||||
|
||||
const page = self.createPage() catch |err| {
|
||||
log.err(.browser, "queued navigation page error", .{
|
||||
.err = err,
|
||||
.url = qn.url,
|
||||
});
|
||||
return err;
|
||||
};
|
||||
|
||||
page.navigate(qn.url, qn.opts) catch |err| {
|
||||
log.err(.browser, "queued navigation error", .{ .err = err, .url = qn.url });
|
||||
return err;
|
||||
};
|
||||
}
|
||||
758
src/browser/URL.zig
Normal file
758
src/browser/URL.zig
Normal file
@@ -0,0 +1,758 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const ResolveOpts = struct {
|
||||
always_dupe: bool = false,
|
||||
};
|
||||
// path is anytype, so that it can be used with both []const u8 and [:0]const u8
|
||||
pub fn resolve(allocator: Allocator, base: [:0]const u8, path: anytype, comptime opts: ResolveOpts) ![:0]const u8 {
|
||||
const PT = @TypeOf(path);
|
||||
if (base.len == 0 or isCompleteHTTPUrl(path)) {
|
||||
if (comptime opts.always_dupe or !isNullTerminated(PT)) {
|
||||
return allocator.dupeZ(u8, path);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
if (path.len == 0) {
|
||||
if (comptime opts.always_dupe) {
|
||||
return allocator.dupeZ(u8, base);
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
if (path[0] == '?') {
|
||||
const base_path_end = std.mem.indexOfAny(u8, base, "?#") orelse base.len;
|
||||
return std.mem.joinZ(allocator, "", &.{ base[0..base_path_end], path });
|
||||
}
|
||||
if (path[0] == '#') {
|
||||
const base_fragment_start = std.mem.indexOfScalar(u8, base, '#') orelse base.len;
|
||||
return std.mem.joinZ(allocator, "", &.{ base[0..base_fragment_start], path });
|
||||
}
|
||||
|
||||
if (std.mem.startsWith(u8, path, "//")) {
|
||||
// network-path reference
|
||||
const index = std.mem.indexOfScalar(u8, base, ':') orelse {
|
||||
if (comptime isNullTerminated(PT)) {
|
||||
return path;
|
||||
}
|
||||
return allocator.dupeZ(u8, path);
|
||||
};
|
||||
const protocol = base[0 .. index + 1];
|
||||
return std.mem.joinZ(allocator, "", &.{ protocol, path });
|
||||
}
|
||||
|
||||
const scheme_end = std.mem.indexOf(u8, base, "://");
|
||||
const authority_start = if (scheme_end) |end| end + 3 else 0;
|
||||
const path_start = std.mem.indexOfScalarPos(u8, base, authority_start, '/') orelse base.len;
|
||||
|
||||
if (path[0] == '/') {
|
||||
return std.mem.joinZ(allocator, "", &.{ base[0..path_start], path });
|
||||
}
|
||||
|
||||
var normalized_base: []const u8 = base[0..path_start];
|
||||
if (path_start < base.len) {
|
||||
if (std.mem.lastIndexOfScalar(u8, base[path_start + 1 ..], '/')) |pos| {
|
||||
normalized_base = base[0 .. path_start + 1 + pos];
|
||||
}
|
||||
}
|
||||
|
||||
// trailing space so that we always have space to append the null terminator
|
||||
var out = try std.mem.join(allocator, "", &.{ normalized_base, "/", path, " " });
|
||||
const end = out.len - 1;
|
||||
|
||||
const path_marker = path_start + 1;
|
||||
|
||||
// Strip out ./ and ../. This is done in-place, because doing so can
|
||||
// only ever make `out` smaller. After this, `out` cannot be freed by
|
||||
// an allocator, which is ok, because we expect allocator to be an arena.
|
||||
var in_i: usize = 0;
|
||||
var out_i: usize = 0;
|
||||
while (in_i < end) {
|
||||
if (std.mem.startsWith(u8, out[in_i..], "./")) {
|
||||
in_i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.startsWith(u8, out[in_i..], "../")) {
|
||||
std.debug.assert(out[out_i - 1] == '/');
|
||||
|
||||
if (out_i > path_marker) {
|
||||
// go back before the /
|
||||
out_i -= 2;
|
||||
while (out_i > 1 and out[out_i - 1] != '/') {
|
||||
out_i -= 1;
|
||||
}
|
||||
} else {
|
||||
// if out_i == path_marker, than we've reached the start of
|
||||
// the path. We can't ../ any more. E.g.:
|
||||
// http://www.example.com/../hello.
|
||||
// You might think that's an error, but, at least with
|
||||
// new URL('../hello', 'http://www.example.com/')
|
||||
// it just ignores the extra ../
|
||||
}
|
||||
in_i += 3;
|
||||
continue;
|
||||
}
|
||||
|
||||
out[out_i] = out[in_i];
|
||||
in_i += 1;
|
||||
out_i += 1;
|
||||
}
|
||||
|
||||
// we always have an extra space
|
||||
out[out_i] = 0;
|
||||
return out[0..out_i :0];
|
||||
}
|
||||
|
||||
fn isNullTerminated(comptime value: type) bool {
|
||||
return @typeInfo(value).pointer.sentinel_ptr != null;
|
||||
}
|
||||
|
||||
pub fn isCompleteHTTPUrl(url: []const u8) bool {
|
||||
if (url.len < 3) { // Minimum is "x://"
|
||||
return false;
|
||||
}
|
||||
|
||||
// very common case
|
||||
if (url[0] == '/') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if there's a scheme (protocol) ending with ://
|
||||
const colon_pos = std.mem.indexOfScalar(u8, url, ':') orelse return false;
|
||||
|
||||
// Check if it's followed by //
|
||||
if (colon_pos + 2 >= url.len or url[colon_pos + 1] != '/' or url[colon_pos + 2] != '/') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Validate that everything before the colon is a valid scheme
|
||||
// A scheme must start with a letter and contain only letters, digits, +, -, .
|
||||
if (colon_pos == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const scheme = url[0..colon_pos];
|
||||
if (!std.ascii.isAlphabetic(scheme[0])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (scheme[1..]) |c| {
|
||||
if (!std.ascii.isAlphanumeric(c) and c != '+' and c != '-' and c != '.') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
pub fn getUsername(raw: [:0]const u8) []const u8 {
|
||||
const user_info = getUserInfo(raw) orelse return "";
|
||||
const pos = std.mem.indexOfScalarPos(u8, user_info, 0, ':') orelse return user_info;
|
||||
return user_info[0..pos];
|
||||
}
|
||||
|
||||
pub fn getPassword(raw: [:0]const u8) []const u8 {
|
||||
const user_info = getUserInfo(raw) orelse return "";
|
||||
const pos = std.mem.indexOfScalarPos(u8, user_info, 0, ':') orelse return "";
|
||||
return user_info[pos + 1 ..];
|
||||
}
|
||||
|
||||
pub fn getPathname(raw: [:0]const u8) []const u8 {
|
||||
const protocol_end = std.mem.indexOf(u8, raw, "://") orelse 0;
|
||||
const path_start = std.mem.indexOfScalarPos(u8, raw, if (protocol_end > 0) protocol_end + 3 else 0, '/') orelse raw.len;
|
||||
|
||||
const query_or_hash_start = std.mem.indexOfAnyPos(u8, raw, path_start, "?#") orelse raw.len;
|
||||
|
||||
if (path_start >= query_or_hash_start) {
|
||||
if (std.mem.indexOf(u8, raw, "://") != null) return "/";
|
||||
return "";
|
||||
}
|
||||
|
||||
return raw[path_start..query_or_hash_start];
|
||||
}
|
||||
|
||||
pub fn getProtocol(raw: [:0]const u8) []const u8 {
|
||||
const pos = std.mem.indexOfScalarPos(u8, raw, 0, ':') orelse return "";
|
||||
return raw[0 .. pos + 1];
|
||||
}
|
||||
|
||||
pub fn isHTTPS(raw: [:0]const u8) bool {
|
||||
return std.mem.startsWith(u8, raw, "https:");
|
||||
}
|
||||
|
||||
pub fn getHostname(raw: [:0]const u8) []const u8 {
|
||||
const host = getHost(raw);
|
||||
const pos = std.mem.lastIndexOfScalar(u8, host, ':') orelse return host;
|
||||
return host[0..pos];
|
||||
}
|
||||
|
||||
pub fn getPort(raw: [:0]const u8) []const u8 {
|
||||
const host = getHost(raw);
|
||||
const pos = std.mem.lastIndexOfScalar(u8, host, ':') orelse return "";
|
||||
|
||||
if (pos + 1 >= host.len) {
|
||||
return "";
|
||||
}
|
||||
|
||||
for (host[pos + 1 ..]) |c| {
|
||||
if (c < '0' or c > '9') {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
return host[pos + 1 ..];
|
||||
}
|
||||
|
||||
pub fn getSearch(raw: [:0]const u8) []const u8 {
|
||||
const pos = std.mem.indexOfScalarPos(u8, raw, 0, '?') orelse return "";
|
||||
const query_part = raw[pos..];
|
||||
|
||||
if (std.mem.indexOfScalarPos(u8, query_part, 0, '#')) |fragment_start| {
|
||||
return query_part[0..fragment_start];
|
||||
}
|
||||
|
||||
return query_part;
|
||||
}
|
||||
|
||||
pub fn getHash(raw: [:0]const u8) []const u8 {
|
||||
const start = std.mem.indexOfScalarPos(u8, raw, 0, '#') orelse return "";
|
||||
return raw[start..];
|
||||
}
|
||||
|
||||
pub fn getOrigin(allocator: Allocator, raw: [:0]const u8) !?[]const u8 {
|
||||
const scheme_end = std.mem.indexOf(u8, raw, "://") orelse return null;
|
||||
|
||||
// Only HTTP and HTTPS schemes have origins
|
||||
const protocol = raw[0 .. scheme_end + 1];
|
||||
if (!std.mem.eql(u8, protocol, "http:") and !std.mem.eql(u8, protocol, "https:")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var authority_start = scheme_end + 3;
|
||||
const has_user_info = if (std.mem.indexOf(u8, raw[authority_start..], "@")) |pos| blk: {
|
||||
authority_start += pos + 1;
|
||||
break :blk true;
|
||||
} else false;
|
||||
|
||||
// Find end of authority (start of path/query/fragment or end of string)
|
||||
const authority_end_relative = std.mem.indexOfAny(u8, raw[authority_start..], "/?#");
|
||||
const authority_end = if (authority_end_relative) |end|
|
||||
authority_start + end
|
||||
else
|
||||
raw.len;
|
||||
|
||||
// Check for port in the host:port section
|
||||
const host_part = raw[authority_start..authority_end];
|
||||
if (std.mem.lastIndexOfScalar(u8, host_part, ':')) |colon_pos_in_host| {
|
||||
const port = host_part[colon_pos_in_host + 1 ..];
|
||||
|
||||
// Validate it's actually a port (all digits)
|
||||
for (port) |c| {
|
||||
if (c < '0' or c > '9') {
|
||||
// Not a port (probably IPv6)
|
||||
if (has_user_info) {
|
||||
// Need to allocate to exclude user info
|
||||
return try std.fmt.allocPrint(allocator, "{s}//{s}", .{ raw[0 .. scheme_end + 1], host_part });
|
||||
}
|
||||
// Can return a slice
|
||||
return raw[0..authority_end];
|
||||
}
|
||||
}
|
||||
|
||||
// Check if it's a default port that should be excluded from origin
|
||||
const is_default =
|
||||
(std.mem.eql(u8, protocol, "http:") and std.mem.eql(u8, port, "80")) or
|
||||
(std.mem.eql(u8, protocol, "https:") and std.mem.eql(u8, port, "443"));
|
||||
|
||||
if (is_default or has_user_info) {
|
||||
// Need to allocate to build origin without default port and/or user info
|
||||
const hostname = host_part[0..colon_pos_in_host];
|
||||
if (is_default) {
|
||||
return try std.fmt.allocPrint(allocator, "{s}//{s}", .{ protocol, hostname });
|
||||
} else {
|
||||
return try std.fmt.allocPrint(allocator, "{s}//{s}", .{ protocol, host_part });
|
||||
}
|
||||
}
|
||||
} else if (has_user_info) {
|
||||
// No port, but has user info - need to allocate
|
||||
return try std.fmt.allocPrint(allocator, "{s}//{s}", .{ raw[0 .. scheme_end + 1], host_part });
|
||||
}
|
||||
|
||||
// Common case: no user info, no default port - return slice (zero allocation!)
|
||||
return raw[0..authority_end];
|
||||
}
|
||||
|
||||
fn getUserInfo(raw: [:0]const u8) ?[]const u8 {
|
||||
const scheme_end = std.mem.indexOf(u8, raw, "://") orelse return null;
|
||||
const authority_start = scheme_end + 3;
|
||||
|
||||
const pos = std.mem.indexOfScalar(u8, raw[authority_start..], '@') orelse return null;
|
||||
const path_start = std.mem.indexOfScalarPos(u8, raw, authority_start, '/') orelse raw.len;
|
||||
|
||||
const full_pos = authority_start + pos;
|
||||
if (full_pos < path_start) {
|
||||
return raw[authority_start..full_pos];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
pub fn getHost(raw: [:0]const u8) []const u8 {
|
||||
const scheme_end = std.mem.indexOf(u8, raw, "://") orelse return "";
|
||||
|
||||
var authority_start = scheme_end + 3;
|
||||
if (std.mem.indexOf(u8, raw[authority_start..], "@")) |pos| {
|
||||
authority_start += pos + 1;
|
||||
}
|
||||
|
||||
const authority = raw[authority_start..];
|
||||
const path_start = std.mem.indexOfAny(u8, authority, "/?#") orelse return authority;
|
||||
return authority[0..path_start];
|
||||
}
|
||||
|
||||
// Returns true if these two URLs point to the same document.
|
||||
pub fn eqlDocument(first: [:0]const u8, second: [:0]const u8) bool {
|
||||
// First '#' signifies the start of the fragment.
|
||||
const first_hash_index = std.mem.indexOfScalar(u8, first, '#') orelse first.len;
|
||||
const second_hash_index = std.mem.indexOfScalar(u8, second, '#') orelse second.len;
|
||||
return std.mem.eql(u8, first[0..first_hash_index], second[0..second_hash_index]);
|
||||
}
|
||||
|
||||
// Helper function to build a URL from components
|
||||
pub fn buildUrl(
|
||||
allocator: Allocator,
|
||||
protocol: []const u8,
|
||||
host: []const u8,
|
||||
pathname: []const u8,
|
||||
search: []const u8,
|
||||
hash: []const u8,
|
||||
) ![:0]const u8 {
|
||||
return std.fmt.allocPrintSentinel(allocator, "{s}//{s}{s}{s}{s}", .{
|
||||
protocol,
|
||||
host,
|
||||
pathname,
|
||||
search,
|
||||
hash,
|
||||
}, 0);
|
||||
}
|
||||
|
||||
pub fn setProtocol(current: [:0]const u8, value: []const u8, allocator: Allocator) ![:0]const u8 {
|
||||
const host = getHost(current);
|
||||
const pathname = getPathname(current);
|
||||
const search = getSearch(current);
|
||||
const hash = getHash(current);
|
||||
|
||||
// Add : suffix if not present
|
||||
const protocol = if (value.len > 0 and value[value.len - 1] != ':')
|
||||
try std.fmt.allocPrint(allocator, "{s}:", .{value})
|
||||
else
|
||||
value;
|
||||
|
||||
return buildUrl(allocator, protocol, host, pathname, search, hash);
|
||||
}
|
||||
|
||||
pub fn setHost(current: [:0]const u8, value: []const u8, allocator: Allocator) ![:0]const u8 {
|
||||
const protocol = getProtocol(current);
|
||||
const pathname = getPathname(current);
|
||||
const search = getSearch(current);
|
||||
const hash = getHash(current);
|
||||
|
||||
// Check if the host includes a port
|
||||
const colon_pos = std.mem.lastIndexOfScalar(u8, value, ':');
|
||||
const clean_host = if (colon_pos) |pos| blk: {
|
||||
const port_str = value[pos + 1 ..];
|
||||
// Remove default ports
|
||||
if (std.mem.eql(u8, protocol, "https:") and std.mem.eql(u8, port_str, "443")) {
|
||||
break :blk value[0..pos];
|
||||
}
|
||||
if (std.mem.eql(u8, protocol, "http:") and std.mem.eql(u8, port_str, "80")) {
|
||||
break :blk value[0..pos];
|
||||
}
|
||||
break :blk value;
|
||||
} else value;
|
||||
|
||||
return buildUrl(allocator, protocol, clean_host, pathname, search, hash);
|
||||
}
|
||||
|
||||
pub fn setHostname(current: [:0]const u8, value: []const u8, allocator: Allocator) ![:0]const u8 {
|
||||
const current_port = getPort(current);
|
||||
const new_host = if (current_port.len > 0)
|
||||
try std.fmt.allocPrint(allocator, "{s}:{s}", .{ value, current_port })
|
||||
else
|
||||
value;
|
||||
|
||||
return setHost(current, new_host, allocator);
|
||||
}
|
||||
|
||||
pub fn setPort(current: [:0]const u8, value: ?[]const u8, allocator: Allocator) ![:0]const u8 {
|
||||
const hostname = getHostname(current);
|
||||
const protocol = getProtocol(current);
|
||||
|
||||
// Handle null or default ports
|
||||
const new_host = if (value) |port_str| blk: {
|
||||
if (port_str.len == 0) {
|
||||
break :blk hostname;
|
||||
}
|
||||
// Check if this is a default port for the protocol
|
||||
if (std.mem.eql(u8, protocol, "https:") and std.mem.eql(u8, port_str, "443")) {
|
||||
break :blk hostname;
|
||||
}
|
||||
if (std.mem.eql(u8, protocol, "http:") and std.mem.eql(u8, port_str, "80")) {
|
||||
break :blk hostname;
|
||||
}
|
||||
break :blk try std.fmt.allocPrint(allocator, "{s}:{s}", .{ hostname, port_str });
|
||||
} else hostname;
|
||||
|
||||
return setHost(current, new_host, allocator);
|
||||
}
|
||||
|
||||
pub fn setPathname(current: [:0]const u8, value: []const u8, allocator: Allocator) ![:0]const u8 {
|
||||
const protocol = getProtocol(current);
|
||||
const host = getHost(current);
|
||||
const search = getSearch(current);
|
||||
const hash = getHash(current);
|
||||
|
||||
// Add / prefix if not present and value is not empty
|
||||
const pathname = if (value.len > 0 and value[0] != '/')
|
||||
try std.fmt.allocPrint(allocator, "/{s}", .{value})
|
||||
else
|
||||
value;
|
||||
|
||||
return buildUrl(allocator, protocol, host, pathname, search, hash);
|
||||
}
|
||||
|
||||
pub fn setSearch(current: [:0]const u8, value: []const u8, allocator: Allocator) ![:0]const u8 {
|
||||
const protocol = getProtocol(current);
|
||||
const host = getHost(current);
|
||||
const pathname = getPathname(current);
|
||||
const hash = getHash(current);
|
||||
|
||||
// Add ? prefix if not present and value is not empty
|
||||
const search = if (value.len > 0 and value[0] != '?')
|
||||
try std.fmt.allocPrint(allocator, "?{s}", .{value})
|
||||
else
|
||||
value;
|
||||
|
||||
return buildUrl(allocator, protocol, host, pathname, search, hash);
|
||||
}
|
||||
|
||||
pub fn setHash(current: [:0]const u8, value: []const u8, allocator: Allocator) ![:0]const u8 {
|
||||
const protocol = getProtocol(current);
|
||||
const host = getHost(current);
|
||||
const pathname = getPathname(current);
|
||||
const search = getSearch(current);
|
||||
|
||||
// Add # prefix if not present and value is not empty
|
||||
const hash = if (value.len > 0 and value[0] != '#')
|
||||
try std.fmt.allocPrint(allocator, "#{s}", .{value})
|
||||
else
|
||||
value;
|
||||
|
||||
return buildUrl(allocator, protocol, host, pathname, search, hash);
|
||||
}
|
||||
|
||||
pub fn concatQueryString(arena: Allocator, url: []const u8, query_string: []const u8) ![:0]const u8 {
|
||||
if (query_string.len == 0) {
|
||||
return arena.dupeZ(u8, url);
|
||||
}
|
||||
|
||||
var buf: std.ArrayList(u8) = .empty;
|
||||
|
||||
// the most space well need is the url + ('?' or '&') + the query_string + null terminator
|
||||
try buf.ensureTotalCapacity(arena, url.len + 2 + query_string.len);
|
||||
buf.appendSliceAssumeCapacity(url);
|
||||
|
||||
if (std.mem.indexOfScalar(u8, url, '?')) |index| {
|
||||
const last_index = url.len - 1;
|
||||
if (index != last_index and url[last_index] != '&') {
|
||||
buf.appendAssumeCapacity('&');
|
||||
}
|
||||
} else {
|
||||
buf.appendAssumeCapacity('?');
|
||||
}
|
||||
buf.appendSliceAssumeCapacity(query_string);
|
||||
buf.appendAssumeCapacity(0);
|
||||
return buf.items[0 .. buf.items.len - 1 :0];
|
||||
}
|
||||
|
||||
const testing = @import("../testing.zig");
|
||||
test "URL: isCompleteHTTPUrl" {
|
||||
try testing.expectEqual(true, isCompleteHTTPUrl("http://example.com/about"));
|
||||
try testing.expectEqual(true, isCompleteHTTPUrl("HttP://example.com/about"));
|
||||
try testing.expectEqual(true, isCompleteHTTPUrl("httpS://example.com/about"));
|
||||
try testing.expectEqual(true, isCompleteHTTPUrl("HTTPs://example.com/about"));
|
||||
try testing.expectEqual(true, isCompleteHTTPUrl("ftp://example.com/about"));
|
||||
|
||||
try testing.expectEqual(false, isCompleteHTTPUrl("/example.com"));
|
||||
try testing.expectEqual(false, isCompleteHTTPUrl("../../about"));
|
||||
try testing.expectEqual(false, isCompleteHTTPUrl("about"));
|
||||
}
|
||||
|
||||
test "URL: resolve regression (#1093)" {
|
||||
defer testing.reset();
|
||||
|
||||
const Case = struct {
|
||||
base: [:0]const u8,
|
||||
path: [:0]const u8,
|
||||
expected: [:0]const u8,
|
||||
};
|
||||
|
||||
const cases = [_]Case{
|
||||
.{
|
||||
.base = "https://alas.aws.amazon.com/alas2.html",
|
||||
.path = "../static/bootstrap.min.css",
|
||||
.expected = "https://alas.aws.amazon.com/static/bootstrap.min.css",
|
||||
},
|
||||
};
|
||||
|
||||
for (cases) |case| {
|
||||
const result = try resolve(testing.arena_allocator, case.base, case.path, .{});
|
||||
try testing.expectString(case.expected, result);
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: resolve" {
|
||||
defer testing.reset();
|
||||
|
||||
const Case = struct {
|
||||
base: [:0]const u8,
|
||||
path: [:0]const u8,
|
||||
expected: [:0]const u8,
|
||||
};
|
||||
|
||||
const cases = [_]Case{
|
||||
.{
|
||||
.base = "https://example/xyz/abc/123",
|
||||
.path = "something.js",
|
||||
.expected = "https://example/xyz/abc/something.js",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/xyz/abc/123",
|
||||
.path = "/something.js",
|
||||
.expected = "https://example/something.js",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/",
|
||||
.path = "something.js",
|
||||
.expected = "https://example/something.js",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/",
|
||||
.path = "/something.js",
|
||||
.expected = "https://example/something.js",
|
||||
},
|
||||
.{
|
||||
.base = "https://example",
|
||||
.path = "something.js",
|
||||
.expected = "https://example/something.js",
|
||||
},
|
||||
.{
|
||||
.base = "https://example",
|
||||
.path = "abc/something.js",
|
||||
.expected = "https://example/abc/something.js",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/nested",
|
||||
.path = "abc/something.js",
|
||||
.expected = "https://example/abc/something.js",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/nested/",
|
||||
.path = "abc/something.js",
|
||||
.expected = "https://example/nested/abc/something.js",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/nested/",
|
||||
.path = "/abc/something.js",
|
||||
.expected = "https://example/abc/something.js",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/nested/",
|
||||
.path = "http://www.github.com/example/",
|
||||
.expected = "http://www.github.com/example/",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/nested/",
|
||||
.path = "",
|
||||
.expected = "https://example/nested/",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/abc/aaa",
|
||||
.path = "./hello/./world",
|
||||
.expected = "https://example/abc/hello/world",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/abc/aaa/",
|
||||
.path = "../hello",
|
||||
.expected = "https://example/abc/hello",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/abc/aaa",
|
||||
.path = "../hello",
|
||||
.expected = "https://example/hello",
|
||||
},
|
||||
.{
|
||||
.base = "https://example/abc/aaa/",
|
||||
.path = "./.././.././hello",
|
||||
.expected = "https://example/hello",
|
||||
},
|
||||
.{
|
||||
.base = "some/page",
|
||||
.path = "hello",
|
||||
.expected = "some/hello",
|
||||
},
|
||||
.{
|
||||
.base = "some/page/",
|
||||
.path = "hello",
|
||||
.expected = "some/page/hello",
|
||||
},
|
||||
.{
|
||||
.base = "some/page/other",
|
||||
.path = ".././hello",
|
||||
.expected = "some/hello",
|
||||
},
|
||||
.{
|
||||
.base = "https://www.example.com/hello/world",
|
||||
.path = "//example/about",
|
||||
.expected = "https://example/about",
|
||||
},
|
||||
.{
|
||||
.base = "http:",
|
||||
.path = "//example.com/over/9000",
|
||||
.expected = "http://example.com/over/9000",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "../hello",
|
||||
.expected = "https://example.com/hello",
|
||||
},
|
||||
.{
|
||||
.base = "https://www.example.com/hello/world/",
|
||||
.path = "../../../../example/about",
|
||||
.expected = "https://www.example.com/example/about",
|
||||
},
|
||||
};
|
||||
|
||||
for (cases) |case| {
|
||||
const result = try resolve(testing.arena_allocator, case.base, case.path, .{});
|
||||
try testing.expectString(case.expected, result);
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: eqlDocument" {
|
||||
defer testing.reset();
|
||||
{
|
||||
const url = "https://lightpanda.io/about";
|
||||
try testing.expectEqual(true, eqlDocument(url, url));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io/about";
|
||||
const url2 = "http://lightpanda.io/about";
|
||||
try testing.expectEqual(false, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io/about";
|
||||
const url2 = "https://example.com/about";
|
||||
try testing.expectEqual(false, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io:8080/about";
|
||||
const url2 = "https://lightpanda.io:9090/about";
|
||||
try testing.expectEqual(false, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io/about";
|
||||
const url2 = "https://lightpanda.io/contact";
|
||||
try testing.expectEqual(false, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io/about?foo=bar";
|
||||
const url2 = "https://lightpanda.io/about?baz=qux";
|
||||
try testing.expectEqual(false, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io/about#section1";
|
||||
const url2 = "https://lightpanda.io/about#section2";
|
||||
try testing.expectEqual(true, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io/about";
|
||||
const url2 = "https://lightpanda.io/about/";
|
||||
try testing.expectEqual(false, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io/about?foo=bar";
|
||||
const url2 = "https://lightpanda.io/about";
|
||||
try testing.expectEqual(false, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io/about";
|
||||
const url2 = "https://lightpanda.io/about?foo=bar";
|
||||
try testing.expectEqual(false, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io/about?foo=bar";
|
||||
const url2 = "https://lightpanda.io/about?foo=bar";
|
||||
try testing.expectEqual(true, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://lightpanda.io/about?";
|
||||
const url2 = "https://lightpanda.io/about";
|
||||
try testing.expectEqual(false, eqlDocument(url1, url2));
|
||||
}
|
||||
{
|
||||
const url1 = "https://duckduckgo.com/";
|
||||
const url2 = "https://duckduckgo.com/?q=lightpanda";
|
||||
try testing.expectEqual(false, eqlDocument(url1, url2));
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: concatQueryString" {
|
||||
defer testing.reset();
|
||||
const arena = testing.arena_allocator;
|
||||
|
||||
{
|
||||
const url = try concatQueryString(arena, "https://www.lightpanda.io/", "");
|
||||
try testing.expectEqual("https://www.lightpanda.io/", url);
|
||||
}
|
||||
|
||||
{
|
||||
const url = try concatQueryString(arena, "https://www.lightpanda.io/index?", "");
|
||||
try testing.expectEqual("https://www.lightpanda.io/index?", url);
|
||||
}
|
||||
|
||||
{
|
||||
const url = try concatQueryString(arena, "https://www.lightpanda.io/index?", "a=b");
|
||||
try testing.expectEqual("https://www.lightpanda.io/index?a=b", url);
|
||||
}
|
||||
|
||||
{
|
||||
const url = try concatQueryString(arena, "https://www.lightpanda.io/index?1=2", "a=b");
|
||||
try testing.expectEqual("https://www.lightpanda.io/index?1=2&a=b", url);
|
||||
}
|
||||
|
||||
{
|
||||
const url = try concatQueryString(arena, "https://www.lightpanda.io/index?1=2&", "a=b");
|
||||
try testing.expectEqual("https://www.lightpanda.io/index?1=2&a=b", url);
|
||||
}
|
||||
}
|
||||
@@ -1,613 +0,0 @@
|
||||
// Copyright (C) 2023-2024 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const Types = @import("root").Types;
|
||||
|
||||
const parser = @import("netsurf");
|
||||
const Loader = @import("loader.zig").Loader;
|
||||
const Dump = @import("dump.zig");
|
||||
const Mime = @import("mime.zig");
|
||||
|
||||
const jsruntime = @import("jsruntime");
|
||||
const Loop = jsruntime.Loop;
|
||||
const Env = jsruntime.Env;
|
||||
|
||||
const apiweb = @import("../apiweb.zig");
|
||||
|
||||
const Window = @import("../html/window.zig").Window;
|
||||
const Walker = @import("../dom/walker.zig").WalkerDepthFirst;
|
||||
|
||||
const storage = @import("../storage/storage.zig");
|
||||
|
||||
const FetchResult = @import("../http/Client.zig").Client.FetchResult;
|
||||
|
||||
const UserContext = @import("../user_context.zig").UserContext;
|
||||
const HttpClient = @import("asyncio").Client;
|
||||
|
||||
const polyfill = @import("../polyfill/polyfill.zig");
|
||||
|
||||
const log = std.log.scoped(.browser);
|
||||
|
||||
// Browser is an instance of the browser.
|
||||
// You can create multiple browser instances.
|
||||
// A browser contains only one session.
|
||||
// TODO allow multiple sessions per browser.
|
||||
pub const Browser = struct {
|
||||
session: Session = undefined,
|
||||
|
||||
const uri = "about:blank";
|
||||
|
||||
pub fn init(self: *Browser, alloc: std.mem.Allocator, loop: *Loop, vm: jsruntime.VM) !void {
|
||||
// We want to ensure the caller initialised a VM, but the browser
|
||||
// doesn't use it directly...
|
||||
_ = vm;
|
||||
|
||||
try Session.init(&self.session, alloc, loop, uri);
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Browser) void {
|
||||
self.session.deinit();
|
||||
}
|
||||
|
||||
pub fn newSession(
|
||||
self: *Browser,
|
||||
alloc: std.mem.Allocator,
|
||||
loop: *jsruntime.Loop,
|
||||
) !void {
|
||||
self.session.deinit();
|
||||
try Session.init(&self.session, alloc, loop, uri);
|
||||
}
|
||||
};
|
||||
|
||||
// Session is like a browser's tab.
|
||||
// It owns the js env and the loader for all the pages of the session.
|
||||
// You can create successively multiple pages for a session, but you must
|
||||
// deinit a page before running another one.
|
||||
pub const Session = struct {
|
||||
// allocator used to init the arena.
|
||||
alloc: std.mem.Allocator,
|
||||
|
||||
// The arena is used only to bound the js env init b/c it leaks memory.
|
||||
// see https://github.com/lightpanda-io/jsruntime-lib/issues/181
|
||||
//
|
||||
// The arena is initialised with self.alloc allocator.
|
||||
// all others Session deps use directly self.alloc and not the arena.
|
||||
arena: std.heap.ArenaAllocator,
|
||||
|
||||
uri: []const u8,
|
||||
|
||||
// TODO handle proxy
|
||||
loader: Loader,
|
||||
env: Env = undefined,
|
||||
inspector: ?jsruntime.Inspector = null,
|
||||
window: Window,
|
||||
// TODO move the shed to the browser?
|
||||
storageShed: storage.Shed,
|
||||
page: ?Page = null,
|
||||
httpClient: HttpClient,
|
||||
|
||||
jstypes: [Types.len]usize = undefined,
|
||||
|
||||
fn init(self: *Session, alloc: std.mem.Allocator, loop: *Loop, uri: []const u8) !void {
|
||||
self.* = Session{
|
||||
.uri = uri,
|
||||
.alloc = alloc,
|
||||
.arena = std.heap.ArenaAllocator.init(alloc),
|
||||
.window = Window.create(null),
|
||||
.loader = Loader.init(alloc),
|
||||
.storageShed = storage.Shed.init(alloc),
|
||||
.httpClient = undefined,
|
||||
};
|
||||
|
||||
Env.init(&self.env, self.arena.allocator(), loop, null);
|
||||
self.httpClient = .{ .allocator = alloc };
|
||||
try self.env.load(&self.jstypes);
|
||||
}
|
||||
|
||||
fn deinit(self: *Session) void {
|
||||
if (self.page) |*p| p.end();
|
||||
|
||||
if (self.inspector) |inspector| {
|
||||
inspector.deinit(self.alloc);
|
||||
}
|
||||
|
||||
self.env.deinit();
|
||||
self.arena.deinit();
|
||||
|
||||
self.httpClient.deinit();
|
||||
self.loader.deinit();
|
||||
self.storageShed.deinit();
|
||||
}
|
||||
|
||||
pub fn initInspector(
|
||||
self: *Session,
|
||||
ctx: anytype,
|
||||
onResp: jsruntime.InspectorOnResponseFn,
|
||||
onEvent: jsruntime.InspectorOnEventFn,
|
||||
) !void {
|
||||
const ctx_opaque = @as(*anyopaque, @ptrCast(ctx));
|
||||
self.inspector = try jsruntime.Inspector.init(self.alloc, self.env, ctx_opaque, onResp, onEvent);
|
||||
self.env.setInspector(self.inspector.?);
|
||||
}
|
||||
|
||||
pub fn callInspector(self: *Session, msg: []const u8) void {
|
||||
if (self.inspector) |inspector| {
|
||||
inspector.send(msg, self.env);
|
||||
} else {
|
||||
@panic("No Inspector");
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: the caller is not the owner of the returned value,
|
||||
// the pointer on Page is just returned as a convenience
|
||||
pub fn createPage(self: *Session) !*Page {
|
||||
if (self.page != null) return error.SessionPageExists;
|
||||
const p: Page = undefined;
|
||||
self.page = p;
|
||||
Page.init(&self.page.?, self.alloc, self);
|
||||
return &self.page.?;
|
||||
}
|
||||
};
|
||||
|
||||
// Page navigates to an url.
|
||||
// You can navigates multiple urls with the same page, but you have to call
|
||||
// end() to stop the previous navigation before starting a new one.
|
||||
// The page handle all its memory in an arena allocator. The arena is reseted
|
||||
// when end() is called.
|
||||
pub const Page = struct {
|
||||
arena: std.heap.ArenaAllocator,
|
||||
session: *Session,
|
||||
doc: ?*parser.Document = null,
|
||||
|
||||
// handle url
|
||||
rawuri: ?[]const u8 = null,
|
||||
uri: std.Uri = undefined,
|
||||
origin: ?[]const u8 = null,
|
||||
|
||||
raw_data: ?[]const u8 = null,
|
||||
|
||||
fn init(
|
||||
self: *Page,
|
||||
alloc: std.mem.Allocator,
|
||||
session: *Session,
|
||||
) void {
|
||||
self.* = .{
|
||||
.arena = std.heap.ArenaAllocator.init(alloc),
|
||||
.session = session,
|
||||
};
|
||||
}
|
||||
|
||||
// reset js env and mem arena.
|
||||
pub fn end(self: *Page) void {
|
||||
self.session.env.stop();
|
||||
// TODO unload document: https://html.spec.whatwg.org/#unloading-documents
|
||||
|
||||
// clear netsurf memory arena.
|
||||
parser.deinit();
|
||||
|
||||
_ = self.arena.reset(.free_all);
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Page) void {
|
||||
self.arena.deinit();
|
||||
self.session.page = null;
|
||||
}
|
||||
|
||||
// dump writes the page content into the given file.
|
||||
pub fn dump(self: *Page, out: std.fs.File) !void {
|
||||
|
||||
// if no HTML document pointer available, dump the data content only.
|
||||
if (self.doc == null) {
|
||||
// no data loaded, nothing to do.
|
||||
if (self.raw_data == null) return;
|
||||
return try out.writeAll(self.raw_data.?);
|
||||
}
|
||||
|
||||
// if the page has a pointer to a document, dumps the HTML.
|
||||
try Dump.writeHTML(self.doc.?, out);
|
||||
}
|
||||
|
||||
pub fn wait(self: *Page) !void {
|
||||
|
||||
// try catch
|
||||
var try_catch: jsruntime.TryCatch = undefined;
|
||||
try_catch.init(self.session.env);
|
||||
defer try_catch.deinit();
|
||||
|
||||
self.session.env.wait() catch |err| {
|
||||
// the js env could not be started if the document wasn't an HTML.
|
||||
if (err == error.EnvNotStarted) return;
|
||||
|
||||
const alloc = self.arena.allocator();
|
||||
if (try try_catch.err(alloc, self.session.env)) |msg| {
|
||||
defer alloc.free(msg);
|
||||
log.info("wait error: {s}", .{msg});
|
||||
return;
|
||||
}
|
||||
};
|
||||
log.debug("wait: OK", .{});
|
||||
}
|
||||
|
||||
// spec reference: https://html.spec.whatwg.org/#document-lifecycle
|
||||
// - auxData: extra data forwarded to the Inspector
|
||||
// see Inspector.contextCreated
|
||||
pub fn navigate(self: *Page, uri: []const u8, auxData: ?[]const u8) !void {
|
||||
const alloc = self.arena.allocator();
|
||||
|
||||
log.debug("starting GET {s}", .{uri});
|
||||
|
||||
// own the url
|
||||
if (self.rawuri) |prev| alloc.free(prev);
|
||||
self.rawuri = try alloc.dupe(u8, uri);
|
||||
self.uri = std.Uri.parse(self.rawuri.?) catch try std.Uri.parseAfterScheme("", self.rawuri.?);
|
||||
|
||||
// prepare origin value.
|
||||
var buf = std.ArrayList(u8).init(alloc);
|
||||
defer buf.deinit();
|
||||
try self.uri.writeToStream(.{
|
||||
.scheme = true,
|
||||
.authority = true,
|
||||
}, buf.writer());
|
||||
self.origin = try buf.toOwnedSlice();
|
||||
|
||||
// TODO handle fragment in url.
|
||||
|
||||
// load the data
|
||||
var resp = try self.session.loader.get(alloc, self.uri);
|
||||
defer resp.deinit();
|
||||
|
||||
const req = resp.req;
|
||||
|
||||
log.info("GET {any} {d}", .{ self.uri, req.response.status });
|
||||
|
||||
// TODO handle redirection
|
||||
if (req.response.status != .ok) {
|
||||
log.debug("{?} {d} {s}", .{
|
||||
req.response.version,
|
||||
req.response.status,
|
||||
req.response.reason,
|
||||
// TODO log headers
|
||||
});
|
||||
return error.BadStatusCode;
|
||||
}
|
||||
|
||||
// TODO handle charset
|
||||
// https://html.spec.whatwg.org/#content-type
|
||||
var it = req.response.iterateHeaders();
|
||||
var ct: ?[]const u8 = null;
|
||||
while (true) {
|
||||
const h = it.next() orelse break;
|
||||
if (std.ascii.eqlIgnoreCase(h.name, "Content-Type")) {
|
||||
ct = try alloc.dupe(u8, h.value);
|
||||
}
|
||||
}
|
||||
if (ct == null) {
|
||||
// no content type in HTTP headers.
|
||||
// TODO try to sniff mime type from the body.
|
||||
log.info("no content-type HTTP header", .{});
|
||||
return;
|
||||
}
|
||||
defer alloc.free(ct.?);
|
||||
|
||||
log.debug("header content-type: {s}", .{ct.?});
|
||||
const mime = try Mime.parse(ct.?);
|
||||
if (mime.eql(Mime.HTML)) {
|
||||
try self.loadHTMLDoc(req.reader(), mime.charset orelse "utf-8", auxData);
|
||||
} else {
|
||||
log.info("non-HTML document: {s}", .{ct.?});
|
||||
|
||||
// save the body into the page.
|
||||
self.raw_data = try req.reader().readAllAlloc(alloc, 16 * 1024 * 1024);
|
||||
}
|
||||
}
|
||||
|
||||
// https://html.spec.whatwg.org/#read-html
|
||||
fn loadHTMLDoc(self: *Page, reader: anytype, charset: []const u8, auxData: ?[]const u8) !void {
|
||||
const alloc = self.arena.allocator();
|
||||
|
||||
// start netsurf memory arena.
|
||||
try parser.init();
|
||||
|
||||
log.debug("parse html with charset {s}", .{charset});
|
||||
|
||||
const ccharset = try alloc.dupeZ(u8, charset);
|
||||
defer alloc.free(ccharset);
|
||||
|
||||
const html_doc = try parser.documentHTMLParse(reader, ccharset);
|
||||
const doc = parser.documentHTMLToDocument(html_doc);
|
||||
|
||||
// save a document's pointer in the page.
|
||||
self.doc = doc;
|
||||
|
||||
// TODO set document.readyState to interactive
|
||||
// https://html.spec.whatwg.org/#reporting-document-loading-status
|
||||
|
||||
// inject the URL to the document including the fragment.
|
||||
try parser.documentSetDocumentURI(doc, self.rawuri orelse "about:blank");
|
||||
|
||||
// TODO set the referrer to the document.
|
||||
|
||||
self.session.window.replaceDocument(html_doc);
|
||||
self.session.window.setStorageShelf(
|
||||
try self.session.storageShed.getOrPut(self.origin orelse "null"),
|
||||
);
|
||||
|
||||
// https://html.spec.whatwg.org/#read-html
|
||||
|
||||
// start JS env
|
||||
// TODO load the js env concurrently with the HTML parsing.
|
||||
log.debug("start js env", .{});
|
||||
try self.session.env.start();
|
||||
|
||||
// load polyfills
|
||||
try polyfill.load(alloc, self.session.env);
|
||||
|
||||
// inspector
|
||||
if (self.session.inspector) |inspector| {
|
||||
inspector.contextCreated(self.session.env, "", self.origin.?, auxData);
|
||||
}
|
||||
|
||||
// replace the user context document with the new one.
|
||||
try self.session.env.setUserContext(.{
|
||||
.document = html_doc,
|
||||
.httpClient = &self.session.httpClient,
|
||||
});
|
||||
|
||||
// add global objects
|
||||
log.debug("setup global env", .{});
|
||||
try self.session.env.bindGlobal(&self.session.window);
|
||||
|
||||
// browse the DOM tree to retrieve scripts
|
||||
// TODO execute the synchronous scripts during the HTL parsing.
|
||||
// TODO fetch the script resources concurrently but execute them in the
|
||||
// declaration order for synchronous ones.
|
||||
|
||||
// sasync stores scripts which can be run asynchronously.
|
||||
// for now they are just run after the non-async one in order to
|
||||
// dispatch DOMContentLoaded the sooner as possible.
|
||||
var sasync = std.ArrayList(*parser.Element).init(alloc);
|
||||
defer sasync.deinit();
|
||||
|
||||
const root = parser.documentToNode(doc);
|
||||
const walker = Walker{};
|
||||
var next: ?*parser.Node = null;
|
||||
while (true) {
|
||||
next = try walker.get_next(root, next) orelse break;
|
||||
|
||||
// ignore non-elements nodes.
|
||||
if (try parser.nodeType(next.?) != .element) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const e = parser.nodeToElement(next.?);
|
||||
const tag = try parser.elementHTMLGetTagType(@as(*parser.ElementHTML, @ptrCast(e)));
|
||||
|
||||
// ignore non-script tags
|
||||
if (tag != .script) continue;
|
||||
|
||||
// ignore non-js script.
|
||||
// > type
|
||||
// > Attribute is not set (default), an empty string, or a JavaScript MIME
|
||||
// > type indicates that the script is a "classic script", containing
|
||||
// > JavaScript code.
|
||||
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attribute_is_not_set_default_an_empty_string_or_a_javascript_mime_type
|
||||
const stype = try parser.elementGetAttribute(e, "type");
|
||||
if (!isJS(stype)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ignore the defer attribute b/c we analyze all script
|
||||
// after the document has been parsed.
|
||||
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer
|
||||
|
||||
// TODO use fetchpriority
|
||||
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#fetchpriority
|
||||
|
||||
// > async
|
||||
// > For classic scripts, if the async attribute is present,
|
||||
// > then the classic script will be fetched in parallel to
|
||||
// > parsing and evaluated as soon as it is available.
|
||||
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#async
|
||||
if (try parser.elementGetAttribute(e, "async") != null) {
|
||||
try sasync.append(e);
|
||||
continue;
|
||||
}
|
||||
|
||||
// TODO handle for attribute
|
||||
// TODO handle event attribute
|
||||
|
||||
// TODO defer
|
||||
// > This Boolean attribute is set to indicate to a browser
|
||||
// > that the script is meant to be executed after the
|
||||
// > document has been parsed, but before firing
|
||||
// > DOMContentLoaded.
|
||||
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer
|
||||
// defer allow us to load a script w/o blocking the rest of
|
||||
// evaluations.
|
||||
|
||||
// > Scripts without async, defer or type="module"
|
||||
// > attributes, as well as inline scripts without the
|
||||
// > type="module" attribute, are fetched and executed
|
||||
// > immediately before the browser continues to parse the
|
||||
// > page.
|
||||
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#notes
|
||||
try parser.documentHTMLSetCurrentScript(html_doc, @ptrCast(e));
|
||||
self.evalScript(e) catch |err| log.warn("evaljs: {any}", .{err});
|
||||
try parser.documentHTMLSetCurrentScript(html_doc, null);
|
||||
}
|
||||
|
||||
// TODO wait for deferred scripts
|
||||
|
||||
// dispatch DOMContentLoaded before the transition to "complete",
|
||||
// at the point where all subresources apart from async script elements
|
||||
// have loaded.
|
||||
// https://html.spec.whatwg.org/#reporting-document-loading-status
|
||||
const evt = try parser.eventCreate();
|
||||
defer parser.eventDestroy(evt);
|
||||
|
||||
try parser.eventInit(evt, "DOMContentLoaded", .{ .bubbles = true, .cancelable = true });
|
||||
_ = try parser.eventTargetDispatchEvent(parser.toEventTarget(parser.DocumentHTML, html_doc), evt);
|
||||
|
||||
// eval async scripts.
|
||||
for (sasync.items) |e| {
|
||||
try parser.documentHTMLSetCurrentScript(html_doc, @ptrCast(e));
|
||||
self.evalScript(e) catch |err| log.warn("evaljs: {any}", .{err});
|
||||
try parser.documentHTMLSetCurrentScript(html_doc, null);
|
||||
}
|
||||
|
||||
// TODO wait for async scripts
|
||||
|
||||
// TODO set document.readyState to complete
|
||||
|
||||
// dispatch window.load event
|
||||
const loadevt = try parser.eventCreate();
|
||||
defer parser.eventDestroy(loadevt);
|
||||
|
||||
try parser.eventInit(loadevt, "load", .{});
|
||||
_ = try parser.eventTargetDispatchEvent(
|
||||
parser.toEventTarget(Window, &self.session.window),
|
||||
loadevt,
|
||||
);
|
||||
}
|
||||
|
||||
// evalScript evaluates the src in priority.
|
||||
// if no src is present, we evaluate the text source.
|
||||
// https://html.spec.whatwg.org/multipage/scripting.html#script-processing-model
|
||||
fn evalScript(self: *Page, e: *parser.Element) !void {
|
||||
const alloc = self.arena.allocator();
|
||||
|
||||
// https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script
|
||||
const opt_src = try parser.elementGetAttribute(e, "src");
|
||||
if (opt_src) |src| {
|
||||
log.debug("starting GET {s}", .{src});
|
||||
|
||||
self.fetchScript(src) catch |err| {
|
||||
switch (err) {
|
||||
FetchError.BadStatusCode => return err,
|
||||
|
||||
// TODO If el's result is null, then fire an event named error at
|
||||
// el, and return.
|
||||
FetchError.NoBody => return,
|
||||
|
||||
FetchError.JsErr => {}, // nothing to do here.
|
||||
else => return err,
|
||||
}
|
||||
};
|
||||
|
||||
// TODO If el's from an external file is true, then fire an event
|
||||
// named load at el.
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var try_catch: jsruntime.TryCatch = undefined;
|
||||
try_catch.init(self.session.env);
|
||||
defer try_catch.deinit();
|
||||
|
||||
const opt_text = try parser.nodeTextContent(parser.elementToNode(e));
|
||||
if (opt_text) |text| {
|
||||
// TODO handle charset attribute
|
||||
const res = self.session.env.exec(text, "") catch {
|
||||
if (try try_catch.err(alloc, self.session.env)) |msg| {
|
||||
defer alloc.free(msg);
|
||||
log.info("eval inline {s}: {s}", .{ text, msg });
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
if (builtin.mode == .Debug) {
|
||||
const msg = try res.toString(alloc, self.session.env);
|
||||
defer alloc.free(msg);
|
||||
log.debug("eval inline {s}", .{msg});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// nothing has been loaded.
|
||||
// TODO If el's result is null, then fire an event named error at
|
||||
// el, and return.
|
||||
}
|
||||
|
||||
const FetchError = error{
|
||||
BadStatusCode,
|
||||
NoBody,
|
||||
JsErr,
|
||||
};
|
||||
|
||||
// fetchScript senf a GET request to the src and execute the script
|
||||
// received.
|
||||
fn fetchScript(self: *Page, src: []const u8) !void {
|
||||
const alloc = self.arena.allocator();
|
||||
|
||||
log.debug("starting fetch script {s}", .{src});
|
||||
|
||||
var buffer: [1024]u8 = undefined;
|
||||
var b: []u8 = buffer[0..];
|
||||
const u = try std.Uri.resolve_inplace(self.uri, src, &b);
|
||||
|
||||
var fetchres = try self.session.loader.get(alloc, u);
|
||||
defer fetchres.deinit();
|
||||
|
||||
const resp = fetchres.req.response;
|
||||
|
||||
log.info("fetch script {any}: {d}", .{ u, resp.status });
|
||||
|
||||
if (resp.status != .ok) return FetchError.BadStatusCode;
|
||||
|
||||
// TODO check content-type
|
||||
const body = try fetchres.req.reader().readAllAlloc(alloc, 16 * 1024 * 1024);
|
||||
defer alloc.free(body);
|
||||
|
||||
// check no body
|
||||
if (body.len == 0) return FetchError.NoBody;
|
||||
|
||||
var try_catch: jsruntime.TryCatch = undefined;
|
||||
try_catch.init(self.session.env);
|
||||
defer try_catch.deinit();
|
||||
|
||||
const res = self.session.env.exec(body, src) catch {
|
||||
if (try try_catch.err(alloc, self.session.env)) |msg| {
|
||||
defer alloc.free(msg);
|
||||
log.info("eval remote {s}: {s}", .{ src, msg });
|
||||
}
|
||||
return FetchError.JsErr;
|
||||
};
|
||||
|
||||
if (builtin.mode == .Debug) {
|
||||
const msg = try res.toString(alloc, self.session.env);
|
||||
defer alloc.free(msg);
|
||||
log.debug("eval remote {s}: {s}", .{ src, msg });
|
||||
}
|
||||
}
|
||||
|
||||
// > type
|
||||
// > Attribute is not set (default), an empty string, or a JavaScript MIME
|
||||
// > type indicates that the script is a "classic script", containing
|
||||
// > JavaScript code.
|
||||
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attribute_is_not_set_default_an_empty_string_or_a_javascript_mime_type
|
||||
fn isJS(stype: ?[]const u8) bool {
|
||||
if (stype == null or stype.?.len == 0) return true;
|
||||
if (std.mem.eql(u8, stype.?, "application/javascript")) return true;
|
||||
if (!std.mem.eql(u8, stype.?, "module")) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
295
src/browser/css/Parser.zig
Normal file
295
src/browser/css/Parser.zig
Normal file
@@ -0,0 +1,295 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const Tokenizer = @import("Tokenizer.zig");
|
||||
|
||||
pub const Declaration = struct {
|
||||
name: []const u8,
|
||||
value: []const u8,
|
||||
important: bool,
|
||||
};
|
||||
|
||||
const TokenSpan = struct {
|
||||
token: Tokenizer.Token,
|
||||
start: usize,
|
||||
end: usize,
|
||||
};
|
||||
|
||||
const TokenStream = struct {
|
||||
tokenizer: Tokenizer,
|
||||
peeked: ?TokenSpan = null,
|
||||
|
||||
fn init(input: []const u8) TokenStream {
|
||||
return .{ .tokenizer = .{ .input = input } };
|
||||
}
|
||||
|
||||
fn nextRaw(self: *TokenStream) ?TokenSpan {
|
||||
const start = self.tokenizer.position;
|
||||
const token = self.tokenizer.next() orelse return null;
|
||||
const end = self.tokenizer.position;
|
||||
return .{ .token = token, .start = start, .end = end };
|
||||
}
|
||||
|
||||
fn next(self: *TokenStream) ?TokenSpan {
|
||||
if (self.peeked) |token| {
|
||||
self.peeked = null;
|
||||
return token;
|
||||
}
|
||||
return self.nextRaw();
|
||||
}
|
||||
|
||||
fn peek(self: *TokenStream) ?TokenSpan {
|
||||
if (self.peeked == null) {
|
||||
self.peeked = self.nextRaw();
|
||||
}
|
||||
return self.peeked;
|
||||
}
|
||||
};
|
||||
|
||||
pub fn parseDeclarationsList(input: []const u8) DeclarationsIterator {
|
||||
return DeclarationsIterator.init(input);
|
||||
}
|
||||
|
||||
pub const DeclarationsIterator = struct {
|
||||
input: []const u8,
|
||||
stream: TokenStream,
|
||||
|
||||
pub fn init(input: []const u8) DeclarationsIterator {
|
||||
return .{
|
||||
.input = input,
|
||||
.stream = TokenStream.init(input),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn next(self: *DeclarationsIterator) ?Declaration {
|
||||
while (true) {
|
||||
self.skipTriviaAndSemicolons();
|
||||
const peeked = self.stream.peek() orelse return null;
|
||||
|
||||
switch (peeked.token) {
|
||||
.at_keyword => {
|
||||
_ = self.stream.next();
|
||||
self.skipAtRule();
|
||||
},
|
||||
.ident => |name| {
|
||||
_ = self.stream.next();
|
||||
if (self.consumeDeclaration(name)) |declaration| {
|
||||
return declaration;
|
||||
}
|
||||
},
|
||||
else => {
|
||||
_ = self.stream.next();
|
||||
self.skipInvalidDeclaration();
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
fn consumeDeclaration(self: *DeclarationsIterator, name: []const u8) ?Declaration {
|
||||
self.skipTrivia();
|
||||
|
||||
const colon = self.stream.next() orelse return null;
|
||||
if (!isColon(colon.token)) {
|
||||
self.skipInvalidDeclaration();
|
||||
return null;
|
||||
}
|
||||
|
||||
const value = self.consumeValue() orelse return null;
|
||||
return .{
|
||||
.name = name,
|
||||
.value = value.value,
|
||||
.important = value.important,
|
||||
};
|
||||
}
|
||||
|
||||
const ValueResult = struct {
|
||||
value: []const u8,
|
||||
important: bool,
|
||||
};
|
||||
|
||||
fn consumeValue(self: *DeclarationsIterator) ?ValueResult {
|
||||
self.skipTrivia();
|
||||
|
||||
var depth: usize = 0;
|
||||
var start: ?usize = null;
|
||||
var last_sig: ?TokenSpan = null;
|
||||
var prev_sig: ?TokenSpan = null;
|
||||
|
||||
while (true) {
|
||||
const peeked = self.stream.peek() orelse break;
|
||||
if (isSemicolon(peeked.token) and depth == 0) {
|
||||
_ = self.stream.next();
|
||||
break;
|
||||
}
|
||||
|
||||
const span = self.stream.next() orelse break;
|
||||
if (isWhitespaceOrComment(span.token)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (start == null) start = span.start;
|
||||
prev_sig = last_sig;
|
||||
last_sig = span;
|
||||
updateDepth(span.token, &depth);
|
||||
}
|
||||
|
||||
const value_start = start orelse return null;
|
||||
const last = last_sig orelse return null;
|
||||
|
||||
var important = false;
|
||||
var end_pos = last.end;
|
||||
|
||||
if (isImportantPair(prev_sig, last)) {
|
||||
important = true;
|
||||
const bang = prev_sig orelse return null;
|
||||
if (value_start >= bang.start) return null;
|
||||
end_pos = bang.start;
|
||||
}
|
||||
|
||||
var value_slice = self.input[value_start..end_pos];
|
||||
value_slice = std.mem.trim(u8, value_slice, &std.ascii.whitespace);
|
||||
if (value_slice.len == 0) return null;
|
||||
|
||||
return .{ .value = value_slice, .important = important };
|
||||
}
|
||||
|
||||
fn skipTrivia(self: *DeclarationsIterator) void {
|
||||
while (self.stream.peek()) |peeked| {
|
||||
if (!isWhitespaceOrComment(peeked.token)) break;
|
||||
_ = self.stream.next();
|
||||
}
|
||||
}
|
||||
|
||||
fn skipTriviaAndSemicolons(self: *DeclarationsIterator) void {
|
||||
while (self.stream.peek()) |peeked| {
|
||||
if (isWhitespaceOrComment(peeked.token) or isSemicolon(peeked.token)) {
|
||||
_ = self.stream.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn skipAtRule(self: *DeclarationsIterator) void {
|
||||
var depth: usize = 0;
|
||||
var saw_block = false;
|
||||
|
||||
while (true) {
|
||||
const peeked = self.stream.peek() orelse return;
|
||||
if (!saw_block and isSemicolon(peeked.token) and depth == 0) {
|
||||
_ = self.stream.next();
|
||||
return;
|
||||
}
|
||||
|
||||
const span = self.stream.next() orelse return;
|
||||
if (isWhitespaceOrComment(span.token)) continue;
|
||||
|
||||
if (isBlockStart(span.token)) {
|
||||
depth += 1;
|
||||
saw_block = true;
|
||||
} else if (isBlockEnd(span.token)) {
|
||||
if (depth > 0) depth -= 1;
|
||||
if (saw_block and depth == 0) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn skipInvalidDeclaration(self: *DeclarationsIterator) void {
|
||||
var depth: usize = 0;
|
||||
|
||||
while (self.stream.peek()) |peeked| {
|
||||
if (isSemicolon(peeked.token) and depth == 0) {
|
||||
_ = self.stream.next();
|
||||
return;
|
||||
}
|
||||
|
||||
const span = self.stream.next() orelse return;
|
||||
if (isWhitespaceOrComment(span.token)) continue;
|
||||
updateDepth(span.token, &depth);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
fn isWhitespaceOrComment(token: Tokenizer.Token) bool {
|
||||
return switch (token) {
|
||||
.white_space, .comment => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn isSemicolon(token: Tokenizer.Token) bool {
|
||||
return switch (token) {
|
||||
.semicolon => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn isColon(token: Tokenizer.Token) bool {
|
||||
return switch (token) {
|
||||
.colon => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn isBlockStart(token: Tokenizer.Token) bool {
|
||||
return switch (token) {
|
||||
.curly_bracket_block, .square_bracket_block, .parenthesis_block, .function => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn isBlockEnd(token: Tokenizer.Token) bool {
|
||||
return switch (token) {
|
||||
.close_curly_bracket, .close_parenthesis, .close_square_bracket => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn updateDepth(token: Tokenizer.Token, depth: *usize) void {
|
||||
if (isBlockStart(token)) {
|
||||
depth.* += 1;
|
||||
return;
|
||||
}
|
||||
|
||||
if (isBlockEnd(token)) {
|
||||
if (depth.* > 0) depth.* -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn isImportantPair(prev_sig: ?TokenSpan, last_sig: TokenSpan) bool {
|
||||
if (!isIdentImportant(last_sig.token)) return false;
|
||||
const prev = prev_sig orelse return false;
|
||||
return isBang(prev.token);
|
||||
}
|
||||
|
||||
fn isIdentImportant(token: Tokenizer.Token) bool {
|
||||
return switch (token) {
|
||||
.ident => |name| std.ascii.eqlIgnoreCase(name, "important"),
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn isBang(token: Tokenizer.Token) bool {
|
||||
return switch (token) {
|
||||
.delim => |c| c == '!',
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
824
src/browser/css/Tokenizer.zig
Normal file
824
src/browser/css/Tokenizer.zig
Normal file
@@ -0,0 +1,824 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
//! This file implements the tokenization step defined in the CSS Syntax Module Level 3 specification.
|
||||
//!
|
||||
//! The algorithm accepts a valid UTF-8 string and returns a stream of tokens.
|
||||
//! The tokenization step never fails, even for complete gibberish.
|
||||
//! Validity must then be checked by the parser.
|
||||
//!
|
||||
//! NOTE: The tokenizer is not thread-safe and does not own any memory, and does not check the validity of utf8.
|
||||
//!
|
||||
//! See spec for more info: https://drafts.csswg.org/css-syntax/#tokenization
|
||||
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
const assert = std.debug.assert;
|
||||
|
||||
const Tokenizer = @This();
|
||||
|
||||
pub const Token = union(enum) {
|
||||
/// A `<ident-token>`
|
||||
ident: []const u8,
|
||||
|
||||
/// A `<function-token>`
|
||||
///
|
||||
/// The value (name) does not include the `(` marker.
|
||||
function: []const u8,
|
||||
|
||||
/// A `<at-keyword-token>`
|
||||
///
|
||||
/// The value does not include the `@` marker.
|
||||
at_keyword: []const u8,
|
||||
|
||||
/// A `<hash-token>` with the type flag set to "id"
|
||||
///
|
||||
/// The value does not include the `#` marker.
|
||||
id_hash: []const u8, // Hash that is a valid ID selector.
|
||||
|
||||
/// A `<hash-token>` with the type flag set to "unrestricted"
|
||||
///
|
||||
/// The value does not include the `#` marker.
|
||||
unrestricted_hash: []const u8,
|
||||
|
||||
/// A `<string-token>`
|
||||
///
|
||||
/// The value does not include the quotes.
|
||||
string: []const u8,
|
||||
|
||||
/// A `<bad-string-token>`
|
||||
///
|
||||
/// This token always indicates a parse error.
|
||||
bad_string: []const u8,
|
||||
|
||||
/// A `<url-token>`
|
||||
///
|
||||
/// The value does not include the `url(` `)` markers. Note that `url( <string-token> )` is represented by a
|
||||
/// `Function` token.
|
||||
url: []const u8,
|
||||
|
||||
/// A `<bad-url-token>`
|
||||
///
|
||||
/// This token always indicates a parse error.
|
||||
bad_url: []const u8,
|
||||
|
||||
/// A `<delim-token>`
|
||||
delim: u8,
|
||||
|
||||
/// A `<number-token>`
|
||||
number: struct {
|
||||
/// Whether the number had a `+` or `-` sign.
|
||||
///
|
||||
/// This is used is some cases like the <An+B> micro syntax. (See the `parse_nth` function.)
|
||||
has_sign: bool,
|
||||
|
||||
/// If the origin source did not include a fractional part, the value as an integer.
|
||||
int_value: ?i32,
|
||||
|
||||
/// The value as a float
|
||||
value: f32,
|
||||
},
|
||||
|
||||
/// A `<percentage-token>`
|
||||
percentage: struct {
|
||||
/// Whether the number had a `+` or `-` sign.
|
||||
has_sign: bool,
|
||||
|
||||
/// If the origin source did not include a fractional part, the value as an integer.
|
||||
/// It is **not** divided by 100.
|
||||
int_value: ?i32,
|
||||
|
||||
/// The value as a float, divided by 100 so that the nominal range is 0.0 to 1.0.
|
||||
unit_value: f32,
|
||||
},
|
||||
|
||||
/// A `<dimension-token>`
|
||||
dimension: struct {
|
||||
/// Whether the number had a `+` or `-` sign.
|
||||
///
|
||||
/// This is used is some cases like the <An+B> micro syntax. (See the `parse_nth` function.)
|
||||
has_sign: bool,
|
||||
|
||||
/// If the origin source did not include a fractional part, the value as an integer.
|
||||
int_value: ?i32,
|
||||
|
||||
/// The value as a float
|
||||
value: f32,
|
||||
|
||||
/// The unit, e.g. "px" in `12px`
|
||||
unit: []const u8,
|
||||
},
|
||||
|
||||
/// A `<unicode-range-token>`
|
||||
unicode_range: struct { bgn: u32, end: i32 },
|
||||
|
||||
/// A `<whitespace-token>`
|
||||
white_space: []const u8,
|
||||
|
||||
/// A `<!--` `<CDO-token>`
|
||||
cdo,
|
||||
|
||||
/// A `-->` `<CDC-token>`
|
||||
cdc,
|
||||
|
||||
/// A `:` `<colon-token>`
|
||||
colon, // :
|
||||
|
||||
/// A `;` `<semicolon-token>`
|
||||
semicolon, // ;
|
||||
|
||||
/// A `,` `<comma-token>`
|
||||
comma, // ,
|
||||
|
||||
/// A `<[-token>`
|
||||
square_bracket_block,
|
||||
|
||||
/// A `<]-token>`
|
||||
///
|
||||
/// When obtained from one of the `Parser::next*` methods,
|
||||
/// this token is always unmatched and indicates a parse error.
|
||||
close_square_bracket,
|
||||
|
||||
/// A `<(-token>`
|
||||
parenthesis_block,
|
||||
|
||||
/// A `<)-token>`
|
||||
///
|
||||
/// When obtained from one of the `Parser::next*` methods,
|
||||
/// this token is always unmatched and indicates a parse error.
|
||||
close_parenthesis,
|
||||
|
||||
/// A `<{-token>`
|
||||
curly_bracket_block,
|
||||
|
||||
/// A `<}-token>`
|
||||
///
|
||||
/// When obtained from one of the `Parser::next*` methods,
|
||||
/// this token is always unmatched and indicates a parse error.
|
||||
close_curly_bracket,
|
||||
|
||||
/// A comment.
|
||||
///
|
||||
/// The CSS Syntax spec does not generate tokens for comments,
|
||||
/// But we do for simplicity of the interface.
|
||||
///
|
||||
/// The value does not include the `/*` `*/` markers.
|
||||
comment: []const u8,
|
||||
};
|
||||
|
||||
input: []const u8,
|
||||
|
||||
/// Counted in bytes, not code points. From 0.
|
||||
position: usize = 0,
|
||||
|
||||
// If true, the input has at least `n` bytes left *after* the current one.
|
||||
// That is, `Lexer.byteAt(n)` will not panic.
|
||||
fn hasAtLeast(self: *const Tokenizer, n: usize) bool {
|
||||
return self.position + n < self.input.len;
|
||||
}
|
||||
|
||||
fn isEof(self: *const Tokenizer) bool {
|
||||
return !self.hasAtLeast(0);
|
||||
}
|
||||
|
||||
fn byteAt(self: *const Tokenizer, offset: usize) u8 {
|
||||
return self.input[self.position + offset];
|
||||
}
|
||||
|
||||
// Assumes non-EOF
|
||||
fn nextByteUnchecked(self: *const Tokenizer) u8 {
|
||||
return self.byteAt(0);
|
||||
}
|
||||
|
||||
fn nextByte(self: *const Tokenizer) ?u8 {
|
||||
return if (self.isEof())
|
||||
null
|
||||
else
|
||||
self.input[self.position];
|
||||
}
|
||||
|
||||
fn startsWith(self: *const Tokenizer, needle: []const u8) bool {
|
||||
return std.mem.startsWith(u8, self.input[self.position..], needle);
|
||||
}
|
||||
|
||||
fn slice(self: *const Tokenizer, start: usize, end: usize) []const u8 {
|
||||
return self.input[start..end];
|
||||
}
|
||||
|
||||
fn sliceFrom(self: *const Tokenizer, start_pos: usize) []const u8 {
|
||||
return self.slice(start_pos, self.position);
|
||||
}
|
||||
|
||||
// Advance over N bytes in the input. This function can advance
|
||||
// over ASCII bytes (excluding newlines), or UTF-8 sequence
|
||||
// leaders (excluding leaders for 4-byte sequences).
|
||||
fn advance(self: *Tokenizer, n: usize) void {
|
||||
if (builtin.mode == .Debug) {
|
||||
// Each byte must either be an ASCII byte or a sequence leader,
|
||||
// but not a 4-byte leader; also newlines are rejected.
|
||||
for (0..n) |i| {
|
||||
const b = self.byteAt(i);
|
||||
assert(b != '\r' and b != '\n' and b != '\x0C');
|
||||
assert(b <= 0x7F or (b & 0xF0 != 0xF0 and b & 0xC0 != 0x80));
|
||||
}
|
||||
}
|
||||
self.position += n;
|
||||
}
|
||||
|
||||
fn hasNewlineAt(self: *const Tokenizer, offset: usize) bool {
|
||||
if (!self.hasAtLeast(offset)) return false;
|
||||
|
||||
return switch (self.byteAt(offset)) {
|
||||
'\n', '\r', '\x0C' => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn hasNonAsciiAt(self: *const Tokenizer, offset: usize) bool {
|
||||
if (!self.hasAtLeast(offset)) return false;
|
||||
|
||||
const byte = self.byteAt(offset);
|
||||
const len_utf8 = std.unicode.utf8ByteSequenceLength(byte) catch return false;
|
||||
|
||||
if (!self.hasAtLeast(offset + len_utf8 - 1)) return false;
|
||||
|
||||
const start = self.position + offset;
|
||||
const bytes = self.slice(start, start + len_utf8);
|
||||
|
||||
const codepoint = std.unicode.utf8Decode(bytes) catch return false;
|
||||
|
||||
// https://drafts.csswg.org/css-syntax/#non-ascii-ident-code-point
|
||||
return switch (codepoint) {
|
||||
'\u{00B7}', '\u{200C}', '\u{200D}', '\u{203F}', '\u{2040}' => true,
|
||||
'\u{00C0}'...'\u{00D6}' => true,
|
||||
'\u{00D8}'...'\u{00F6}' => true,
|
||||
'\u{00F8}'...'\u{037D}' => true,
|
||||
'\u{037F}'...'\u{1FFF}' => true,
|
||||
'\u{2070}'...'\u{218F}' => true,
|
||||
'\u{2C00}'...'\u{2FEF}' => true,
|
||||
'\u{3001}'...'\u{D7FF}' => true,
|
||||
'\u{F900}'...'\u{FDCF}' => true,
|
||||
'\u{FDF0}'...'\u{FFFD}' => true,
|
||||
else => codepoint >= '\u{10000}',
|
||||
};
|
||||
}
|
||||
|
||||
fn isIdentStart(self: *Tokenizer) bool {
|
||||
if (self.isEof()) return false;
|
||||
|
||||
var b = self.nextByteUnchecked();
|
||||
if (b == '-') {
|
||||
b = if (self.hasAtLeast(1)) self.byteAt(1) else return false;
|
||||
}
|
||||
|
||||
return switch (b) {
|
||||
'a'...'z', 'A'...'Z', '_', 0x0 => true,
|
||||
'\\' => !self.hasNewlineAt(1),
|
||||
else => b > 0x7F, // not is ascii
|
||||
};
|
||||
}
|
||||
|
||||
fn consumeChar(self: *Tokenizer) void {
|
||||
const byte = self.nextByteUnchecked();
|
||||
const len_utf8 = std.unicode.utf8ByteSequenceLength(byte) catch 1;
|
||||
self.position += len_utf8;
|
||||
}
|
||||
|
||||
// Given that a newline has been seen, advance over the newline
|
||||
// and update the state.
|
||||
fn consumeNewline(self: *Tokenizer) void {
|
||||
const byte = self.nextByteUnchecked();
|
||||
assert(byte == '\r' or byte == '\n' or byte == '\x0C');
|
||||
|
||||
self.position += 1;
|
||||
if (byte == '\r' and self.nextByte() == '\n') {
|
||||
self.position += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn consumeWhiteSpace(self: *Tokenizer, newline: bool) Token {
|
||||
const start_position = self.position;
|
||||
if (newline) {
|
||||
self.consumeNewline();
|
||||
} else {
|
||||
self.advance(1);
|
||||
}
|
||||
while (!self.isEof()) {
|
||||
const b = self.nextByteUnchecked();
|
||||
switch (b) {
|
||||
' ', '\t' => {
|
||||
self.advance(1);
|
||||
},
|
||||
'\n', '\x0C', '\r' => {
|
||||
self.consumeNewline();
|
||||
},
|
||||
else => break,
|
||||
}
|
||||
}
|
||||
return .{ .white_space = self.sliceFrom(start_position) };
|
||||
}
|
||||
|
||||
fn consumeComment(self: *Tokenizer) []const u8 {
|
||||
self.advance(2); // consume "/*"
|
||||
const start_position = self.position;
|
||||
while (!self.isEof()) {
|
||||
switch (self.nextByteUnchecked()) {
|
||||
'*' => {
|
||||
const end_position = self.position;
|
||||
self.advance(1);
|
||||
if (self.nextByte() == '/') {
|
||||
self.advance(1);
|
||||
return self.slice(start_position, end_position);
|
||||
}
|
||||
},
|
||||
'\n', '\x0C', '\r' => {
|
||||
self.consumeNewline();
|
||||
},
|
||||
0x0 => self.advance(1),
|
||||
else => self.consumeChar(),
|
||||
}
|
||||
}
|
||||
return self.sliceFrom(start_position);
|
||||
}
|
||||
|
||||
fn byteToHexDigit(b: u8) ?u32 {
|
||||
return switch (b) {
|
||||
'0'...'9' => b - '0',
|
||||
'a'...'f' => b - 'a' + 10,
|
||||
'A'...'F' => b - 'A' + 10,
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
fn byteToDecimalDigit(b: u8) ?u32 {
|
||||
return if (std.ascii.isDigit(b)) b - '0' else null;
|
||||
}
|
||||
|
||||
// (value, number of digits up to 6)
|
||||
fn consumeHexDigits(self: *Tokenizer) void {
|
||||
var value: u32 = 0;
|
||||
var digits: u32 = 0;
|
||||
|
||||
while (digits < 6 and !self.isEof()) {
|
||||
if (byteToHexDigit(self.nextByteUnchecked())) |digit| {
|
||||
value = value * 16 + digit;
|
||||
digits += 1;
|
||||
self.advance(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
_ = &value;
|
||||
}
|
||||
|
||||
// Assumes that the U+005C REVERSE SOLIDUS (\) has already been consumed
|
||||
// and that the next input character has already been verified
|
||||
// to not be a newline.
|
||||
fn consumeEscape(self: *Tokenizer) void {
|
||||
if (self.isEof())
|
||||
return; // Escaped EOF
|
||||
|
||||
switch (self.nextByteUnchecked()) {
|
||||
'0'...'9', 'A'...'F', 'a'...'f' => {
|
||||
consumeHexDigits(self);
|
||||
|
||||
if (!self.isEof()) {
|
||||
switch (self.nextByteUnchecked()) {
|
||||
' ', '\t' => {
|
||||
self.advance(1);
|
||||
},
|
||||
'\n', '\x0C', '\r' => {
|
||||
self.consumeNewline();
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
},
|
||||
else => self.consumeChar(),
|
||||
}
|
||||
}
|
||||
|
||||
/// https://drafts.csswg.org/css-syntax/#consume-string-token
|
||||
fn consumeString(self: *Tokenizer, single_quote: bool) Token {
|
||||
self.advance(1); // Skip the initial quote
|
||||
|
||||
// start_pos is at code point boundary, after " or '
|
||||
const start_pos = self.position;
|
||||
|
||||
while (!self.isEof()) {
|
||||
switch (self.nextByteUnchecked()) {
|
||||
'"' => {
|
||||
if (!single_quote) {
|
||||
const value = self.sliceFrom(start_pos);
|
||||
self.advance(1);
|
||||
return .{ .string = value };
|
||||
}
|
||||
self.advance(1);
|
||||
},
|
||||
'\'' => {
|
||||
if (single_quote) {
|
||||
const value = self.sliceFrom(start_pos);
|
||||
self.advance(1);
|
||||
return .{ .string = value };
|
||||
}
|
||||
self.advance(1);
|
||||
},
|
||||
'\n', '\r', '\x0C' => {
|
||||
return .{ .bad_string = self.sliceFrom(start_pos) };
|
||||
},
|
||||
'\\' => {
|
||||
self.advance(1);
|
||||
if (self.isEof())
|
||||
continue; // escaped EOF, do nothing.
|
||||
|
||||
switch (self.nextByteUnchecked()) {
|
||||
// Escaped newline
|
||||
'\n', '\x0C', '\r' => self.consumeNewline(),
|
||||
|
||||
// Spec calls for replacing escape sequences with characters,
|
||||
// but this would require allocating a new string.
|
||||
// Therefore, we leave it as is and let the parser handle the escaping.
|
||||
else => self.consumeEscape(),
|
||||
}
|
||||
},
|
||||
else => self.consumeChar(),
|
||||
}
|
||||
}
|
||||
|
||||
return .{ .string = self.sliceFrom(start_pos) };
|
||||
}
|
||||
|
||||
fn consumeName(self: *Tokenizer) []const u8 {
|
||||
// start_pos is the end of the previous token, therefore at a code point boundary
|
||||
const start_pos = self.position;
|
||||
|
||||
while (!self.isEof()) {
|
||||
switch (self.nextByteUnchecked()) {
|
||||
'a'...'z', 'A'...'Z', '0'...'9', '_', '-' => self.advance(1),
|
||||
'\\' => {
|
||||
if (self.hasNewlineAt(1)) {
|
||||
break;
|
||||
}
|
||||
|
||||
self.advance(1);
|
||||
self.consumeEscape();
|
||||
},
|
||||
0x0 => self.advance(1),
|
||||
'\x80'...'\xBF', '\xC0'...'\xEF', '\xF0'...'\xFF' => {
|
||||
// This byte *is* part of a multi-byte code point,
|
||||
// we’ll end up copying the whole code point before this loop does something else.
|
||||
self.advance(1);
|
||||
},
|
||||
else => {
|
||||
if (self.hasNonAsciiAt(0)) {
|
||||
self.consumeChar();
|
||||
} else {
|
||||
break; // ASCII
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return self.sliceFrom(start_pos);
|
||||
}
|
||||
|
||||
fn consumeMark(self: *Tokenizer) Token {
|
||||
const byte = self.nextByteUnchecked();
|
||||
self.advance(1);
|
||||
return switch (byte) {
|
||||
',' => .comma,
|
||||
':' => .colon,
|
||||
';' => .semicolon,
|
||||
'(' => .parenthesis_block,
|
||||
')' => .close_parenthesis,
|
||||
'{' => .curly_bracket_block,
|
||||
'}' => .close_curly_bracket,
|
||||
'[' => .square_bracket_block,
|
||||
']' => .close_square_bracket,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
fn consumeNumeric(self: *Tokenizer) Token {
|
||||
// Parse [+-]?\d*(\.\d+)?([eE][+-]?\d+)?
|
||||
// But this is always called so that there is at least one digit in \d*(\.\d+)?
|
||||
|
||||
// Do all the math in f64 so that large numbers overflow to +/-inf
|
||||
// and i32::{MIN, MAX} are within range.
|
||||
|
||||
var sign: f64 = 1.0;
|
||||
var has_sign = false;
|
||||
switch (self.nextByteUnchecked()) {
|
||||
'+' => {
|
||||
has_sign = true;
|
||||
},
|
||||
'-' => {
|
||||
has_sign = true;
|
||||
sign = -1.0;
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
if (has_sign) {
|
||||
self.advance(1);
|
||||
}
|
||||
|
||||
var is_integer = true;
|
||||
var integral_part: f64 = 0.0;
|
||||
var fractional_part: f64 = 0.0;
|
||||
|
||||
while (!self.isEof()) {
|
||||
if (byteToDecimalDigit(self.nextByteUnchecked())) |digit| {
|
||||
integral_part = integral_part * 10.0 + @as(f64, @floatFromInt(digit));
|
||||
self.advance(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (self.hasAtLeast(1) and self.nextByteUnchecked() == '.' and std.ascii.isDigit(self.byteAt(1))) {
|
||||
is_integer = false;
|
||||
self.advance(1); // Consume '.'
|
||||
|
||||
var factor: f64 = 0.1;
|
||||
while (!self.isEof()) {
|
||||
if (byteToDecimalDigit(self.nextByteUnchecked())) |digit| {
|
||||
fractional_part += @as(f64, @floatFromInt(digit)) * factor;
|
||||
factor *= 0.1;
|
||||
self.advance(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var value = sign * (integral_part + fractional_part);
|
||||
|
||||
blk: {
|
||||
const e = self.nextByte() orelse break :blk;
|
||||
if (e != 'e' and e != 'E') break :blk;
|
||||
|
||||
var mul: f64 = 1.0;
|
||||
|
||||
if (self.hasAtLeast(2) and (self.byteAt(1) == '+' or self.byteAt(1) == '-') and std.ascii.isDigit(self.byteAt(2))) {
|
||||
mul = switch (self.byteAt(1)) {
|
||||
'-' => -1.0,
|
||||
'+' => 1.0,
|
||||
else => unreachable,
|
||||
};
|
||||
|
||||
self.advance(2);
|
||||
} else if (self.hasAtLeast(1) and std.ascii.isDigit(self.byteAt(2))) {
|
||||
self.advance(1);
|
||||
} else {
|
||||
break :blk;
|
||||
}
|
||||
|
||||
is_integer = false;
|
||||
|
||||
var exponent: f64 = 0.0;
|
||||
while (!self.isEof()) {
|
||||
if (byteToDecimalDigit(self.nextByteUnchecked())) |digit| {
|
||||
exponent = exponent * 10.0 + @as(f64, @floatFromInt(digit));
|
||||
self.advance(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
value *= std.math.pow(f64, 10.0, mul * exponent);
|
||||
}
|
||||
|
||||
const int_value: ?i32 = if (is_integer) blk: {
|
||||
if (value >= std.math.maxInt(i32)) {
|
||||
break :blk std.math.maxInt(i32);
|
||||
}
|
||||
|
||||
if (value <= std.math.minInt(i32)) {
|
||||
break :blk std.math.minInt(i32);
|
||||
}
|
||||
|
||||
break :blk @as(i32, @intFromFloat(value));
|
||||
} else null;
|
||||
|
||||
if (!self.isEof() and self.nextByteUnchecked() == '%') {
|
||||
self.advance(1);
|
||||
|
||||
return .{ .percentage = .{
|
||||
.has_sign = has_sign,
|
||||
.int_value = int_value,
|
||||
.unit_value = @as(f32, @floatCast(value / 100.0)),
|
||||
} };
|
||||
}
|
||||
|
||||
if (isIdentStart(self)) {
|
||||
return .{ .dimension = .{
|
||||
.has_sign = has_sign,
|
||||
.int_value = int_value,
|
||||
.value = @as(f32, @floatCast(value)),
|
||||
.unit = consumeName(self),
|
||||
} };
|
||||
}
|
||||
|
||||
return .{ .number = .{
|
||||
.has_sign = has_sign,
|
||||
.int_value = int_value,
|
||||
.value = @as(f32, @floatCast(value)),
|
||||
} };
|
||||
}
|
||||
|
||||
fn consumeUnquotedUrl(self: *Tokenizer) ?Token {
|
||||
// TODO: true url parser
|
||||
if (self.nextByte()) |it| {
|
||||
return self.consumeString(it == '\'');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
fn consumeIdentLike(self: *Tokenizer) Token {
|
||||
const value = self.consumeName();
|
||||
|
||||
if (!self.isEof() and self.nextByteUnchecked() == '(') {
|
||||
self.advance(1);
|
||||
|
||||
if (std.ascii.eqlIgnoreCase(value, "url")) {
|
||||
if (self.consumeUnquotedUrl()) |result| {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return .{ .function = value };
|
||||
}
|
||||
|
||||
return .{ .ident = value };
|
||||
}
|
||||
|
||||
pub fn next(self: *Tokenizer) ?Token {
|
||||
if (self.isEof()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const b = self.nextByteUnchecked();
|
||||
return switch (b) {
|
||||
// Consume comments
|
||||
'/' => {
|
||||
if (self.startsWith("/*")) {
|
||||
return .{ .comment = self.consumeComment() };
|
||||
} else {
|
||||
self.advance(1);
|
||||
return .{ .delim = '/' };
|
||||
}
|
||||
},
|
||||
|
||||
// Consume marks
|
||||
'(', ')', '{', '}', '[', ']', ',', ':', ';' => {
|
||||
return self.consumeMark();
|
||||
},
|
||||
|
||||
// Consume as much whitespace as possible. Return a <whitespace-token>.
|
||||
' ', '\t' => self.consumeWhiteSpace(false),
|
||||
'\n', '\x0C', '\r' => self.consumeWhiteSpace(true),
|
||||
|
||||
// Consume a string token and return it.
|
||||
'"' => self.consumeString(false),
|
||||
'\'' => self.consumeString(true),
|
||||
|
||||
'0'...'9' => self.consumeNumeric(),
|
||||
'a'...'z', 'A'...'Z', '_', 0x0 => self.consumeIdentLike(),
|
||||
|
||||
'+' => {
|
||||
if ((self.hasAtLeast(1) and std.ascii.isDigit(self.byteAt(1))) or
|
||||
(self.hasAtLeast(2) and self.byteAt(1) == '.' and std.ascii.isDigit(self.byteAt(2))))
|
||||
{
|
||||
return self.consumeNumeric();
|
||||
}
|
||||
self.advance(1);
|
||||
return .{ .delim = '+' };
|
||||
},
|
||||
'-' => {
|
||||
if ((self.hasAtLeast(1) and std.ascii.isDigit(self.byteAt(1))) or
|
||||
(self.hasAtLeast(2) and self.byteAt(1) == '.' and std.ascii.isDigit(self.byteAt(2))))
|
||||
{
|
||||
return self.consumeNumeric();
|
||||
}
|
||||
|
||||
if (self.startsWith("-->")) {
|
||||
self.advance(3);
|
||||
return .cdc;
|
||||
}
|
||||
|
||||
if (isIdentStart(self)) {
|
||||
return self.consumeIdentLike();
|
||||
}
|
||||
|
||||
self.advance(1);
|
||||
return .{ .delim = '-' };
|
||||
},
|
||||
'.' => {
|
||||
if (self.hasAtLeast(1) and std.ascii.isDigit(self.byteAt(1))) {
|
||||
return self.consumeNumeric();
|
||||
}
|
||||
self.advance(1);
|
||||
return .{ .delim = '.' };
|
||||
},
|
||||
|
||||
// Consume hash token
|
||||
'#' => {
|
||||
self.advance(1);
|
||||
if (self.isIdentStart()) {
|
||||
return .{ .id_hash = self.consumeName() };
|
||||
}
|
||||
if (self.nextByte()) |it| {
|
||||
switch (it) {
|
||||
// Any other valid case here already resulted in IDHash.
|
||||
'0'...'9', '-' => return .{ .unrestricted_hash = self.consumeName() },
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
return .{ .delim = '#' };
|
||||
},
|
||||
|
||||
// Consume at-rules
|
||||
'@' => {
|
||||
self.advance(1);
|
||||
return if (isIdentStart(self))
|
||||
.{ .at_keyword = consumeName(self) }
|
||||
else
|
||||
.{ .delim = '@' };
|
||||
},
|
||||
|
||||
'<' => {
|
||||
if (self.startsWith("<!--")) {
|
||||
self.advance(4);
|
||||
return .cdo;
|
||||
} else {
|
||||
self.advance(1);
|
||||
return .{ .delim = '<' };
|
||||
}
|
||||
},
|
||||
|
||||
'\\' => {
|
||||
if (!self.hasNewlineAt(1)) {
|
||||
return self.consumeIdentLike();
|
||||
}
|
||||
|
||||
self.advance(1);
|
||||
return .{ .delim = '\\' };
|
||||
},
|
||||
|
||||
else => {
|
||||
if (b > 0x7F) { // not is ascii
|
||||
return self.consumeIdentLike();
|
||||
}
|
||||
|
||||
self.advance(1);
|
||||
return .{ .delim = b };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const testing = std.testing;
|
||||
|
||||
fn expectTokensEqual(input: []const u8, tokens: []const Token) !void {
|
||||
var lexer = Tokenizer{ .input = input };
|
||||
|
||||
var i: usize = 0;
|
||||
while (lexer.next()) |token| : (i += 1) {
|
||||
assert(i < tokens.len);
|
||||
try testing.expectEqualDeep(tokens[i], token);
|
||||
}
|
||||
|
||||
try testing.expectEqual(i, tokens.len);
|
||||
try testing.expectEqualDeep(null, lexer.next());
|
||||
}
|
||||
|
||||
test "smoke" {
|
||||
try expectTokensEqual(
|
||||
\\.lightpanda {color:red;}
|
||||
, &.{
|
||||
.{ .delim = '.' },
|
||||
.{ .ident = "lightpanda" },
|
||||
.{ .white_space = " " },
|
||||
.curly_bracket_block,
|
||||
.{ .ident = "color" },
|
||||
.colon,
|
||||
.{ .ident = "red" },
|
||||
.semicolon,
|
||||
.close_curly_bracket,
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (C) 2023-2024 Lightpanda (Selecy SAS)
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
@@ -17,116 +17,307 @@
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const File = std.fs.File;
|
||||
const Page = @import("Page.zig");
|
||||
const Node = @import("webapi/Node.zig");
|
||||
const Slot = @import("webapi/element/html/Slot.zig");
|
||||
|
||||
const parser = @import("netsurf");
|
||||
const Walker = @import("../dom/walker.zig").WalkerChildren;
|
||||
pub const RootOpts = struct {
|
||||
with_base: bool = false,
|
||||
strip: Opts.Strip = .{},
|
||||
shadow: Opts.Shadow = .rendered,
|
||||
};
|
||||
|
||||
// writer must be a std.io.Writer
|
||||
pub fn writeHTML(doc: *parser.Document, writer: anytype) !void {
|
||||
try writer.writeAll("<!DOCTYPE html>\n");
|
||||
try writeNode(parser.documentToNode(doc), writer);
|
||||
try writer.writeAll("\n");
|
||||
pub const Opts = struct {
|
||||
strip: Strip = .{},
|
||||
shadow: Shadow = .rendered,
|
||||
|
||||
pub const Strip = struct {
|
||||
js: bool = false,
|
||||
ui: bool = false,
|
||||
css: bool = false,
|
||||
};
|
||||
|
||||
pub const Shadow = enum {
|
||||
// Skip shadow DOM entirely (innerHTML/outerHTML)
|
||||
skip,
|
||||
|
||||
// Dump everyhting (like "view source")
|
||||
complete,
|
||||
|
||||
// Resolve slot elements (like what actually gets rendered)
|
||||
rendered,
|
||||
};
|
||||
};
|
||||
|
||||
pub fn root(doc: *Node.Document, opts: RootOpts, writer: *std.Io.Writer, page: *Page) !void {
|
||||
if (doc.is(Node.Document.HTMLDocument)) |html_doc| {
|
||||
try writer.writeAll("<!DOCTYPE html>");
|
||||
if (opts.with_base) {
|
||||
const parent = if (html_doc.getHead()) |head| head.asNode() else doc.asNode();
|
||||
const base = try doc.createElement("base", null, page);
|
||||
try base.setAttributeSafe("base", page.base(), page);
|
||||
_ = try parent.insertBefore(base.asNode(), parent.firstChild(), page);
|
||||
}
|
||||
}
|
||||
|
||||
// writer must be a std.io.Writer
|
||||
pub fn writeNode(root: *parser.Node, writer: anytype) !void {
|
||||
const walker = Walker{};
|
||||
var next: ?*parser.Node = null;
|
||||
while (true) {
|
||||
next = try walker.get_next(root, next) orelse break;
|
||||
switch (try parser.nodeType(next.?)) {
|
||||
.element => {
|
||||
// open the tag
|
||||
const tag = try parser.nodeLocalName(next.?);
|
||||
try writer.writeAll("<");
|
||||
try writer.writeAll(tag);
|
||||
|
||||
// write the attributes
|
||||
const map = try parser.nodeGetAttributes(next.?);
|
||||
const ln = try parser.namedNodeMapGetLength(map);
|
||||
var i: u32 = 0;
|
||||
while (i < ln) {
|
||||
const attr = try parser.namedNodeMapItem(map, i) orelse break;
|
||||
try writer.writeAll(" ");
|
||||
try writer.writeAll(try parser.attributeGetName(attr));
|
||||
try writer.writeAll("=\"");
|
||||
try writer.writeAll(try parser.attributeGetValue(attr) orelse "");
|
||||
try writer.writeAll("\"");
|
||||
i += 1;
|
||||
return deep(doc.asNode(), .{ .strip = opts.strip, .shadow = opts.shadow }, writer, page);
|
||||
}
|
||||
|
||||
try writer.writeAll(">");
|
||||
pub fn deep(node: *Node, opts: Opts, writer: *std.Io.Writer, page: *Page) error{WriteFailed}!void {
|
||||
return _deep(node, opts, false, writer, page);
|
||||
}
|
||||
|
||||
// void elements can't have any content.
|
||||
if (try isVoid(parser.nodeToElement(next.?))) continue;
|
||||
|
||||
// write the children
|
||||
// TODO avoid recursion
|
||||
try writeNode(next.?, writer);
|
||||
|
||||
// close the tag
|
||||
try writer.writeAll("</");
|
||||
try writer.writeAll(tag);
|
||||
try writer.writeAll(">");
|
||||
},
|
||||
.text => {
|
||||
const v = try parser.nodeValue(next.?) orelse continue;
|
||||
try writer.writeAll(v);
|
||||
},
|
||||
.cdata_section => {
|
||||
const v = try parser.nodeValue(next.?) orelse continue;
|
||||
try writer.writeAll("<![CDATA[");
|
||||
try writer.writeAll(v);
|
||||
try writer.writeAll("]]>");
|
||||
},
|
||||
.comment => {
|
||||
const v = try parser.nodeValue(next.?) orelse continue;
|
||||
fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Writer, page: *Page) error{WriteFailed}!void {
|
||||
switch (node._type) {
|
||||
.cdata => |cd| {
|
||||
if (node.is(Node.CData.Comment)) |_| {
|
||||
try writer.writeAll("<!--");
|
||||
try writer.writeAll(v);
|
||||
try writer.writeAll(cd.getData());
|
||||
try writer.writeAll("-->");
|
||||
} else if (node.is(Node.CData.ProcessingInstruction)) |pi| {
|
||||
try writer.writeAll("<?");
|
||||
try writer.writeAll(pi._target);
|
||||
try writer.writeAll(" ");
|
||||
try writer.writeAll(cd.getData());
|
||||
try writer.writeAll("?>");
|
||||
} else {
|
||||
if (shouldEscapeText(node._parent)) {
|
||||
try writeEscapedText(cd.getData(), writer);
|
||||
} else {
|
||||
try writer.writeAll(cd.getData());
|
||||
}
|
||||
}
|
||||
},
|
||||
// TODO handle processing instruction dump
|
||||
.processing_instruction => continue,
|
||||
// document fragment is outside of the main document DOM, so we
|
||||
// don't output it.
|
||||
.document_fragment => continue,
|
||||
// document will never be called, but required for completeness.
|
||||
.document => continue,
|
||||
// done globally instead, but required for completeness.
|
||||
.document_type => continue,
|
||||
// deprecated
|
||||
.attribute => continue,
|
||||
.entity_reference => continue,
|
||||
.entity => continue,
|
||||
.notation => continue,
|
||||
.element => |el| {
|
||||
if (shouldStripElement(el, opts)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// When opts.shadow == .rendered, we normally skip any element with
|
||||
// a slot attribute. Only the "active" element will get rendered into
|
||||
// the <slot name="X">. However, the `deep` function is itself used
|
||||
// to render that "active" content, so when we're trying to render
|
||||
// it, we don't want to skip it.
|
||||
if ((comptime force_slot == false) and opts.shadow == .rendered) {
|
||||
if (el.getAttributeSafe("slot")) |_| {
|
||||
// Skip - will be rendered by the Slot if it's the active container
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try el.format(writer);
|
||||
|
||||
if (opts.shadow == .rendered) {
|
||||
if (el.is(Slot)) |slot| {
|
||||
try dumpSlotContent(slot, opts, writer, page);
|
||||
return writer.writeAll("</slot>");
|
||||
}
|
||||
}
|
||||
if (opts.shadow != .skip) {
|
||||
if (page._element_shadow_roots.get(el)) |shadow| {
|
||||
try children(shadow.asNode(), opts, writer, page);
|
||||
// In rendered mode, light DOM is only shown through slots, not directly
|
||||
if (opts.shadow == .rendered) {
|
||||
// Skip rendering light DOM children
|
||||
if (!isVoidElement(el)) {
|
||||
try writer.writeAll("</");
|
||||
try writer.writeAll(el.getTagNameDump());
|
||||
try writer.writeByte('>');
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// area, base, br, col, embed, hr, img, input, link, meta, source, track, wbr
|
||||
// https://html.spec.whatwg.org/#void-elements
|
||||
fn isVoid(elem: *parser.Element) !bool {
|
||||
const tag = try parser.elementHTMLGetTagType(@as(*parser.ElementHTML, @ptrCast(elem)));
|
||||
return switch (tag) {
|
||||
.area, .base, .br, .col, .embed, .hr, .img, .input, .link => true,
|
||||
.meta, .source, .track, .wbr => true,
|
||||
try children(node, opts, writer, page);
|
||||
if (!isVoidElement(el)) {
|
||||
try writer.writeAll("</");
|
||||
try writer.writeAll(el.getTagNameDump());
|
||||
try writer.writeByte('>');
|
||||
}
|
||||
},
|
||||
.document => try children(node, opts, writer, page),
|
||||
.document_type => |dt| {
|
||||
try writer.writeAll("<!DOCTYPE ");
|
||||
try writer.writeAll(dt.getName());
|
||||
|
||||
const public_id = dt.getPublicId();
|
||||
const system_id = dt.getSystemId();
|
||||
if (public_id.len != 0 and system_id.len != 0) {
|
||||
try writer.writeAll(" PUBLIC \"");
|
||||
try writeEscapedText(public_id, writer);
|
||||
try writer.writeAll("\" \"");
|
||||
try writeEscapedText(system_id, writer);
|
||||
try writer.writeByte('"');
|
||||
} else if (public_id.len != 0) {
|
||||
try writer.writeAll(" PUBLIC \"");
|
||||
try writeEscapedText(public_id, writer);
|
||||
try writer.writeByte('"');
|
||||
} else if (system_id.len != 0) {
|
||||
try writer.writeAll(" SYSTEM \"");
|
||||
try writeEscapedText(system_id, writer);
|
||||
try writer.writeByte('"');
|
||||
}
|
||||
try writer.writeAll(">\n");
|
||||
},
|
||||
.document_fragment => try children(node, opts, writer, page),
|
||||
.attribute => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn children(parent: *Node, opts: Opts, writer: *std.Io.Writer, page: *Page) !void {
|
||||
var it = parent.childrenIterator();
|
||||
while (it.next()) |child| {
|
||||
try deep(child, opts, writer, page);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn toJSON(node: *Node, writer: *std.json.Stringify) !void {
|
||||
try writer.beginObject();
|
||||
|
||||
try writer.objectField("type");
|
||||
switch (node.type) {
|
||||
.cdata => {
|
||||
try writer.write("cdata");
|
||||
},
|
||||
.document => {
|
||||
try writer.write("document");
|
||||
},
|
||||
.document_type => {
|
||||
try writer.write("document_type");
|
||||
},
|
||||
.element => |*el| {
|
||||
try writer.write("element");
|
||||
try writer.objectField("tag");
|
||||
try writer.write(el.tagName());
|
||||
|
||||
try writer.objectField("attributes");
|
||||
try writer.beginObject();
|
||||
var it = el.attributeIterator();
|
||||
while (it.next()) |attr| {
|
||||
try writer.objectField(attr.name);
|
||||
try writer.write(attr.value);
|
||||
}
|
||||
try writer.endObject();
|
||||
},
|
||||
}
|
||||
|
||||
try writer.objectField("children");
|
||||
try writer.beginArray();
|
||||
var it = node.childrenIterator();
|
||||
while (it.next()) |child| {
|
||||
try toJSON(child, writer);
|
||||
}
|
||||
try writer.endArray();
|
||||
try writer.endObject();
|
||||
}
|
||||
|
||||
fn dumpSlotContent(slot: *Slot, opts: Opts, writer: *std.Io.Writer, page: *Page) !void {
|
||||
const assigned = slot.assignedNodes(null, page) catch return;
|
||||
|
||||
if (assigned.len > 0) {
|
||||
for (assigned) |assigned_node| {
|
||||
try _deep(assigned_node, opts, true, writer, page);
|
||||
}
|
||||
} else {
|
||||
try children(slot.asNode(), opts, writer, page);
|
||||
}
|
||||
}
|
||||
|
||||
fn isVoidElement(el: *const Node.Element) bool {
|
||||
return switch (el._type) {
|
||||
.html => |html| switch (html._type) {
|
||||
.br, .hr, .img, .input, .link, .meta => true,
|
||||
else => false,
|
||||
},
|
||||
.svg => false,
|
||||
};
|
||||
}
|
||||
|
||||
test "dump.writeHTML" {
|
||||
const out = try std.fs.openFileAbsolute("/dev/null", .{ .mode = .write_only });
|
||||
defer out.close();
|
||||
fn shouldStripElement(el: *const Node.Element, opts: Opts) bool {
|
||||
const tag_name = el.getTagNameDump();
|
||||
|
||||
const file = try std.fs.cwd().openFile("test.html", .{});
|
||||
defer file.close();
|
||||
if (opts.strip.js) {
|
||||
if (std.mem.eql(u8, tag_name, "script")) return true;
|
||||
if (std.mem.eql(u8, tag_name, "noscript")) return true;
|
||||
|
||||
const doc_html = try parser.documentHTMLParse(file.reader(), "UTF-8");
|
||||
// ignore close error
|
||||
defer parser.documentHTMLClose(doc_html) catch {};
|
||||
|
||||
const doc = parser.documentHTMLToDocument(doc_html);
|
||||
|
||||
try writeHTML(doc, out);
|
||||
if (std.mem.eql(u8, tag_name, "link")) {
|
||||
if (el.getAttributeSafe("as")) |as| {
|
||||
if (std.mem.eql(u8, as, "script")) return true;
|
||||
}
|
||||
if (el.getAttributeSafe("rel")) |rel| {
|
||||
if (std.mem.eql(u8, rel, "modulepreload") or std.mem.eql(u8, rel, "preload")) {
|
||||
if (el.getAttributeSafe("as")) |as| {
|
||||
if (std.mem.eql(u8, as, "script")) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (opts.strip.css or opts.strip.ui) {
|
||||
if (std.mem.eql(u8, tag_name, "style")) return true;
|
||||
|
||||
if (std.mem.eql(u8, tag_name, "link")) {
|
||||
if (el.getAttributeSafe("rel")) |rel| {
|
||||
if (std.mem.eql(u8, rel, "stylesheet")) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (opts.strip.ui) {
|
||||
if (std.mem.eql(u8, tag_name, "img")) return true;
|
||||
if (std.mem.eql(u8, tag_name, "picture")) return true;
|
||||
if (std.mem.eql(u8, tag_name, "video")) return true;
|
||||
if (std.mem.eql(u8, tag_name, "audio")) return true;
|
||||
if (std.mem.eql(u8, tag_name, "svg")) return true;
|
||||
if (std.mem.eql(u8, tag_name, "canvas")) return true;
|
||||
if (std.mem.eql(u8, tag_name, "iframe")) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
fn shouldEscapeText(node_: ?*Node) bool {
|
||||
const node = node_ orelse return true;
|
||||
if (node.is(Node.Element.Html.Script) != null) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
fn writeEscapedText(text: []const u8, writer: *std.Io.Writer) !void {
|
||||
// Fast path: if no special characters, write directly
|
||||
const first_special = std.mem.indexOfAnyPos(u8, text, 0, &.{ '&', '<', '>', 194 }) orelse {
|
||||
return writer.writeAll(text);
|
||||
};
|
||||
|
||||
try writer.writeAll(text[0..first_special]);
|
||||
var remaining = try writeEscapedByte(text, first_special, writer);
|
||||
|
||||
while (std.mem.indexOfAnyPos(u8, remaining, 0, &.{ '&', '<', '>', 194 })) |offset| {
|
||||
try writer.writeAll(remaining[0..offset]);
|
||||
remaining = try writeEscapedByte(remaining, offset, writer);
|
||||
}
|
||||
|
||||
if (remaining.len > 0) {
|
||||
try writer.writeAll(remaining);
|
||||
}
|
||||
}
|
||||
|
||||
fn writeEscapedByte(input: []const u8, index: usize, writer: *std.Io.Writer) ![]const u8 {
|
||||
switch (input[index]) {
|
||||
'&' => try writer.writeAll("&"),
|
||||
'<' => try writer.writeAll("<"),
|
||||
'>' => try writer.writeAll(">"),
|
||||
194 => {
|
||||
// non breaking space
|
||||
if (input.len > index + 1 and input[index + 1] == 160) {
|
||||
try writer.writeAll(" ");
|
||||
return input[index + 2 ..];
|
||||
}
|
||||
try writer.writeByte(194);
|
||||
},
|
||||
else => unreachable,
|
||||
}
|
||||
return input[index + 1 ..];
|
||||
}
|
||||
|
||||
38
src/browser/js/Array.zig
Normal file
38
src/browser/js/Array.zig
Normal file
@@ -0,0 +1,38 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const Array = @This();
|
||||
js_arr: v8.Array,
|
||||
context: *js.Context,
|
||||
|
||||
pub fn len(self: Array) usize {
|
||||
return @intCast(self.js_arr.length());
|
||||
}
|
||||
|
||||
pub fn get(self: Array, index: usize) !js.Value {
|
||||
const idx_key = v8.Integer.initU32(self.context.isolate, @intCast(index));
|
||||
const js_obj = self.js_arr.castTo(v8.Object);
|
||||
return .{
|
||||
.context = self.context,
|
||||
.js_val = try js_obj.getValue(self.context.v8_context, idx_key.toValue()),
|
||||
};
|
||||
}
|
||||
538
src/browser/js/Caller.zig
Normal file
538
src/browser/js/Caller.zig
Normal file
@@ -0,0 +1,538 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
const log = @import("../../log.zig");
|
||||
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const Context = @import("Context.zig");
|
||||
|
||||
const Page = @import("../Page.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const ArenaAllocator = std.heap.ArenaAllocator;
|
||||
|
||||
const CALL_ARENA_RETAIN = 1024 * 16;
|
||||
|
||||
// Responsible for calling Zig functions from JS invocations. This could
|
||||
// probably just contained in ExecutionWorld, but having this specific logic, which
|
||||
// is somewhat repetitive between constructors, functions, getters, etc contained
|
||||
// here does feel like it makes it cleaner.
|
||||
const Caller = @This();
|
||||
context: *Context,
|
||||
v8_context: v8.Context,
|
||||
isolate: v8.Isolate,
|
||||
call_arena: Allocator,
|
||||
|
||||
// info is a v8.PropertyCallbackInfo or a v8.FunctionCallback
|
||||
// All we really want from it is the isolate.
|
||||
// executor = Isolate -> getCurrentContext -> getEmbedderData()
|
||||
pub fn init(info: anytype) Caller {
|
||||
const isolate = info.getIsolate();
|
||||
const v8_context = isolate.getCurrentContext();
|
||||
const context: *Context = @ptrFromInt(v8_context.getEmbedderData(1).castTo(v8.BigInt).getUint64());
|
||||
|
||||
context.call_depth += 1;
|
||||
return .{
|
||||
.context = context,
|
||||
.isolate = isolate,
|
||||
.v8_context = v8_context,
|
||||
.call_arena = context.call_arena,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Caller) void {
|
||||
const context = self.context;
|
||||
const call_depth = context.call_depth - 1;
|
||||
|
||||
// Because of callbacks, calls can be nested. Because of this, we
|
||||
// can't clear the call_arena after _every_ call. Imagine we have
|
||||
// arr.forEach((i) => { console.log(i); }
|
||||
//
|
||||
// First we call forEach. Inside of our forEach call,
|
||||
// we call console.log. If we reset the call_arena after this call,
|
||||
// it'll reset it for the `forEach` call after, which might still
|
||||
// need the data.
|
||||
//
|
||||
// Therefore, we keep a call_depth, and only reset the call_arena
|
||||
// when a top-level (call_depth == 0) function ends.
|
||||
if (call_depth == 0) {
|
||||
const arena: *ArenaAllocator = @ptrCast(@alignCast(context.call_arena.ptr));
|
||||
_ = arena.reset(.{ .retain_with_limit = CALL_ARENA_RETAIN });
|
||||
}
|
||||
|
||||
context.call_depth = call_depth;
|
||||
}
|
||||
|
||||
pub const CallOpts = struct {
|
||||
dom_exception: bool = false,
|
||||
null_as_undefined: bool = false,
|
||||
as_typed_array: bool = false,
|
||||
};
|
||||
|
||||
pub fn constructor(self: *Caller, comptime T: type, func: anytype, info: v8.FunctionCallbackInfo, comptime opts: CallOpts) void {
|
||||
if (!info.isConstructCall()) {
|
||||
self.handleError(T, @TypeOf(func), error.InvalidArgument, info, opts);
|
||||
return;
|
||||
}
|
||||
self._constructor(func, info) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
};
|
||||
}
|
||||
pub fn _constructor(self: *Caller, func: anytype, info: v8.FunctionCallbackInfo) !void {
|
||||
const F = @TypeOf(func);
|
||||
const args = try self.getArgs(F, 0, info);
|
||||
const res = @call(.auto, func, args);
|
||||
|
||||
const ReturnType = @typeInfo(F).@"fn".return_type orelse {
|
||||
@compileError(@typeName(F) ++ " has a constructor without a return type");
|
||||
};
|
||||
|
||||
const new_this = info.getThis();
|
||||
var this = new_this;
|
||||
if (@typeInfo(ReturnType) == .error_union) {
|
||||
const non_error_res = res catch |err| return err;
|
||||
this = (try self.context.mapZigInstanceToJs(this, non_error_res)).castToObject();
|
||||
} else {
|
||||
this = (try self.context.mapZigInstanceToJs(this, res)).castToObject();
|
||||
}
|
||||
|
||||
// If we got back a different object (existing wrapper), copy the prototype
|
||||
// from new object. (this happens when we're upgrading an CustomElement)
|
||||
if (this.handle != new_this.handle) {
|
||||
const new_prototype = new_this.getPrototype();
|
||||
_ = this.setPrototype(self.context.v8_context, new_prototype.castTo(v8.Object));
|
||||
}
|
||||
|
||||
info.getReturnValue().set(this);
|
||||
}
|
||||
|
||||
pub fn method(self: *Caller, comptime T: type, func: anytype, info: v8.FunctionCallbackInfo, comptime opts: CallOpts) void {
|
||||
self._method(T, func, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
};
|
||||
}
|
||||
|
||||
pub fn _method(self: *Caller, comptime T: type, func: anytype, info: v8.FunctionCallbackInfo, comptime opts: CallOpts) !void {
|
||||
const F = @TypeOf(func);
|
||||
var handle_scope: v8.HandleScope = undefined;
|
||||
handle_scope.init(self.isolate);
|
||||
defer handle_scope.deinit();
|
||||
|
||||
var args = try self.getArgs(F, 1, info);
|
||||
@field(args, "0") = try Context.typeTaggedAnyOpaque(*T, info.getThis());
|
||||
const res = @call(.auto, func, args);
|
||||
info.getReturnValue().set(try self.context.zigValueToJs(res, opts));
|
||||
}
|
||||
|
||||
pub fn function(self: *Caller, comptime T: type, func: anytype, info: v8.FunctionCallbackInfo, comptime opts: CallOpts) void {
|
||||
self._function(func, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
};
|
||||
}
|
||||
|
||||
pub fn _function(self: *Caller, func: anytype, info: v8.FunctionCallbackInfo, comptime opts: CallOpts) !void {
|
||||
const F = @TypeOf(func);
|
||||
const context = self.context;
|
||||
const args = try self.getArgs(F, 0, info);
|
||||
const res = @call(.auto, func, args);
|
||||
info.getReturnValue().set(try context.zigValueToJs(res, opts));
|
||||
}
|
||||
|
||||
pub fn getIndex(self: *Caller, comptime T: type, func: anytype, idx: u32, info: v8.PropertyCallbackInfo, comptime opts: CallOpts) u8 {
|
||||
return self._getIndex(T, func, idx, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
return v8.Intercepted.No;
|
||||
};
|
||||
}
|
||||
|
||||
pub fn _getIndex(self: *Caller, comptime T: type, func: anytype, idx: u32, info: v8.PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
const F = @TypeOf(func);
|
||||
var args = try self.getArgs(F, 2, info);
|
||||
@field(args, "0") = try Context.typeTaggedAnyOpaque(*T, info.getThis());
|
||||
@field(args, "1") = idx;
|
||||
const ret = @call(.auto, func, args);
|
||||
return self.handleIndexedReturn(T, F, true, ret, info, opts);
|
||||
}
|
||||
|
||||
pub fn getNamedIndex(self: *Caller, comptime T: type, func: anytype, name: v8.Name, info: v8.PropertyCallbackInfo, comptime opts: CallOpts) u8 {
|
||||
return self._getNamedIndex(T, func, name, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
return v8.Intercepted.No;
|
||||
};
|
||||
}
|
||||
|
||||
pub fn _getNamedIndex(self: *Caller, comptime T: type, func: anytype, name: v8.Name, info: v8.PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
const F = @TypeOf(func);
|
||||
var args = try self.getArgs(F, 2, info);
|
||||
@field(args, "0") = try Context.typeTaggedAnyOpaque(*T, info.getThis());
|
||||
@field(args, "1") = try self.nameToString(name);
|
||||
const ret = @call(.auto, func, args);
|
||||
return self.handleIndexedReturn(T, F, true, ret, info, opts);
|
||||
}
|
||||
|
||||
pub fn setNamedIndex(self: *Caller, comptime T: type, func: anytype, name: v8.Name, js_value: v8.Value, info: v8.PropertyCallbackInfo, comptime opts: CallOpts) u8 {
|
||||
return self._setNamedIndex(T, func, name, js_value, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
return v8.Intercepted.No;
|
||||
};
|
||||
}
|
||||
|
||||
pub fn _setNamedIndex(self: *Caller, comptime T: type, func: anytype, name: v8.Name, js_value: v8.Value, info: v8.PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
const F = @TypeOf(func);
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
@field(args, "0") = try Context.typeTaggedAnyOpaque(*T, info.getThis());
|
||||
@field(args, "1") = try self.nameToString(name);
|
||||
@field(args, "2") = try self.context.jsValueToZig(@TypeOf(@field(args, "2")), js_value);
|
||||
if (@typeInfo(F).@"fn".params.len == 4) {
|
||||
@field(args, "3") = self.context.page;
|
||||
}
|
||||
const ret = @call(.auto, func, args);
|
||||
return self.handleIndexedReturn(T, F, false, ret, info, opts);
|
||||
}
|
||||
|
||||
pub fn deleteNamedIndex(self: *Caller, comptime T: type, func: anytype, name: v8.Name, info: v8.PropertyCallbackInfo, comptime opts: CallOpts) u8 {
|
||||
return self._deleteNamedIndex(T, func, name, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
return v8.Intercepted.No;
|
||||
};
|
||||
}
|
||||
|
||||
pub fn _deleteNamedIndex(self: *Caller, comptime T: type, func: anytype, name: v8.Name, info: v8.PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
const F = @TypeOf(func);
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
@field(args, "0") = try Context.typeTaggedAnyOpaque(*T, info.getThis());
|
||||
@field(args, "1") = try self.nameToString(name);
|
||||
if (@typeInfo(F).@"fn".params.len == 3) {
|
||||
@field(args, "2") = self.context.page;
|
||||
}
|
||||
const ret = @call(.auto, func, args);
|
||||
return self.handleIndexedReturn(T, F, false, ret, info, opts);
|
||||
}
|
||||
|
||||
fn handleIndexedReturn(self: *Caller, comptime T: type, comptime F: type, comptime getter: bool, ret: anytype, info: v8.PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
// need to unwrap this error immediately for when opts.null_as_undefined == true
|
||||
// and we need to compare it to null;
|
||||
const non_error_ret = switch (@typeInfo(@TypeOf(ret))) {
|
||||
.error_union => |eu| blk: {
|
||||
break :blk ret catch |err| {
|
||||
// We can't compare err == error.NotHandled if error.NotHandled
|
||||
// isn't part of the possible error set. So we first need to check
|
||||
// if error.NotHandled is part of the error set.
|
||||
if (isInErrorSet(error.NotHandled, eu.error_set)) {
|
||||
if (err == error.NotHandled) {
|
||||
return v8.Intercepted.No;
|
||||
}
|
||||
}
|
||||
self.handleError(T, F, err, info, opts);
|
||||
return v8.Intercepted.No;
|
||||
};
|
||||
},
|
||||
else => ret,
|
||||
};
|
||||
|
||||
if (comptime getter) {
|
||||
info.getReturnValue().set(try self.context.zigValueToJs(non_error_ret, opts));
|
||||
}
|
||||
return v8.Intercepted.Yes;
|
||||
}
|
||||
|
||||
fn isInErrorSet(err: anyerror, comptime T: type) bool {
|
||||
inline for (@typeInfo(T).error_set.?) |e| {
|
||||
if (err == @field(anyerror, e.name)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
fn namedSetOrDeleteCall(res: anytype, has_value: bool) !u8 {
|
||||
if (@typeInfo(@TypeOf(res)) == .error_union) {
|
||||
_ = try res;
|
||||
}
|
||||
if (has_value == false) {
|
||||
return v8.Intercepted.No;
|
||||
}
|
||||
return v8.Intercepted.Yes;
|
||||
}
|
||||
|
||||
fn nameToString(self: *Caller, name: v8.Name) ![]const u8 {
|
||||
return self.context.valueToString(.{ .handle = name.handle }, .{});
|
||||
}
|
||||
|
||||
fn isSelfReceiver(comptime T: type, comptime F: type) bool {
|
||||
return checkSelfReceiver(T, F, false);
|
||||
}
|
||||
fn assertSelfReceiver(comptime T: type, comptime F: type) void {
|
||||
_ = checkSelfReceiver(T, F, true);
|
||||
}
|
||||
fn checkSelfReceiver(comptime T: type, comptime F: type, comptime fail: bool) bool {
|
||||
const params = @typeInfo(F).@"fn".params;
|
||||
if (params.len == 0) {
|
||||
if (fail) {
|
||||
@compileError(@typeName(F) ++ " must have a self parameter");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const first_param = params[0].type.?;
|
||||
if (first_param != *T and first_param != *const T) {
|
||||
if (fail) {
|
||||
@compileError(std.fmt.comptimePrint("The first parameter to {s} must be a *{s} or *const {s}. Got: {s}", .{
|
||||
@typeName(F),
|
||||
@typeName(T),
|
||||
@typeName(T),
|
||||
@typeName(first_param),
|
||||
}));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
fn assertIsPageArg(comptime T: type, comptime F: type, index: comptime_int) void {
|
||||
const param = @typeInfo(F).@"fn".params[index].type.?;
|
||||
if (isPage(param)) {
|
||||
return;
|
||||
}
|
||||
@compileError(std.fmt.comptimePrint("The {d} parameter of {s}.{s} must be a *Page or *const Page. Got: {s}", .{ index, @typeName(T), @typeName(F), @typeName(param) }));
|
||||
}
|
||||
|
||||
fn handleError(self: *Caller, comptime T: type, comptime F: type, err: anyerror, info: anytype, comptime opts: CallOpts) void {
|
||||
const isolate = self.isolate;
|
||||
|
||||
if (comptime @import("builtin").mode == .Debug and @hasDecl(@TypeOf(info), "length")) {
|
||||
if (log.enabled(.js, .warn)) {
|
||||
self.logFunctionCallError(@typeName(T), @typeName(F), err, info);
|
||||
}
|
||||
}
|
||||
|
||||
var js_err: ?v8.Value = switch (err) {
|
||||
error.InvalidArgument => createTypeException(isolate, "invalid argument"),
|
||||
error.OutOfMemory => js._createException(isolate, "out of memory"),
|
||||
error.IllegalConstructor => js._createException(isolate, "Illegal Contructor"),
|
||||
else => blk: {
|
||||
if (!comptime opts.dom_exception) {
|
||||
break :blk null;
|
||||
}
|
||||
const DOMException = @import("../webapi/DOMException.zig");
|
||||
const ex = DOMException.fromError(err) orelse break :blk null;
|
||||
break :blk self.context.zigValueToJs(ex, .{}) catch js._createException(isolate, "internal error");
|
||||
},
|
||||
};
|
||||
|
||||
if (js_err == null) {
|
||||
js_err = js._createException(isolate, @errorName(err));
|
||||
}
|
||||
const js_exception = isolate.throwException(js_err.?);
|
||||
info.getReturnValue().setValueHandle(js_exception.handle);
|
||||
}
|
||||
|
||||
// If we call a method in javascript: cat.lives('nine');
|
||||
//
|
||||
// Then we'd expect a Zig function with 2 parameters: a self and the string.
|
||||
// In this case, offset == 1. Offset is always 1 for setters or methods.
|
||||
//
|
||||
// Offset is always 0 for constructors.
|
||||
//
|
||||
// For constructors, setters and methods, we can further increase offset + 1
|
||||
// if the first parameter is an instance of Page.
|
||||
//
|
||||
// Finally, if the JS function is called with _more_ parameters and
|
||||
// the last parameter in Zig is an array, we'll try to slurp the additional
|
||||
// parameters into the array.
|
||||
fn getArgs(self: *const Caller, comptime F: type, comptime offset: usize, info: anytype) !ParameterTypes(F) {
|
||||
const context = self.context;
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
|
||||
const params = @typeInfo(F).@"fn".params[offset..];
|
||||
// Except for the constructor, the first parameter is always `self`
|
||||
// This isn't something we'll bind from JS, so skip it.
|
||||
const params_to_map = blk: {
|
||||
if (params.len == 0) {
|
||||
return args;
|
||||
}
|
||||
|
||||
// If the last parameter is the Page, set it, and exclude it
|
||||
// from our params slice, because we don't want to bind it to
|
||||
// a JS argument
|
||||
if (comptime isPage(params[params.len - 1].type.?)) {
|
||||
@field(args, tupleFieldName(params.len - 1 + offset)) = self.context.page;
|
||||
break :blk params[0 .. params.len - 1];
|
||||
}
|
||||
|
||||
// If the last parameter is a special JsThis, set it, and exclude it
|
||||
// from our params slice, because we don't want to bind it to
|
||||
// a JS argument
|
||||
if (comptime params[params.len - 1].type.? == js.This) {
|
||||
@field(args, tupleFieldName(params.len - 1 + offset)) = .{ .obj = .{
|
||||
.context = context,
|
||||
.js_obj = info.getThis(),
|
||||
} };
|
||||
|
||||
// AND the 2nd last parameter is state
|
||||
if (params.len > 1 and comptime isPage(params[params.len - 2].type.?)) {
|
||||
@field(args, tupleFieldName(params.len - 2 + offset)) = self.context.page;
|
||||
break :blk params[0 .. params.len - 2];
|
||||
}
|
||||
|
||||
break :blk params[0 .. params.len - 1];
|
||||
}
|
||||
|
||||
// we have neither a Page nor a JsObject. All params must be
|
||||
// bound to a JavaScript value.
|
||||
break :blk params;
|
||||
};
|
||||
|
||||
if (params_to_map.len == 0) {
|
||||
return args;
|
||||
}
|
||||
|
||||
const js_parameter_count = info.length();
|
||||
const last_js_parameter = params_to_map.len - 1;
|
||||
var is_variadic = false;
|
||||
|
||||
{
|
||||
// This is going to get complicated. If the last Zig parameter
|
||||
// is a slice AND the corresponding javascript parameter is
|
||||
// NOT an an array, then we'll treat it as a variadic.
|
||||
|
||||
const last_parameter_type = params_to_map[params_to_map.len - 1].type.?;
|
||||
const last_parameter_type_info = @typeInfo(last_parameter_type);
|
||||
if (last_parameter_type_info == .pointer and last_parameter_type_info.pointer.size == .slice) {
|
||||
const slice_type = last_parameter_type_info.pointer.child;
|
||||
const corresponding_js_value = info.getArg(@as(u32, @intCast(last_js_parameter)));
|
||||
if (corresponding_js_value.isArray() == false and corresponding_js_value.isTypedArray() == false and slice_type != u8) {
|
||||
is_variadic = true;
|
||||
if (js_parameter_count == 0) {
|
||||
@field(args, tupleFieldName(params_to_map.len + offset - 1)) = &.{};
|
||||
} else if (js_parameter_count >= params_to_map.len) {
|
||||
const arr = try self.call_arena.alloc(last_parameter_type_info.pointer.child, js_parameter_count - params_to_map.len + 1);
|
||||
for (arr, last_js_parameter..) |*a, i| {
|
||||
const js_value = info.getArg(@as(u32, @intCast(i)));
|
||||
a.* = try context.jsValueToZig(slice_type, js_value);
|
||||
}
|
||||
@field(args, tupleFieldName(params_to_map.len + offset - 1)) = arr;
|
||||
} else {
|
||||
@field(args, tupleFieldName(params_to_map.len + offset - 1)) = &.{};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline for (params_to_map, 0..) |param, i| {
|
||||
const field_index = comptime i + offset;
|
||||
if (comptime i == params_to_map.len - 1) {
|
||||
if (is_variadic) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (comptime isPage(param.type.?)) {
|
||||
@compileError("Page must be the last parameter (or 2nd last if there's a JsThis): " ++ @typeName(F));
|
||||
} else if (comptime param.type.? == js.This) {
|
||||
@compileError("JsThis must be the last parameter: " ++ @typeName(F));
|
||||
} else if (i >= js_parameter_count) {
|
||||
if (@typeInfo(param.type.?) != .optional) {
|
||||
return error.InvalidArgument;
|
||||
}
|
||||
@field(args, tupleFieldName(field_index)) = null;
|
||||
} else {
|
||||
const js_value = info.getArg(@as(u32, @intCast(i)));
|
||||
@field(args, tupleFieldName(field_index)) = context.jsValueToZig(param.type.?, js_value) catch {
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
// This is extracted to speed up compilation. When left inlined in handleError,
|
||||
// this can add as much as 10 seconds of compilation time.
|
||||
fn logFunctionCallError(self: *Caller, type_name: []const u8, func: []const u8, err: anyerror, info: v8.FunctionCallbackInfo) void {
|
||||
const args_dump = self.serializeFunctionArgs(info) catch "failed to serialize args";
|
||||
log.info(.js, "function call error", .{
|
||||
.type = type_name,
|
||||
.func = func,
|
||||
.err = err,
|
||||
.args = args_dump,
|
||||
.stack = self.context.stackTrace() catch |err1| @errorName(err1),
|
||||
});
|
||||
}
|
||||
|
||||
fn serializeFunctionArgs(self: *Caller, info: v8.FunctionCallbackInfo) ![]const u8 {
|
||||
const context = self.context;
|
||||
var buf = std.Io.Writer.Allocating.init(context.call_arena);
|
||||
|
||||
const separator = log.separator();
|
||||
for (0..info.length()) |i| {
|
||||
try buf.writer.print("{s}{d} - ", .{ separator, i + 1 });
|
||||
try context.debugValue(info.getArg(@intCast(i)), &buf.writer);
|
||||
}
|
||||
return buf.written();
|
||||
}
|
||||
|
||||
// Takes a function, and returns a tuple for its argument. Used when we
|
||||
// @call a function
|
||||
fn ParameterTypes(comptime F: type) type {
|
||||
const params = @typeInfo(F).@"fn".params;
|
||||
var fields: [params.len]std.builtin.Type.StructField = undefined;
|
||||
|
||||
inline for (params, 0..) |param, i| {
|
||||
fields[i] = .{
|
||||
.name = tupleFieldName(i),
|
||||
.type = param.type.?,
|
||||
.default_value_ptr = null,
|
||||
.is_comptime = false,
|
||||
.alignment = @alignOf(param.type.?),
|
||||
};
|
||||
}
|
||||
|
||||
return @Type(.{ .@"struct" = .{
|
||||
.layout = .auto,
|
||||
.decls = &.{},
|
||||
.fields = &fields,
|
||||
.is_tuple = true,
|
||||
} });
|
||||
}
|
||||
|
||||
fn tupleFieldName(comptime i: usize) [:0]const u8 {
|
||||
return switch (i) {
|
||||
0 => "0",
|
||||
1 => "1",
|
||||
2 => "2",
|
||||
3 => "3",
|
||||
4 => "4",
|
||||
5 => "5",
|
||||
6 => "6",
|
||||
7 => "7",
|
||||
8 => "8",
|
||||
9 => "9",
|
||||
else => std.fmt.comptimePrint("{d}", .{i}),
|
||||
};
|
||||
}
|
||||
|
||||
fn isPage(comptime T: type) bool {
|
||||
return T == *Page or T == *const Page;
|
||||
}
|
||||
|
||||
fn createTypeException(isolate: v8.Isolate, msg: []const u8) v8.Value {
|
||||
return v8.Exception.initTypeError(v8.String.initUtf8(isolate, msg));
|
||||
}
|
||||
2089
src/browser/js/Context.zig
Normal file
2089
src/browser/js/Context.zig
Normal file
File diff suppressed because it is too large
Load Diff
193
src/browser/js/Env.zig
Normal file
193
src/browser/js/Env.zig
Normal file
@@ -0,0 +1,193 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const log = @import("../../log.zig");
|
||||
|
||||
const bridge = @import("bridge.zig");
|
||||
const Context = @import("Context.zig");
|
||||
const Platform = @import("Platform.zig");
|
||||
const Snapshot = @import("Snapshot.zig");
|
||||
const Inspector = @import("Inspector.zig");
|
||||
const ExecutionWorld = @import("ExecutionWorld.zig");
|
||||
|
||||
const JsApis = bridge.JsApis;
|
||||
const Allocator = std.mem.Allocator;
|
||||
const ArenaAllocator = std.heap.ArenaAllocator;
|
||||
|
||||
// The Env maps to a V8 isolate, which represents a isolated sandbox for
|
||||
// executing JavaScript. The Env is where we'll define our V8 <-> Zig bindings,
|
||||
// and it's where we'll start ExecutionWorlds, which actually execute JavaScript.
|
||||
// The `S` parameter is arbitrary state. When we start an ExecutionWorld, an instance
|
||||
// of S must be given. This instance is available to any Zig binding.
|
||||
// The `types` parameter is a tuple of Zig structures we want to bind to V8.
|
||||
const Env = @This();
|
||||
|
||||
allocator: Allocator,
|
||||
|
||||
platform: *const Platform,
|
||||
|
||||
// the global isolate
|
||||
isolate: v8.Isolate,
|
||||
|
||||
// just kept around because we need to free it on deinit
|
||||
isolate_params: *v8.CreateParams,
|
||||
|
||||
context_id: usize,
|
||||
|
||||
// Dynamic slice to avoid circular dependency on JsApis.len at comptime
|
||||
templates: []v8.FunctionTemplate,
|
||||
|
||||
pub fn init(allocator: Allocator, platform: *const Platform, snapshot: *Snapshot) !Env {
|
||||
var params = try allocator.create(v8.CreateParams);
|
||||
errdefer allocator.destroy(params);
|
||||
v8.c.v8__Isolate__CreateParams__CONSTRUCT(params);
|
||||
params.snapshot_blob = @ptrCast(&snapshot.startup_data);
|
||||
|
||||
params.array_buffer_allocator = v8.createDefaultArrayBufferAllocator();
|
||||
errdefer v8.destroyArrayBufferAllocator(params.array_buffer_allocator.?);
|
||||
|
||||
params.external_references = &snapshot.external_references;
|
||||
|
||||
var isolate = v8.Isolate.init(params);
|
||||
errdefer isolate.deinit();
|
||||
|
||||
// This is the callback that runs whenever a module is dynamically imported.
|
||||
isolate.setHostImportModuleDynamicallyCallback(Context.dynamicModuleCallback);
|
||||
isolate.setPromiseRejectCallback(promiseRejectCallback);
|
||||
isolate.setMicrotasksPolicy(v8.c.kExplicit);
|
||||
|
||||
isolate.enter();
|
||||
errdefer isolate.exit();
|
||||
|
||||
isolate.setHostInitializeImportMetaObjectCallback(Context.metaObjectCallback);
|
||||
|
||||
// Allocate templates array dynamically to avoid comptime dependency on JsApis.len
|
||||
const templates = try allocator.alloc(v8.FunctionTemplate, JsApis.len);
|
||||
errdefer allocator.free(templates);
|
||||
|
||||
{
|
||||
var temp_scope: v8.HandleScope = undefined;
|
||||
v8.HandleScope.init(&temp_scope, isolate);
|
||||
defer temp_scope.deinit();
|
||||
const context = v8.Context.init(isolate, null, null);
|
||||
|
||||
context.enter();
|
||||
defer context.exit();
|
||||
|
||||
inline for (JsApis, 0..) |JsApi, i| {
|
||||
JsApi.Meta.class_id = i;
|
||||
const data = context.getDataFromSnapshotOnce(snapshot.data_start + i);
|
||||
const function = v8.FunctionTemplate{ .handle = @ptrCast(data) };
|
||||
templates[i] = v8.Persistent(v8.FunctionTemplate).init(isolate, function).castToFunctionTemplate();
|
||||
}
|
||||
}
|
||||
|
||||
return .{
|
||||
.context_id = 0,
|
||||
.isolate = isolate,
|
||||
.platform = platform,
|
||||
.allocator = allocator,
|
||||
.templates = templates,
|
||||
.isolate_params = params,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Env) void {
|
||||
self.isolate.exit();
|
||||
self.isolate.deinit();
|
||||
v8.destroyArrayBufferAllocator(self.isolate_params.array_buffer_allocator.?);
|
||||
self.allocator.destroy(self.isolate_params);
|
||||
self.allocator.free(self.templates);
|
||||
}
|
||||
|
||||
pub fn newInspector(self: *Env, arena: Allocator, ctx: anytype) !Inspector {
|
||||
return Inspector.init(arena, self.isolate, ctx);
|
||||
}
|
||||
|
||||
pub fn runMicrotasks(self: *const Env) void {
|
||||
self.isolate.performMicrotasksCheckpoint();
|
||||
}
|
||||
|
||||
pub fn pumpMessageLoop(self: *const Env) bool {
|
||||
return self.platform.inner.pumpMessageLoop(self.isolate, false);
|
||||
}
|
||||
|
||||
pub fn runIdleTasks(self: *const Env) void {
|
||||
return self.platform.inner.runIdleTasks(self.isolate, 1);
|
||||
}
|
||||
pub fn newExecutionWorld(self: *Env) !ExecutionWorld {
|
||||
return .{
|
||||
.env = self,
|
||||
.context = null,
|
||||
.context_arena = ArenaAllocator.init(self.allocator),
|
||||
};
|
||||
}
|
||||
|
||||
// V8 doesn't immediately free memory associated with
|
||||
// a Context, it's managed by the garbage collector. We use the
|
||||
// `lowMemoryNotification` call on the isolate to encourage v8 to free
|
||||
// any contexts which have been freed.
|
||||
pub fn lowMemoryNotification(self: *Env) void {
|
||||
var handle_scope: v8.HandleScope = undefined;
|
||||
v8.HandleScope.init(&handle_scope, self.isolate);
|
||||
defer handle_scope.deinit();
|
||||
self.isolate.lowMemoryNotification();
|
||||
}
|
||||
|
||||
pub fn dumpMemoryStats(self: *Env) void {
|
||||
const stats = self.isolate.getHeapStatistics();
|
||||
std.debug.print(
|
||||
\\ Total Heap Size: {d}
|
||||
\\ Total Heap Size Executable: {d}
|
||||
\\ Total Physical Size: {d}
|
||||
\\ Total Available Size: {d}
|
||||
\\ Used Heap Size: {d}
|
||||
\\ Heap Size Limit: {d}
|
||||
\\ Malloced Memory: {d}
|
||||
\\ External Memory: {d}
|
||||
\\ Peak Malloced Memory: {d}
|
||||
\\ Number Of Native Contexts: {d}
|
||||
\\ Number Of Detached Contexts: {d}
|
||||
\\ Total Global Handles Size: {d}
|
||||
\\ Used Global Handles Size: {d}
|
||||
\\ Zap Garbage: {any}
|
||||
\\
|
||||
, .{ stats.total_heap_size, stats.total_heap_size_executable, stats.total_physical_size, stats.total_available_size, stats.used_heap_size, stats.heap_size_limit, stats.malloced_memory, stats.external_memory, stats.peak_malloced_memory, stats.number_of_native_contexts, stats.number_of_detached_contexts, stats.total_global_handles_size, stats.used_global_handles_size, stats.does_zap_garbage });
|
||||
}
|
||||
|
||||
fn promiseRejectCallback(v8_msg: v8.C_PromiseRejectMessage) callconv(.c) void {
|
||||
const msg = v8.PromiseRejectMessage.initFromC(v8_msg);
|
||||
const isolate = msg.getPromise().toObject().getIsolate();
|
||||
const context = Context.fromIsolate(isolate);
|
||||
|
||||
const value =
|
||||
if (msg.getValue()) |v8_value|
|
||||
context.valueToString(v8_value, .{}) catch |err| @errorName(err)
|
||||
else
|
||||
"no value";
|
||||
|
||||
log.debug(.js, "unhandled rejection", .{
|
||||
.value = value,
|
||||
.stack = context.stackTrace() catch |err| @errorName(err) orelse "???",
|
||||
.note = "This should be updated to call window.unhandledrejection",
|
||||
});
|
||||
}
|
||||
208
src/browser/js/ExecutionWorld.zig
Normal file
208
src/browser/js/ExecutionWorld.zig
Normal file
@@ -0,0 +1,208 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
const log = @import("../../log.zig");
|
||||
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const Env = @import("Env.zig");
|
||||
const Context = @import("Context.zig");
|
||||
|
||||
const Page = @import("../Page.zig");
|
||||
|
||||
const ArenaAllocator = std.heap.ArenaAllocator;
|
||||
|
||||
const CONTEXT_ARENA_RETAIN = 1024 * 64;
|
||||
|
||||
// ExecutionWorld closely models a JS World.
|
||||
// https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/renderer/bindings/core/v8/V8BindingDesign.md#World
|
||||
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/ExecutionWorld
|
||||
const ExecutionWorld = @This();
|
||||
|
||||
env: *Env,
|
||||
|
||||
// Arena whose lifetime is for a single page load. Where
|
||||
// the call_arena lives for a single function call, the context_arena
|
||||
// lives for the lifetime of the entire page. The allocator will be
|
||||
// owned by the Context, but the arena itself is owned by the ExecutionWorld
|
||||
// so that we can re-use it from context to context.
|
||||
context_arena: ArenaAllocator,
|
||||
|
||||
// Currently a context maps to a Browser's Page. Here though, it's only a
|
||||
// mechanism to organization page-specific memory. The ExecutionWorld
|
||||
// does all the work, but having all page-specific data structures
|
||||
// grouped together helps keep things clean.
|
||||
context: ?Context = null,
|
||||
|
||||
// no init, must be initialized via env.newExecutionWorld()
|
||||
|
||||
pub fn deinit(self: *ExecutionWorld) void {
|
||||
if (self.context != null) {
|
||||
self.removeContext();
|
||||
}
|
||||
|
||||
self.context_arena.deinit();
|
||||
}
|
||||
|
||||
// Only the top Context in the Main ExecutionWorld should hold a handle_scope.
|
||||
// A v8.HandleScope is like an arena. Once created, any "Local" that
|
||||
// v8 creates will be released (or at least, releasable by the v8 GC)
|
||||
// when the handle_scope is freed.
|
||||
// We also maintain our own "context_arena" which allows us to have
|
||||
// all page related memory easily managed.
|
||||
pub fn createContext(self: *ExecutionWorld, page: *Page, enter: bool) !*Context {
|
||||
std.debug.assert(self.context == null);
|
||||
|
||||
const env = self.env;
|
||||
const isolate = env.isolate;
|
||||
const arena = self.context_arena.allocator();
|
||||
|
||||
var v8_context: v8.Context = blk: {
|
||||
var temp_scope: v8.HandleScope = undefined;
|
||||
v8.HandleScope.init(&temp_scope, isolate);
|
||||
defer temp_scope.deinit();
|
||||
|
||||
// Creates a global template that inherits from Window.
|
||||
const global_template = @import("Snapshot.zig").createGlobalTemplate(isolate, env.templates);
|
||||
|
||||
// Add the named property handler
|
||||
global_template.setNamedProperty(v8.NamedPropertyHandlerConfiguration{
|
||||
.getter = unknownPropertyCallback,
|
||||
.flags = v8.PropertyHandlerFlags.NonMasking | v8.PropertyHandlerFlags.OnlyInterceptStrings,
|
||||
}, null);
|
||||
|
||||
const context_local = v8.Context.init(isolate, global_template, null);
|
||||
const v8_context = v8.Persistent(v8.Context).init(isolate, context_local).castToContext();
|
||||
break :blk v8_context;
|
||||
};
|
||||
|
||||
// For a Page we only create one HandleScope, it is stored in the main World (enter==true). A page can have multple contexts, 1 for each World.
|
||||
// The main Context that enters and holds the HandleScope should therefore always be created first. Following other worlds for this page
|
||||
// like isolated Worlds, will thereby place their objects on the main page's HandleScope. Note: In the furure the number of context will multiply multiple frames support
|
||||
var handle_scope: ?v8.HandleScope = null;
|
||||
if (enter) {
|
||||
handle_scope = @as(v8.HandleScope, undefined);
|
||||
v8.HandleScope.init(&handle_scope.?, isolate);
|
||||
v8_context.enter();
|
||||
}
|
||||
errdefer if (enter) {
|
||||
v8_context.exit();
|
||||
handle_scope.?.deinit();
|
||||
};
|
||||
|
||||
const context_id = env.context_id;
|
||||
env.context_id = context_id + 1;
|
||||
|
||||
self.context = Context{
|
||||
.page = page,
|
||||
.id = context_id,
|
||||
.isolate = isolate,
|
||||
.v8_context = v8_context,
|
||||
.templates = env.templates,
|
||||
.handle_scope = handle_scope,
|
||||
.script_manager = &page._script_manager,
|
||||
.call_arena = page.call_arena,
|
||||
.arena = arena,
|
||||
};
|
||||
|
||||
var context = &self.context.?;
|
||||
// Store a pointer to our context inside the v8 context so that, given
|
||||
// a v8 context, we can get our context out
|
||||
const data = isolate.initBigIntU64(@intCast(@intFromPtr(context)));
|
||||
v8_context.setEmbedderData(1, data);
|
||||
|
||||
try context.setupGlobal();
|
||||
return context;
|
||||
}
|
||||
|
||||
pub fn removeContext(self: *ExecutionWorld) void {
|
||||
// Force running the micro task to drain the queue before reseting the
|
||||
// context arena.
|
||||
// Tasks in the queue are relying to the arena memory could be present in
|
||||
// the queue. Running them later could lead to invalid memory accesses.
|
||||
self.env.runMicrotasks();
|
||||
|
||||
self.context.?.deinit();
|
||||
self.context = null;
|
||||
_ = self.context_arena.reset(.{ .retain_with_limit = CONTEXT_ARENA_RETAIN });
|
||||
}
|
||||
|
||||
pub fn terminateExecution(self: *const ExecutionWorld) void {
|
||||
self.env.isolate.terminateExecution();
|
||||
}
|
||||
|
||||
pub fn resumeExecution(self: *const ExecutionWorld) void {
|
||||
self.env.isolate.cancelTerminateExecution();
|
||||
}
|
||||
|
||||
pub fn unknownPropertyCallback(c_name: ?*const v8.C_Name, raw_info: ?*const v8.C_PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const info = v8.PropertyCallbackInfo.initFromV8(raw_info);
|
||||
|
||||
const context = Context.fromIsolate(info.getIsolate());
|
||||
const maybe_property: ?[]u8 = context.valueToString(.{ .handle = c_name.? }, .{}) catch null;
|
||||
|
||||
const ignored = std.StaticStringMap(void).initComptime(.{
|
||||
.{ "process", {} },
|
||||
.{ "ShadyDOM", {} },
|
||||
.{ "ShadyCSS", {} },
|
||||
|
||||
.{ "litNonce", {} },
|
||||
.{ "litHtmlVersions", {} },
|
||||
.{ "litElementVersions", {} },
|
||||
.{ "litHtmlPolyfillSupport", {} },
|
||||
.{ "litElementHydrateSupport", {} },
|
||||
.{ "litElementPolyfillSupport", {} },
|
||||
.{ "reactiveElementVersions", {} },
|
||||
|
||||
.{ "recaptcha", {} },
|
||||
.{ "grecaptcha", {} },
|
||||
.{ "___grecaptcha_cfg", {} },
|
||||
.{ "__recaptcha_api", {} },
|
||||
.{ "__google_recaptcha_client", {} },
|
||||
|
||||
.{ "CLOSURE_FLAGS", {} },
|
||||
});
|
||||
|
||||
if (maybe_property) |prop| {
|
||||
if (!ignored.has(prop)) {
|
||||
const page = context.page;
|
||||
const document = page.document;
|
||||
|
||||
if (document.getElementById(prop, page)) |el| {
|
||||
const js_value = context.zigValueToJs(el, .{}) catch {
|
||||
return v8.Intercepted.No;
|
||||
};
|
||||
|
||||
info.getReturnValue().set(js_value);
|
||||
return v8.Intercepted.Yes;
|
||||
}
|
||||
|
||||
log.debug(.unknown_prop, "unknown global property", .{
|
||||
.info = "but the property can exist in pure JS",
|
||||
.stack = context.stackTrace() catch "???",
|
||||
.property = prop,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return v8.Intercepted.No;
|
||||
}
|
||||
189
src/browser/js/Function.zig
Normal file
189
src/browser/js/Function.zig
Normal file
@@ -0,0 +1,189 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const PersistentFunction = v8.Persistent(v8.Function);
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const Function = @This();
|
||||
|
||||
id: usize,
|
||||
context: *js.Context,
|
||||
this: ?v8.Object = null,
|
||||
func: PersistentFunction,
|
||||
|
||||
pub const Result = struct {
|
||||
stack: ?[]const u8,
|
||||
exception: []const u8,
|
||||
};
|
||||
|
||||
pub fn getName(self: *const Function, allocator: Allocator) ![]const u8 {
|
||||
const name = self.func.castToFunction().getName();
|
||||
return self.context.valueToString(name, .{ .allocator = allocator });
|
||||
}
|
||||
|
||||
pub fn setName(self: *const Function, name: []const u8) void {
|
||||
const v8_name = v8.String.initUtf8(self.context.isolate, name);
|
||||
self.func.castToFunction().setName(v8_name);
|
||||
}
|
||||
|
||||
pub fn withThis(self: *const Function, value: anytype) !Function {
|
||||
const this_obj = if (@TypeOf(value) == js.Object)
|
||||
value.js_obj
|
||||
else
|
||||
(try self.context.zigValueToJs(value, .{})).castTo(v8.Object);
|
||||
|
||||
return .{
|
||||
.id = self.id,
|
||||
.this = this_obj,
|
||||
.func = self.func,
|
||||
.context = self.context,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn newInstance(self: *const Function, result: *Result) !js.Object {
|
||||
const context = self.context;
|
||||
|
||||
var try_catch: js.TryCatch = undefined;
|
||||
try_catch.init(context);
|
||||
defer try_catch.deinit();
|
||||
|
||||
// This creates a new instance using this Function as a constructor.
|
||||
// This returns a generic Object
|
||||
const js_obj = self.func.castToFunction().initInstance(context.v8_context, &.{}) orelse {
|
||||
if (try_catch.hasCaught()) {
|
||||
const allocator = context.call_arena;
|
||||
result.stack = try_catch.stack(allocator) catch null;
|
||||
result.exception = (try_catch.exception(allocator) catch "???") orelse "???";
|
||||
} else {
|
||||
result.stack = null;
|
||||
result.exception = "???";
|
||||
}
|
||||
return error.JsConstructorFailed;
|
||||
};
|
||||
|
||||
return .{
|
||||
.context = context,
|
||||
.js_obj = js_obj,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn call(self: *const Function, comptime T: type, args: anytype) !T {
|
||||
return self.callWithThis(T, self.getThis(), args);
|
||||
}
|
||||
|
||||
pub fn tryCall(self: *const Function, comptime T: type, args: anytype, result: *Result) !T {
|
||||
return self.tryCallWithThis(T, self.getThis(), args, result);
|
||||
}
|
||||
|
||||
pub fn tryCallWithThis(self: *const Function, comptime T: type, this: anytype, args: anytype, result: *Result) !T {
|
||||
var try_catch: js.TryCatch = undefined;
|
||||
try_catch.init(self.context);
|
||||
defer try_catch.deinit();
|
||||
|
||||
return self.callWithThis(T, this, args) catch |err| {
|
||||
if (try_catch.hasCaught()) {
|
||||
const allocator = self.context.call_arena;
|
||||
result.stack = try_catch.stack(allocator) catch null;
|
||||
result.exception = (try_catch.exception(allocator) catch @errorName(err)) orelse @errorName(err);
|
||||
} else {
|
||||
result.stack = null;
|
||||
result.exception = @errorName(err);
|
||||
}
|
||||
return err;
|
||||
};
|
||||
}
|
||||
|
||||
pub fn callWithThis(self: *const Function, comptime T: type, this: anytype, args: anytype) !T {
|
||||
const context = self.context;
|
||||
|
||||
// When we're calling a function from within JavaScript itself, this isn't
|
||||
// necessary. We're within a Caller instantiation, which will already have
|
||||
// incremented the call_depth and it won't decrement it until the Caller is
|
||||
// done.
|
||||
// But some JS functions are initiated from Zig code, and not v8. For
|
||||
// example, Observers, some event and window callbacks. In those cases, we
|
||||
// need to increase the call_depth so that the call_arena remains valid for
|
||||
// the duration of the function call. If we don't do this, the call_arena
|
||||
// will be reset after each statement of the function which executes Zig code.
|
||||
const call_depth = context.call_depth;
|
||||
context.call_depth = call_depth + 1;
|
||||
defer context.call_depth = call_depth;
|
||||
|
||||
const js_this = blk: {
|
||||
if (@TypeOf(this) == v8.Object) {
|
||||
break :blk this;
|
||||
}
|
||||
|
||||
if (@TypeOf(this) == js.Object) {
|
||||
break :blk this.js_obj;
|
||||
}
|
||||
break :blk try context.zigValueToJs(this, .{});
|
||||
};
|
||||
|
||||
const aargs = if (comptime @typeInfo(@TypeOf(args)) == .null) struct {}{} else args;
|
||||
|
||||
const js_args: []const v8.Value = switch (@typeInfo(@TypeOf(aargs))) {
|
||||
.@"struct" => |s| blk: {
|
||||
const fields = s.fields;
|
||||
var js_args: [fields.len]v8.Value = undefined;
|
||||
inline for (fields, 0..) |f, i| {
|
||||
js_args[i] = try context.zigValueToJs(@field(aargs, f.name), .{});
|
||||
}
|
||||
const cargs: [fields.len]v8.Value = js_args;
|
||||
break :blk &cargs;
|
||||
},
|
||||
.pointer => blk: {
|
||||
var values = try context.call_arena.alloc(v8.Value, args.len);
|
||||
for (args, 0..) |a, i| {
|
||||
values[i] = try context.zigValueToJs(a, .{});
|
||||
}
|
||||
break :blk values;
|
||||
},
|
||||
else => @compileError("JS Function called with invalid paremter type"),
|
||||
};
|
||||
|
||||
const result = self.func.castToFunction().call(context.v8_context, js_this, js_args);
|
||||
if (result == null) {
|
||||
// std.debug.print("CB ERR: {s}\n", .{self.src() catch "???"});
|
||||
return error.JSExecCallback;
|
||||
}
|
||||
|
||||
if (@typeInfo(T) == .void) return {};
|
||||
return context.jsValueToZig(T, result.?);
|
||||
}
|
||||
|
||||
fn getThis(self: *const Function) v8.Object {
|
||||
return self.this orelse self.context.v8_context.getGlobal();
|
||||
}
|
||||
|
||||
pub fn src(self: *const Function) ![]const u8 {
|
||||
const value = self.func.castToFunction().toValue();
|
||||
return self.context.valueToString(value, .{});
|
||||
}
|
||||
|
||||
pub fn getPropertyValue(self: *const Function, name: []const u8) !?js.Value {
|
||||
const func_obj = self.func.castToFunction().toObject();
|
||||
const key = v8.String.initUtf8(self.context.isolate, name);
|
||||
const value = func_obj.getValue(self.context.v8_context, key) catch return null;
|
||||
return self.context.createValue(value);
|
||||
}
|
||||
162
src/browser/js/Inspector.zig
Normal file
162
src/browser/js/Inspector.zig
Normal file
@@ -0,0 +1,162 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const Context = @import("Context.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const Inspector = @This();
|
||||
|
||||
pub const RemoteObject = v8.RemoteObject;
|
||||
|
||||
isolate: v8.Isolate,
|
||||
inner: *v8.Inspector,
|
||||
session: v8.InspectorSession,
|
||||
|
||||
// We expect allocator to be an arena
|
||||
pub fn init(allocator: Allocator, isolate: v8.Isolate, ctx: anytype) !Inspector {
|
||||
const ContextT = @TypeOf(ctx);
|
||||
|
||||
const InspectorContainer = switch (@typeInfo(ContextT)) {
|
||||
.@"struct" => ContextT,
|
||||
.pointer => |ptr| ptr.child,
|
||||
.void => NoopInspector,
|
||||
else => @compileError("invalid context type"),
|
||||
};
|
||||
|
||||
// If necessary, turn a void context into something we can safely ptrCast
|
||||
const safe_context: *anyopaque = if (ContextT == void) @ptrCast(@constCast(&{})) else ctx;
|
||||
|
||||
const channel = v8.InspectorChannel.init(
|
||||
safe_context,
|
||||
InspectorContainer.onInspectorResponse,
|
||||
InspectorContainer.onInspectorEvent,
|
||||
InspectorContainer.onRunMessageLoopOnPause,
|
||||
InspectorContainer.onQuitMessageLoopOnPause,
|
||||
isolate,
|
||||
);
|
||||
|
||||
const client = v8.InspectorClient.init();
|
||||
|
||||
const inner = try allocator.create(v8.Inspector);
|
||||
v8.Inspector.init(inner, client, channel, isolate);
|
||||
return .{ .inner = inner, .isolate = isolate, .session = inner.connect() };
|
||||
}
|
||||
|
||||
pub fn deinit(self: *const Inspector) void {
|
||||
self.session.deinit();
|
||||
self.inner.deinit();
|
||||
}
|
||||
|
||||
pub fn send(self: *const Inspector, msg: []const u8) void {
|
||||
// Can't assume the main Context exists (with its HandleScope)
|
||||
// available when doing this. Pages (and thus the HandleScope)
|
||||
// comes and goes, but CDP can keep sending messages.
|
||||
const isolate = self.isolate;
|
||||
var temp_scope: v8.HandleScope = undefined;
|
||||
v8.HandleScope.init(&temp_scope, isolate);
|
||||
defer temp_scope.deinit();
|
||||
|
||||
self.session.dispatchProtocolMessage(isolate, msg);
|
||||
}
|
||||
|
||||
// From CDP docs
|
||||
// https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#type-ExecutionContextDescription
|
||||
// ----
|
||||
// - name: Human readable name describing given context.
|
||||
// - origin: Execution context origin (ie. URL who initialised the request)
|
||||
// - auxData: Embedder-specific auxiliary data likely matching
|
||||
// {isDefault: boolean, type: 'default'|'isolated'|'worker', frameId: string}
|
||||
// - is_default_context: Whether the execution context is default, should match the auxData
|
||||
pub fn contextCreated(
|
||||
self: *const Inspector,
|
||||
context: *const Context,
|
||||
name: []const u8,
|
||||
origin: []const u8,
|
||||
aux_data: ?[]const u8,
|
||||
is_default_context: bool,
|
||||
) void {
|
||||
self.inner.contextCreated(context.v8_context, name, origin, aux_data, is_default_context);
|
||||
}
|
||||
|
||||
// Retrieves the RemoteObject for a given value.
|
||||
// The value is loaded through the ExecutionWorld's mapZigInstanceToJs function,
|
||||
// just like a method return value. Therefore, if we've mapped this
|
||||
// value before, we'll get the existing JS PersistedObject and if not
|
||||
// we'll create it and track it for cleanup when the context ends.
|
||||
pub fn getRemoteObject(
|
||||
self: *const Inspector,
|
||||
context: *Context,
|
||||
group: []const u8,
|
||||
value: anytype,
|
||||
) !RemoteObject {
|
||||
const js_value = try context.zigValueToJs(value, .{});
|
||||
|
||||
// We do not want to expose this as a parameter for now
|
||||
const generate_preview = false;
|
||||
return self.session.wrapObject(
|
||||
context.isolate,
|
||||
context.v8_context,
|
||||
js_value,
|
||||
group,
|
||||
generate_preview,
|
||||
);
|
||||
}
|
||||
|
||||
// Gets a value by object ID regardless of which context it is in.
|
||||
// Our TaggedAnyOpaque stores the "resolved" ptr value (the most specific _type,
|
||||
// e.g. we store the ptr to the Div not the EventTarget). But, this is asking for
|
||||
// the pointer to the Node, so we need to use the same resolution mechanism which
|
||||
// is used when we're calling a function to turn the Div into a Node, which is
|
||||
// what Context.typeTaggedAnyOpaque does.
|
||||
pub fn getNodePtr(self: *const Inspector, allocator: Allocator, object_id: []const u8) !*anyopaque {
|
||||
const unwrapped = try self.session.unwrapObject(allocator, object_id);
|
||||
// The values context and groupId are not used here
|
||||
const js_val = unwrapped.value;
|
||||
if (js_val.isObject() == false) {
|
||||
return error.ObjectIdIsNotANode;
|
||||
}
|
||||
const Node = @import("../webapi/Node.zig");
|
||||
return Context.typeTaggedAnyOpaque(*Node, js_val.castTo(v8.Object)) catch {
|
||||
return error.ObjectIdIsNotANode;
|
||||
};
|
||||
}
|
||||
|
||||
const NoopInspector = struct {
|
||||
pub fn onInspectorResponse(_: *anyopaque, _: u32, _: []const u8) void {}
|
||||
pub fn onInspectorEvent(_: *anyopaque, _: []const u8) void {}
|
||||
pub fn onRunMessageLoopOnPause(_: *anyopaque, _: u32) void {}
|
||||
pub fn onQuitMessageLoopOnPause(_: *anyopaque) void {}
|
||||
};
|
||||
|
||||
pub fn getTaggedAnyOpaque(value: v8.Value) ?*js.TaggedAnyOpaque {
|
||||
if (value.isObject() == false) {
|
||||
return null;
|
||||
}
|
||||
const obj = value.castTo(v8.Object);
|
||||
if (obj.internalFieldCount() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const external_data = obj.getInternalField(0).castTo(v8.External).get().?;
|
||||
return @ptrCast(@alignCast(external_data));
|
||||
}
|
||||
176
src/browser/js/Object.zig
Normal file
176
src/browser/js/Object.zig
Normal file
@@ -0,0 +1,176 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
const Context = @import("Context.zig");
|
||||
const PersistentObject = v8.Persistent(v8.Object);
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const Object = @This();
|
||||
js_obj: v8.Object,
|
||||
context: *js.Context,
|
||||
|
||||
pub fn getId(self: Object) u32 {
|
||||
return self.js_obj.getIdentityHash();
|
||||
}
|
||||
|
||||
pub const SetOpts = packed struct(u32) {
|
||||
READ_ONLY: bool = false,
|
||||
DONT_ENUM: bool = false,
|
||||
DONT_DELETE: bool = false,
|
||||
_: u29 = 0,
|
||||
};
|
||||
pub fn setIndex(self: Object, index: u32, value: anytype, opts: SetOpts) !void {
|
||||
@setEvalBranchQuota(10000);
|
||||
const key = switch (index) {
|
||||
inline 0...20 => |i| std.fmt.comptimePrint("{d}", .{i}),
|
||||
else => try std.fmt.allocPrint(self.context.arena, "{d}", .{index}),
|
||||
};
|
||||
return self.set(key, value, opts);
|
||||
}
|
||||
|
||||
pub fn set(self: Object, key: []const u8, value: anytype, opts: SetOpts) error{ FailedToSet, OutOfMemory }!void {
|
||||
const context = self.context;
|
||||
|
||||
const js_key = v8.String.initUtf8(context.isolate, key);
|
||||
const js_value = try context.zigValueToJs(value, .{});
|
||||
|
||||
const res = self.js_obj.defineOwnProperty(context.v8_context, js_key.toName(), js_value, @bitCast(opts)) orelse false;
|
||||
if (!res) {
|
||||
return error.FailedToSet;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(self: Object, key: []const u8) !js.Value {
|
||||
const context = self.context;
|
||||
const js_key = v8.String.initUtf8(context.isolate, key);
|
||||
const js_val = try self.js_obj.getValue(context.v8_context, js_key);
|
||||
return context.createValue(js_val);
|
||||
}
|
||||
|
||||
pub fn isTruthy(self: Object) bool {
|
||||
const js_value = self.js_obj.toValue();
|
||||
return js_value.toBool(self.context.isolate);
|
||||
}
|
||||
|
||||
pub fn toString(self: Object) ![]const u8 {
|
||||
const js_value = self.js_obj.toValue();
|
||||
return self.context.valueToString(js_value, .{});
|
||||
}
|
||||
|
||||
pub fn format(self: Object, writer: *std.Io.Writer) !void {
|
||||
if (comptime IS_DEBUG) {
|
||||
return self.context.debugValue(self.js_obj.toValue(), writer);
|
||||
}
|
||||
const str = self.toString() catch return error.WriteFailed;
|
||||
return writer.writeAll(str);
|
||||
}
|
||||
|
||||
pub fn toJson(self: Object, allocator: Allocator) ![]u8 {
|
||||
const json_string = try v8.Json.stringify(self.context.v8_context, self.js_obj.toValue(), null);
|
||||
const str = try self.context.jsStringToZig(json_string, .{ .allocator = allocator });
|
||||
return str;
|
||||
}
|
||||
|
||||
pub fn persist(self: Object) !Object {
|
||||
var context = self.context;
|
||||
const js_obj = self.js_obj;
|
||||
|
||||
const persisted = PersistentObject.init(context.isolate, js_obj);
|
||||
try context.js_object_list.append(context.arena, persisted);
|
||||
|
||||
return .{
|
||||
.context = context,
|
||||
.js_obj = persisted.castToObject(),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn getFunction(self: Object, name: []const u8) !?js.Function {
|
||||
if (self.isNullOrUndefined()) {
|
||||
return null;
|
||||
}
|
||||
const context = self.context;
|
||||
|
||||
const js_name = v8.String.initUtf8(context.isolate, name);
|
||||
|
||||
const js_value = try self.js_obj.getValue(context.v8_context, js_name.toName());
|
||||
if (!js_value.isFunction()) {
|
||||
return null;
|
||||
}
|
||||
return try context.createFunction(js_value);
|
||||
}
|
||||
|
||||
pub fn callMethod(self: Object, comptime T: type, method_name: []const u8, args: anytype) !T {
|
||||
const func = try self.getFunction(method_name) orelse return error.MethodNotFound;
|
||||
return func.callWithThis(T, self, args);
|
||||
}
|
||||
|
||||
pub fn isNull(self: Object) bool {
|
||||
return self.js_obj.toValue().isNull();
|
||||
}
|
||||
|
||||
pub fn isUndefined(self: Object) bool {
|
||||
return self.js_obj.toValue().isUndefined();
|
||||
}
|
||||
|
||||
pub fn isNullOrUndefined(self: Object) bool {
|
||||
return self.js_obj.toValue().isNullOrUndefined();
|
||||
}
|
||||
|
||||
pub fn nameIterator(self: Object) NameIterator {
|
||||
const context = self.context;
|
||||
const js_obj = self.js_obj;
|
||||
|
||||
const array = js_obj.getPropertyNames(context.v8_context);
|
||||
const count = array.length();
|
||||
|
||||
return .{
|
||||
.count = count,
|
||||
.context = context,
|
||||
.js_obj = array.castTo(v8.Object),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn toZig(self: Object, comptime T: type) !T {
|
||||
return self.context.jsValueToZig(T, self.js_obj.toValue());
|
||||
}
|
||||
|
||||
pub const NameIterator = struct {
|
||||
count: u32,
|
||||
idx: u32 = 0,
|
||||
js_obj: v8.Object,
|
||||
context: *const Context,
|
||||
|
||||
pub fn next(self: *NameIterator) !?[]const u8 {
|
||||
const idx = self.idx;
|
||||
if (idx == self.count) {
|
||||
return null;
|
||||
}
|
||||
self.idx += 1;
|
||||
|
||||
const context = self.context;
|
||||
const js_val = try self.js_obj.getAtIndex(context.v8_context, idx);
|
||||
return try context.valueToString(js_val, .{});
|
||||
}
|
||||
};
|
||||
39
src/browser/js/Platform.zig
Normal file
39
src/browser/js/Platform.zig
Normal file
@@ -0,0 +1,39 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const Platform = @This();
|
||||
inner: v8.Platform,
|
||||
|
||||
pub fn init() !Platform {
|
||||
if (v8.initV8ICU() == false) {
|
||||
return error.FailedToInitializeICU;
|
||||
}
|
||||
const platform = v8.Platform.initDefault(0, true);
|
||||
v8.initV8Platform(platform);
|
||||
v8.initV8();
|
||||
return .{ .inner = platform };
|
||||
}
|
||||
|
||||
pub fn deinit(self: Platform) void {
|
||||
_ = v8.deinitV8();
|
||||
v8.deinitV8Platform();
|
||||
self.inner.deinit();
|
||||
}
|
||||
491
src/browser/js/Snapshot.zig
Normal file
491
src/browser/js/Snapshot.zig
Normal file
@@ -0,0 +1,491 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const bridge = @import("bridge.zig");
|
||||
const log = @import("../../log.zig");
|
||||
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
const Window = @import("../webapi/Window.zig");
|
||||
|
||||
const v8 = js.v8;
|
||||
const JsApis = bridge.JsApis;
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const Snapshot = @This();
|
||||
|
||||
const embedded_snapshot_blob = if (@import("build_config").snapshot_path) |path| @embedFile(path) else "";
|
||||
|
||||
// When creating our Snapshot, we use local function templates for every Zig type.
|
||||
// You cannot, from what I can tell, create persisted FunctionTemplates at
|
||||
// snapshot creation time. But you can embedd those templates (or any other v8
|
||||
// Data) so that it's available to contexts created from the snapshot. This is
|
||||
// the starting index of those function templates, which we can extract. At
|
||||
// creation time, in debug, we assert that this is actually a consecutive integer
|
||||
// sequence
|
||||
data_start: usize,
|
||||
|
||||
// The snapshot data (v8.StartupData is a ptr to the data and len).
|
||||
startup_data: v8.StartupData,
|
||||
|
||||
// V8 doesn't know how to serialize external references, and pretty much any hook
|
||||
// into Zig is an external reference (e.g. every accessor and function callback).
|
||||
// When we create the snapshot, we give it an array with the address of every
|
||||
// external reference. When we load the snapshot, we need to give it the same
|
||||
// array with the exact same number of entries in the same order (but, of course
|
||||
// cross-process, the value (address) might be different).
|
||||
external_references: [countExternalReferences()]isize,
|
||||
|
||||
// Track whether this snapshot owns its data (was created in-process)
|
||||
// If false, the data points into embedded_snapshot_blob and should not be freed
|
||||
owns_data: bool = false,
|
||||
|
||||
pub fn load(allocator: Allocator) !Snapshot {
|
||||
if (loadEmbedded()) |snapshot| {
|
||||
return snapshot;
|
||||
}
|
||||
return create(allocator);
|
||||
}
|
||||
|
||||
fn loadEmbedded() ?Snapshot {
|
||||
// Binary format: [data_start: usize][blob data]
|
||||
const min_size = @sizeOf(usize) + 1000;
|
||||
if (embedded_snapshot_blob.len < min_size) {
|
||||
// our blob should be in the MB, this is just a quick sanity check
|
||||
return null;
|
||||
}
|
||||
|
||||
const data_start = std.mem.readInt(usize, embedded_snapshot_blob[0..@sizeOf(usize)], .little);
|
||||
const blob = embedded_snapshot_blob[@sizeOf(usize)..];
|
||||
|
||||
const startup_data = v8.StartupData{ .data = blob.ptr, .raw_size = @intCast(blob.len) };
|
||||
if (!v8.SnapshotCreator.startupDataIsValid(startup_data)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return .{
|
||||
.owns_data = false,
|
||||
.data_start = data_start,
|
||||
.startup_data = startup_data,
|
||||
.external_references = collectExternalReferences(),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: Snapshot, allocator: Allocator) void {
|
||||
// Only free if we own the data (was created in-process)
|
||||
if (self.owns_data) {
|
||||
allocator.free(self.startup_data.data[0..@intCast(self.startup_data.raw_size)]);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(self: Snapshot, writer: *std.Io.Writer) !void {
|
||||
if (!self.isValid()) {
|
||||
return error.InvalidSnapshot;
|
||||
}
|
||||
|
||||
try writer.writeInt(usize, self.data_start, .little);
|
||||
try writer.writeAll(self.startup_data.data[0..@intCast(self.startup_data.raw_size)]);
|
||||
}
|
||||
|
||||
pub fn fromEmbedded(self: Snapshot) bool {
|
||||
// if the snapshot comes from the embedFile, then it'll be flagged as not
|
||||
// owneing (aka, not needing to free) the data.
|
||||
return self.owns_data == false;
|
||||
}
|
||||
|
||||
fn isValid(self: Snapshot) bool {
|
||||
return v8.SnapshotCreator.startupDataIsValid(self.startup_data);
|
||||
}
|
||||
|
||||
pub fn createGlobalTemplate(isolate: v8.Isolate, templates: []const v8.FunctionTemplate) v8.ObjectTemplate {
|
||||
// Set up the global template to inherit from Window's template
|
||||
// This way the global object gets all Window properties through inheritance
|
||||
const js_global = v8.FunctionTemplate.initDefault(isolate);
|
||||
js_global.setClassName(v8.String.initUtf8(isolate, "Window"));
|
||||
// Find Window in JsApis by name (avoids circular import)
|
||||
const window_index = comptime bridge.JsApiLookup.getId(Window.JsApi);
|
||||
js_global.inherit(templates[window_index]);
|
||||
return js_global.getInstanceTemplate();
|
||||
}
|
||||
|
||||
pub fn create(allocator: Allocator) !Snapshot {
|
||||
var external_references = collectExternalReferences();
|
||||
|
||||
var params = v8.initCreateParams();
|
||||
params.array_buffer_allocator = v8.createDefaultArrayBufferAllocator();
|
||||
defer v8.destroyArrayBufferAllocator(params.array_buffer_allocator.?);
|
||||
params.external_references = @ptrCast(&external_references);
|
||||
|
||||
var snapshot_creator: v8.SnapshotCreator = undefined;
|
||||
v8.SnapshotCreator.init(&snapshot_creator, ¶ms);
|
||||
defer snapshot_creator.deinit();
|
||||
|
||||
var data_start: usize = 0;
|
||||
const isolate = snapshot_creator.getIsolate();
|
||||
|
||||
{
|
||||
// CreateBlob, which we'll call once everything is setup, MUST NOT
|
||||
// be called from an active HandleScope. Hence we have this scope to
|
||||
// clean it up before we call CreateBlob
|
||||
var handle_scope: v8.HandleScope = undefined;
|
||||
v8.HandleScope.init(&handle_scope, isolate);
|
||||
defer handle_scope.deinit();
|
||||
|
||||
// Create templates (constructors only) FIRST
|
||||
var templates: [JsApis.len]v8.FunctionTemplate = undefined;
|
||||
inline for (JsApis, 0..) |JsApi, i| {
|
||||
@setEvalBranchQuota(10_000);
|
||||
templates[i] = generateConstructor(JsApi, isolate);
|
||||
attachClass(JsApi, isolate, templates[i]);
|
||||
}
|
||||
|
||||
// Set up prototype chains BEFORE attaching properties
|
||||
// This must come before attachClass so inheritance is set up first
|
||||
inline for (JsApis, 0..) |JsApi, i| {
|
||||
if (comptime protoIndexLookup(JsApi)) |proto_index| {
|
||||
templates[i].inherit(templates[proto_index]);
|
||||
}
|
||||
}
|
||||
|
||||
// Set up the global template to inherit from Window's template
|
||||
// This way the global object gets all Window properties through inheritance
|
||||
const global_template = createGlobalTemplate(isolate, templates[0..]);
|
||||
|
||||
const context = v8.Context.init(isolate, global_template, null);
|
||||
context.enter();
|
||||
defer context.exit();
|
||||
|
||||
// Add templates to context snapshot
|
||||
var last_data_index: usize = 0;
|
||||
inline for (JsApis, 0..) |_, i| {
|
||||
@setEvalBranchQuota(10_000);
|
||||
const data_index = snapshot_creator.addDataWithContext(context, @ptrCast(templates[i].handle));
|
||||
if (i == 0) {
|
||||
data_start = data_index;
|
||||
last_data_index = data_index;
|
||||
} else {
|
||||
// This isn't strictly required, but it means we only need to keep
|
||||
// the first data_index. This is based on the assumption that
|
||||
// addDataWithContext always increases by 1. If we ever hit this
|
||||
// error, then that assumption is wrong and we should capture
|
||||
// all the indexes explicitly in an array.
|
||||
if (data_index != last_data_index + 1) {
|
||||
return error.InvalidDataIndex;
|
||||
}
|
||||
last_data_index = data_index;
|
||||
}
|
||||
}
|
||||
|
||||
// Realize all templates by getting their functions and attaching to global
|
||||
const global_obj = context.getGlobal();
|
||||
|
||||
inline for (JsApis, 0..) |JsApi, i| {
|
||||
const func = templates[i].getFunction(context);
|
||||
|
||||
// Attach to global if it has a name
|
||||
if (@hasDecl(JsApi.Meta, "name")) {
|
||||
if (@hasDecl(JsApi.Meta, "constructor_alias")) {
|
||||
const v8_class_name = v8.String.initUtf8(isolate, JsApi.Meta.constructor_alias);
|
||||
_ = global_obj.setValue(context, v8_class_name, func);
|
||||
|
||||
// @TODO: This is wrong. This name should be registered with the
|
||||
// illegalConstructorCallback. I.e. new Image() is OK, but
|
||||
// new HTMLImageElement() isn't.
|
||||
// But we _have_ to register the name, i.e. HTMLImageElement
|
||||
// has to be registered so, for now, instead of creating another
|
||||
// template, we just hook it into the constructor.
|
||||
const illegal_class_name = v8.String.initUtf8(isolate, JsApi.Meta.name);
|
||||
_ = global_obj.setValue(context, illegal_class_name, func);
|
||||
} else {
|
||||
const v8_class_name = v8.String.initUtf8(isolate, JsApi.Meta.name);
|
||||
_ = global_obj.setValue(context, v8_class_name, func);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// If we want to overwrite the built-in console, we have to
|
||||
// delete the built-in one.
|
||||
const console_key = v8.String.initUtf8(isolate, "console");
|
||||
if (global_obj.deleteValue(context, console_key) == false) {
|
||||
return error.ConsoleDeleteError;
|
||||
}
|
||||
}
|
||||
|
||||
// This shouldn't be necessary, but it is:
|
||||
// https://groups.google.com/g/v8-users/c/qAQQBmbi--8
|
||||
// TODO: see if newer V8 engines have a way around this.
|
||||
inline for (JsApis, 0..) |JsApi, i| {
|
||||
if (comptime protoIndexLookup(JsApi)) |proto_index| {
|
||||
const proto_obj = templates[proto_index].getFunction(context).toObject();
|
||||
const self_obj = templates[i].getFunction(context).toObject();
|
||||
_ = self_obj.setPrototype(context, proto_obj);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
// Custom exception
|
||||
// TODO: this is an horrible hack, I can't figure out how to do this cleanly.
|
||||
const code = v8.String.initUtf8(isolate, "DOMException.prototype.__proto__ = Error.prototype");
|
||||
_ = try (try v8.Script.compile(context, code, null)).run(context);
|
||||
}
|
||||
|
||||
snapshot_creator.setDefaultContext(context);
|
||||
}
|
||||
|
||||
const blob = snapshot_creator.createBlob(v8.FunctionCodeHandling.kKeep);
|
||||
const owned = try allocator.dupe(u8, blob.data[0..@intCast(blob.raw_size)]);
|
||||
|
||||
return .{
|
||||
.owns_data = true,
|
||||
.data_start = data_start,
|
||||
.external_references = external_references,
|
||||
.startup_data = .{ .data = owned.ptr, .raw_size = @intCast(owned.len) },
|
||||
};
|
||||
}
|
||||
|
||||
// Count total callbacks needed for external_references array
|
||||
fn countExternalReferences() comptime_int {
|
||||
@setEvalBranchQuota(100_000);
|
||||
|
||||
// +1 for the illegal constructor callback
|
||||
var count: comptime_int = 1;
|
||||
|
||||
inline for (JsApis) |JsApi| {
|
||||
// Constructor (only if explicit)
|
||||
if (@hasDecl(JsApi, "constructor")) {
|
||||
count += 1;
|
||||
}
|
||||
|
||||
// Callable (htmldda)
|
||||
if (@hasDecl(JsApi, "callable")) {
|
||||
count += 1;
|
||||
}
|
||||
|
||||
// All other callbacks
|
||||
const declarations = @typeInfo(JsApi).@"struct".decls;
|
||||
inline for (declarations) |d| {
|
||||
const value = @field(JsApi, d.name);
|
||||
const T = @TypeOf(value);
|
||||
if (T == bridge.Accessor) {
|
||||
count += 1; // getter
|
||||
if (value.setter != null) count += 1; // setter
|
||||
} else if (T == bridge.Function) {
|
||||
count += 1;
|
||||
} else if (T == bridge.Iterator) {
|
||||
count += 1;
|
||||
} else if (T == bridge.Indexed) {
|
||||
count += 1;
|
||||
} else if (T == bridge.NamedIndexed) {
|
||||
count += 1; // getter
|
||||
if (value.setter != null) count += 1;
|
||||
if (value.deleter != null) count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count + 1; // +1 for null terminator
|
||||
}
|
||||
|
||||
fn collectExternalReferences() [countExternalReferences()]isize {
|
||||
var idx: usize = 0;
|
||||
var references = std.mem.zeroes([countExternalReferences()]isize);
|
||||
|
||||
references[idx] = @bitCast(@intFromPtr(&illegalConstructorCallback));
|
||||
idx += 1;
|
||||
|
||||
inline for (JsApis) |JsApi| {
|
||||
if (@hasDecl(JsApi, "constructor")) {
|
||||
references[idx] = @bitCast(@intFromPtr(JsApi.constructor.func));
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
if (@hasDecl(JsApi, "callable")) {
|
||||
references[idx] = @bitCast(@intFromPtr(JsApi.callable.func));
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
const declarations = @typeInfo(JsApi).@"struct".decls;
|
||||
inline for (declarations) |d| {
|
||||
const value = @field(JsApi, d.name);
|
||||
const T = @TypeOf(value);
|
||||
if (T == bridge.Accessor) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.getter));
|
||||
idx += 1;
|
||||
if (value.setter) |setter| {
|
||||
references[idx] = @bitCast(@intFromPtr(setter));
|
||||
idx += 1;
|
||||
}
|
||||
} else if (T == bridge.Function) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.func));
|
||||
idx += 1;
|
||||
} else if (T == bridge.Iterator) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.func));
|
||||
idx += 1;
|
||||
} else if (T == bridge.Indexed) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.getter));
|
||||
idx += 1;
|
||||
} else if (T == bridge.NamedIndexed) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.getter));
|
||||
idx += 1;
|
||||
if (value.setter) |setter| {
|
||||
references[idx] = @bitCast(@intFromPtr(setter));
|
||||
idx += 1;
|
||||
}
|
||||
if (value.deleter) |deleter| {
|
||||
references[idx] = @bitCast(@intFromPtr(deleter));
|
||||
idx += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return references;
|
||||
}
|
||||
|
||||
// Even if a struct doesn't have a `constructor` function, we still
|
||||
// `generateConstructor`, because this is how we create our
|
||||
// FunctionTemplate. Such classes exist, but they can't be instantiated
|
||||
// via `new ClassName()` - but they could, for example, be created in
|
||||
// Zig and returned from a function call, which is why we need the
|
||||
// FunctionTemplate.
|
||||
fn generateConstructor(comptime JsApi: type, isolate: v8.Isolate) v8.FunctionTemplate {
|
||||
const callback = blk: {
|
||||
if (@hasDecl(JsApi, "constructor")) {
|
||||
break :blk JsApi.constructor.func;
|
||||
}
|
||||
|
||||
// Use shared illegal constructor callback
|
||||
break :blk illegalConstructorCallback;
|
||||
};
|
||||
|
||||
const template = v8.FunctionTemplate.initCallback(isolate, callback);
|
||||
if (!@hasDecl(JsApi.Meta, "empty_with_no_proto")) {
|
||||
template.getInstanceTemplate().setInternalFieldCount(1);
|
||||
}
|
||||
const class_name = v8.String.initUtf8(isolate, if (@hasDecl(JsApi.Meta, "name")) JsApi.Meta.name else @typeName(JsApi));
|
||||
template.setClassName(class_name);
|
||||
return template;
|
||||
}
|
||||
|
||||
// Attaches JsApi members to the prototype template (normal case)
|
||||
fn attachClass(comptime JsApi: type, isolate: v8.Isolate, template: v8.FunctionTemplate) void {
|
||||
const target = template.getPrototypeTemplate();
|
||||
const declarations = @typeInfo(JsApi).@"struct".decls;
|
||||
inline for (declarations) |d| {
|
||||
const name: [:0]const u8 = d.name;
|
||||
const value = @field(JsApi, name);
|
||||
const definition = @TypeOf(value);
|
||||
|
||||
switch (definition) {
|
||||
bridge.Accessor => {
|
||||
const js_name = v8.String.initUtf8(isolate, name).toName();
|
||||
const getter_callback = v8.FunctionTemplate.initCallback(isolate, value.getter);
|
||||
if (value.setter == null) {
|
||||
if (value.static) {
|
||||
template.setAccessorGetter(js_name, getter_callback);
|
||||
} else {
|
||||
target.setAccessorGetter(js_name, getter_callback);
|
||||
}
|
||||
} else {
|
||||
std.debug.assert(value.static == false);
|
||||
const setter_callback = v8.FunctionTemplate.initCallback(isolate, value.setter);
|
||||
target.setAccessorGetterAndSetter(js_name, getter_callback, setter_callback);
|
||||
}
|
||||
},
|
||||
bridge.Function => {
|
||||
const function_template = v8.FunctionTemplate.initCallback(isolate, value.func);
|
||||
const js_name = v8.String.initUtf8(isolate, name).toName();
|
||||
if (value.static) {
|
||||
template.set(js_name, function_template, v8.PropertyAttribute.None);
|
||||
} else {
|
||||
target.set(js_name, function_template, v8.PropertyAttribute.None);
|
||||
}
|
||||
},
|
||||
bridge.Indexed => {
|
||||
const configuration = v8.IndexedPropertyHandlerConfiguration{
|
||||
.getter = value.getter,
|
||||
};
|
||||
target.setIndexedProperty(configuration, null);
|
||||
},
|
||||
bridge.NamedIndexed => template.getInstanceTemplate().setNamedProperty(.{
|
||||
.getter = value.getter,
|
||||
.setter = value.setter,
|
||||
.deleter = value.deleter,
|
||||
.flags = v8.PropertyHandlerFlags.OnlyInterceptStrings | v8.PropertyHandlerFlags.NonMasking,
|
||||
}, null),
|
||||
bridge.Iterator => {
|
||||
const function_template = v8.FunctionTemplate.initCallback(isolate, value.func);
|
||||
const js_name = if (value.async)
|
||||
v8.Symbol.getAsyncIterator(isolate).toName()
|
||||
else
|
||||
v8.Symbol.getIterator(isolate).toName();
|
||||
target.set(js_name, function_template, v8.PropertyAttribute.None);
|
||||
},
|
||||
bridge.Property => {
|
||||
const js_value = switch (value) {
|
||||
.int => |v| js.simpleZigValueToJs(isolate, v, true, false),
|
||||
};
|
||||
|
||||
const js_name = v8.String.initUtf8(isolate, name).toName();
|
||||
// apply it both to the type itself
|
||||
template.set(js_name, js_value, v8.PropertyAttribute.ReadOnly + v8.PropertyAttribute.DontDelete);
|
||||
|
||||
// and to instances of the type
|
||||
target.set(js_name, js_value, v8.PropertyAttribute.ReadOnly + v8.PropertyAttribute.DontDelete);
|
||||
},
|
||||
bridge.Constructor => {}, // already handled in generateConstructor
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
if (@hasDecl(JsApi.Meta, "htmldda")) {
|
||||
const instance_template = template.getInstanceTemplate();
|
||||
instance_template.markAsUndetectable();
|
||||
instance_template.setCallAsFunctionHandler(JsApi.Meta.callable.func);
|
||||
}
|
||||
|
||||
if (@hasDecl(JsApi.Meta, "name")) {
|
||||
const js_name = v8.Symbol.getToStringTag(isolate).toName();
|
||||
const instance_template = template.getInstanceTemplate();
|
||||
instance_template.set(js_name, v8.String.initUtf8(isolate, JsApi.Meta.name), v8.PropertyAttribute.ReadOnly + v8.PropertyAttribute.DontDelete);
|
||||
}
|
||||
}
|
||||
|
||||
fn protoIndexLookup(comptime JsApi: type) ?bridge.JsApiLookup.BackingInt {
|
||||
@setEvalBranchQuota(2000);
|
||||
comptime {
|
||||
const T = JsApi.bridge.type;
|
||||
if (!@hasField(T, "_proto")) {
|
||||
return null;
|
||||
}
|
||||
const Ptr = std.meta.fieldInfo(T, ._proto).type;
|
||||
const F = @typeInfo(Ptr).pointer.child;
|
||||
return bridge.JsApiLookup.getId(F.JsApi);
|
||||
}
|
||||
}
|
||||
|
||||
// Shared illegal constructor callback for types without explicit constructors
|
||||
fn illegalConstructorCallback(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.c) void {
|
||||
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
|
||||
const iso = info.getIsolate();
|
||||
log.warn(.js, "Illegal constructor call", .{});
|
||||
const js_exception = iso.throwException(js._createException(iso, "Illegal Constructor"));
|
||||
info.getReturnValue().set(js_exception);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (C) 2023-2024 Lightpanda (Selecy SAS)
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
@@ -16,25 +16,25 @@
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const generate = @import("../generate.zig");
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
|
||||
const DOMException = @import("exceptions.zig").DOMException;
|
||||
const EventTarget = @import("event_target.zig").EventTarget;
|
||||
const DOMImplementation = @import("implementation.zig").DOMImplementation;
|
||||
const NamedNodeMap = @import("namednodemap.zig").NamedNodeMap;
|
||||
const DOMTokenList = @import("token_list.zig").DOMTokenList;
|
||||
const NodeList = @import("nodelist.zig");
|
||||
const Nod = @import("node.zig");
|
||||
const MutationObserver = @import("mutation_observer.zig");
|
||||
// This only exists so that we know whether a function wants the opaque
|
||||
// JS argument (js.Object), or if it wants the receiver as an opaque
|
||||
// value.
|
||||
// js.Object is normally used when a method wants an opaque JS object
|
||||
// that it'll pass into a callback.
|
||||
// This is used when the function wants to do advanced manipulation
|
||||
// of the v8.Object bound to the instance. For example, postAttach is an
|
||||
// example of using This.
|
||||
|
||||
pub const Interfaces = generate.Tuple(.{
|
||||
DOMException,
|
||||
EventTarget,
|
||||
DOMImplementation,
|
||||
NamedNodeMap,
|
||||
DOMTokenList,
|
||||
NodeList.Interfaces,
|
||||
Nod.Node,
|
||||
Nod.Interfaces,
|
||||
MutationObserver.Interfaces,
|
||||
});
|
||||
const This = @This();
|
||||
obj: js.Object,
|
||||
|
||||
pub fn setIndex(self: This, index: u32, value: anytype, opts: js.Object.SetOpts) !void {
|
||||
return self.obj.setIndex(index, value, opts);
|
||||
}
|
||||
|
||||
pub fn set(self: This, key: []const u8, value: anytype, opts: js.Object.SetOpts) !void {
|
||||
return self.obj.set(key, value, opts);
|
||||
}
|
||||
82
src/browser/js/TryCatch.zig
Normal file
82
src/browser/js/TryCatch.zig
Normal file
@@ -0,0 +1,82 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const TryCatch = @This();
|
||||
|
||||
inner: v8.TryCatch,
|
||||
context: *const js.Context,
|
||||
|
||||
pub fn init(self: *TryCatch, context: *const js.Context) void {
|
||||
self.context = context;
|
||||
self.inner.init(context.isolate);
|
||||
}
|
||||
|
||||
pub fn hasCaught(self: TryCatch) bool {
|
||||
return self.inner.hasCaught();
|
||||
}
|
||||
|
||||
// the caller needs to deinit the string returned
|
||||
pub fn exception(self: TryCatch, allocator: Allocator) !?[]const u8 {
|
||||
const msg = self.inner.getException() orelse return null;
|
||||
return try self.context.valueToString(msg, .{ .allocator = allocator });
|
||||
}
|
||||
|
||||
// the caller needs to deinit the string returned
|
||||
pub fn stack(self: TryCatch, allocator: Allocator) !?[]const u8 {
|
||||
const context = self.context;
|
||||
const s = self.inner.getStackTrace(context.v8_context) orelse return null;
|
||||
return try context.valueToString(s, .{ .allocator = allocator });
|
||||
}
|
||||
|
||||
// the caller needs to deinit the string returned
|
||||
pub fn sourceLine(self: TryCatch, allocator: Allocator) !?[]const u8 {
|
||||
const context = self.context;
|
||||
const msg = self.inner.getMessage() orelse return null;
|
||||
const sl = msg.getSourceLine(context.v8_context) orelse return null;
|
||||
return try context.jsStringToZig(sl, .{ .allocator = allocator });
|
||||
}
|
||||
|
||||
pub fn sourceLineNumber(self: TryCatch) ?u32 {
|
||||
const context = self.context;
|
||||
const msg = self.inner.getMessage() orelse return null;
|
||||
return msg.getLineNumber(context.v8_context);
|
||||
}
|
||||
|
||||
// a shorthand method to return either the entire stack message
|
||||
// or just the exception message
|
||||
// - in Debug mode return the stack if available
|
||||
// - otherwise return the exception if available
|
||||
// the caller needs to deinit the string returned
|
||||
pub fn err(self: TryCatch, allocator: Allocator) !?[]const u8 {
|
||||
if (comptime @import("builtin").mode == .Debug) {
|
||||
if (try self.stack(allocator)) |msg| {
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
return try self.exception(allocator);
|
||||
}
|
||||
|
||||
pub fn deinit(self: *TryCatch) void {
|
||||
self.inner.deinit();
|
||||
}
|
||||
104
src/browser/js/Value.zig
Normal file
104
src/browser/js/Value.zig
Normal file
@@ -0,0 +1,104 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
|
||||
const v8 = js.v8;
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const PersistentValue = v8.Persistent(v8.Value);
|
||||
|
||||
const Value = @This();
|
||||
js_val: v8.Value,
|
||||
context: *js.Context,
|
||||
|
||||
pub fn isObject(self: Value) bool {
|
||||
return self.js_val.isObject();
|
||||
}
|
||||
|
||||
pub fn isString(self: Value) bool {
|
||||
return self.js_val.isString();
|
||||
}
|
||||
|
||||
pub fn isArray(self: Value) bool {
|
||||
return self.js_val.isArray();
|
||||
}
|
||||
|
||||
pub fn isNull(self: Value) bool {
|
||||
return self.js_val.isNull();
|
||||
}
|
||||
|
||||
pub fn isUndefined(self: Value) bool {
|
||||
return self.js_val.isUndefined();
|
||||
}
|
||||
|
||||
pub fn toString(self: Value, allocator: Allocator) ![]const u8 {
|
||||
return self.context.valueToString(self.js_val, .{ .allocator = allocator });
|
||||
}
|
||||
|
||||
pub fn fromJson(ctx: *js.Context, json: []const u8) !Value {
|
||||
const json_string = v8.String.initUtf8(ctx.isolate, json);
|
||||
const value = try v8.Json.parse(ctx.v8_context, json_string);
|
||||
return Value{ .context = ctx, .js_val = value };
|
||||
}
|
||||
|
||||
pub fn persist(self: Value) !Value {
|
||||
const js_val = self.js_val;
|
||||
var context = self.context;
|
||||
|
||||
const persisted = PersistentValue.init(context.isolate, js_val);
|
||||
try context.js_value_list.append(context.arena, persisted);
|
||||
|
||||
return Value{ .context = context, .js_val = persisted.toValue() };
|
||||
}
|
||||
|
||||
pub fn toZig(self: Value, comptime T: type) !T {
|
||||
return self.context.jsValueToZig(T, self.js_val);
|
||||
}
|
||||
|
||||
pub fn toObject(self: Value) js.Object {
|
||||
return .{
|
||||
.context = self.context,
|
||||
.js_obj = self.js_val.castTo(v8.Object),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn toArray(self: Value) js.Array {
|
||||
return .{
|
||||
.context = self.context,
|
||||
.js_arr = self.js_val.castTo(v8.Array),
|
||||
};
|
||||
}
|
||||
|
||||
// pub const Value = struct {
|
||||
// value: v8.Value,
|
||||
// context: *const Context,
|
||||
|
||||
// // the caller needs to deinit the string returned
|
||||
// pub fn toString(self: Value, allocator: Allocator) ![]const u8 {
|
||||
// return self.context.valueToString(self.value, .{ .allocator = allocator });
|
||||
// }
|
||||
|
||||
// pub fn fromJson(ctx: *Context, json: []const u8) !Value {
|
||||
// const json_string = v8.String.initUtf8(ctx.isolate, json);
|
||||
// const value = try v8.Json.parse(ctx.v8_context, json_string);
|
||||
// return Value{ .context = ctx, .value = value };
|
||||
// }
|
||||
// };
|
||||
620
src/browser/js/bridge.zig
Normal file
620
src/browser/js/bridge.zig
Normal file
@@ -0,0 +1,620 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const log = @import("../../log.zig");
|
||||
|
||||
const v8 = js.v8;
|
||||
|
||||
const Caller = @import("Caller.zig");
|
||||
|
||||
pub fn Builder(comptime T: type) type {
|
||||
return struct {
|
||||
pub const @"type" = T;
|
||||
pub const ClassId = u16;
|
||||
|
||||
pub fn constructor(comptime func: anytype, comptime opts: Constructor.Opts) Constructor {
|
||||
return Constructor.init(T, func, opts);
|
||||
}
|
||||
|
||||
pub fn accessor(comptime getter: anytype, comptime setter: anytype, comptime opts: Accessor.Opts) Accessor {
|
||||
return Accessor.init(T, getter, setter, opts);
|
||||
}
|
||||
|
||||
pub fn function(comptime func: anytype, comptime opts: Function.Opts) Function {
|
||||
return Function.init(T, func, opts);
|
||||
}
|
||||
|
||||
pub fn indexed(comptime getter_func: anytype, comptime opts: Indexed.Opts) Indexed {
|
||||
return Indexed.init(T, getter_func, opts);
|
||||
}
|
||||
|
||||
pub fn namedIndexed(comptime getter_func: anytype, setter_func: anytype, deleter_func: anytype, comptime opts: NamedIndexed.Opts) NamedIndexed {
|
||||
return NamedIndexed.init(T, getter_func, setter_func, deleter_func, opts);
|
||||
}
|
||||
|
||||
pub fn iterator(comptime func: anytype, comptime opts: Iterator.Opts) Iterator {
|
||||
return Iterator.init(T, func, opts);
|
||||
}
|
||||
|
||||
pub fn callable(comptime func: anytype, comptime opts: Callable.Opts) Callable {
|
||||
return Callable.init(T, func, opts);
|
||||
}
|
||||
|
||||
pub fn property(value: anytype) Property {
|
||||
switch (@typeInfo(@TypeOf(value))) {
|
||||
.comptime_int, .int => return .{ .int = value },
|
||||
else => {},
|
||||
}
|
||||
@compileError("Property for " ++ @typeName(@TypeOf(value)) ++ " hasn't been defined yet");
|
||||
}
|
||||
|
||||
pub fn prototypeChain() [prototypeChainLength(T)]js.PrototypeChainEntry {
|
||||
var entries: [prototypeChainLength(T)]js.PrototypeChainEntry = undefined;
|
||||
|
||||
entries[0] = .{ .offset = 0, .index = JsApiLookup.getId(T.JsApi) };
|
||||
|
||||
if (entries.len == 1) {
|
||||
return entries;
|
||||
}
|
||||
|
||||
var Prototype = T;
|
||||
inline for (entries[1..]) |*entry| {
|
||||
const Next = PrototypeType(Prototype).?;
|
||||
entry.* = .{
|
||||
.index = JsApiLookup.getId(Next.JsApi),
|
||||
.offset = @offsetOf(Prototype, "_proto"),
|
||||
};
|
||||
Prototype = Next;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub const Constructor = struct {
|
||||
func: *const fn (?*const v8.C_FunctionCallbackInfo) callconv(.c) void,
|
||||
|
||||
const Opts = struct {
|
||||
dom_exception: bool = false,
|
||||
};
|
||||
|
||||
fn init(comptime T: type, comptime func: anytype, comptime opts: Opts) Constructor {
|
||||
return .{ .func = struct {
|
||||
fn wrap(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.c) void {
|
||||
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
|
||||
var caller = Caller.init(info);
|
||||
defer caller.deinit();
|
||||
|
||||
caller.constructor(T, func, info, .{
|
||||
.dom_exception = opts.dom_exception,
|
||||
});
|
||||
}
|
||||
}.wrap };
|
||||
}
|
||||
};
|
||||
|
||||
pub const Function = struct {
|
||||
static: bool,
|
||||
func: *const fn (?*const v8.C_FunctionCallbackInfo) callconv(.c) void,
|
||||
|
||||
const Opts = struct {
|
||||
static: bool = false,
|
||||
dom_exception: bool = false,
|
||||
as_typed_array: bool = false,
|
||||
null_as_undefined: bool = false,
|
||||
};
|
||||
|
||||
fn init(comptime T: type, comptime func: anytype, comptime opts: Opts) Function {
|
||||
return .{
|
||||
.static = opts.static,
|
||||
.func = struct {
|
||||
fn wrap(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.c) void {
|
||||
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
|
||||
var caller = Caller.init(info);
|
||||
defer caller.deinit();
|
||||
|
||||
if (comptime opts.static) {
|
||||
caller.function(T, func, info, .{
|
||||
.dom_exception = opts.dom_exception,
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
} else {
|
||||
caller.method(T, func, info, .{
|
||||
.dom_exception = opts.dom_exception,
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}.wrap,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
pub const Accessor = struct {
|
||||
static: bool = false,
|
||||
getter: ?*const fn (?*const v8.C_FunctionCallbackInfo) callconv(.c) void = null,
|
||||
setter: ?*const fn (?*const v8.C_FunctionCallbackInfo) callconv(.c) void = null,
|
||||
|
||||
const Opts = struct {
|
||||
static: bool = false,
|
||||
cache: ?[]const u8 = null, // @ZIGDOM
|
||||
as_typed_array: bool = false,
|
||||
null_as_undefined: bool = false,
|
||||
};
|
||||
|
||||
fn init(comptime T: type, comptime getter: anytype, comptime setter: anytype, comptime opts: Opts) Accessor {
|
||||
var accessor = Accessor{
|
||||
.static = opts.static,
|
||||
};
|
||||
|
||||
if (@typeInfo(@TypeOf(getter)) != .null) {
|
||||
accessor.getter = struct {
|
||||
fn wrap(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.c) void {
|
||||
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
|
||||
var caller = Caller.init(info);
|
||||
defer caller.deinit();
|
||||
|
||||
caller.method(T, getter, info, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap;
|
||||
}
|
||||
|
||||
if (@typeInfo(@TypeOf(setter)) != .null) {
|
||||
accessor.setter = struct {
|
||||
fn wrap(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.c) void {
|
||||
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
|
||||
std.debug.assert(info.length() == 1);
|
||||
|
||||
var caller = Caller.init(info);
|
||||
defer caller.deinit();
|
||||
|
||||
caller.method(T, setter, info, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap;
|
||||
}
|
||||
|
||||
return accessor;
|
||||
}
|
||||
};
|
||||
|
||||
pub const Indexed = struct {
|
||||
getter: *const fn (idx: u32, raw_info: ?*const v8.C_PropertyCallbackInfo) callconv(.c) u8,
|
||||
|
||||
const Opts = struct {
|
||||
as_typed_array: bool = false,
|
||||
null_as_undefined: bool = false,
|
||||
};
|
||||
|
||||
fn init(comptime T: type, comptime getter: anytype, comptime opts: Opts) Indexed {
|
||||
return .{ .getter = struct {
|
||||
fn wrap(idx: u32, raw_info: ?*const v8.C_PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const info = v8.PropertyCallbackInfo.initFromV8(raw_info);
|
||||
var caller = Caller.init(info);
|
||||
defer caller.deinit();
|
||||
return caller.getIndex(T, getter, idx, info, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap };
|
||||
}
|
||||
};
|
||||
|
||||
pub const NamedIndexed = struct {
|
||||
getter: *const fn (c_name: ?*const v8.C_Name, raw_info: ?*const v8.C_PropertyCallbackInfo) callconv(.c) u8,
|
||||
setter: ?*const fn (c_name: ?*const v8.C_Name, c_value: ?*const v8.C_Value, raw_info: ?*const v8.C_PropertyCallbackInfo) callconv(.c) u8 = null,
|
||||
deleter: ?*const fn (c_name: ?*const v8.C_Name, raw_info: ?*const v8.C_PropertyCallbackInfo) callconv(.c) u8 = null,
|
||||
|
||||
const Opts = struct {
|
||||
as_typed_array: bool = false,
|
||||
null_as_undefined: bool = false,
|
||||
};
|
||||
|
||||
fn init(comptime T: type, comptime getter: anytype, setter: anytype, deleter: anytype, comptime opts: Opts) NamedIndexed {
|
||||
const getter_fn = struct {
|
||||
fn wrap(c_name: ?*const v8.C_Name, raw_info: ?*const v8.C_PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const info = v8.PropertyCallbackInfo.initFromV8(raw_info);
|
||||
var caller = Caller.init(info);
|
||||
defer caller.deinit();
|
||||
return caller.getNamedIndex(T, getter, .{ .handle = c_name.? }, info, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap;
|
||||
|
||||
const setter_fn = if (@typeInfo(@TypeOf(setter)) == .null) null else struct {
|
||||
fn wrap(c_name: ?*const v8.C_Name, c_value: ?*const v8.C_Value, raw_info: ?*const v8.C_PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const info = v8.PropertyCallbackInfo.initFromV8(raw_info);
|
||||
var caller = Caller.init(info);
|
||||
defer caller.deinit();
|
||||
|
||||
return caller.setNamedIndex(T, setter, .{ .handle = c_name.? }, .{ .handle = c_value.? }, info, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap;
|
||||
|
||||
const deleter_fn = if (@typeInfo(@TypeOf(deleter)) == .null) null else struct {
|
||||
fn wrap(c_name: ?*const v8.C_Name, raw_info: ?*const v8.C_PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const info = v8.PropertyCallbackInfo.initFromV8(raw_info);
|
||||
var caller = Caller.init(info);
|
||||
defer caller.deinit();
|
||||
|
||||
return caller.deleteNamedIndex(T, deleter, .{ .handle = c_name.? }, info, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap;
|
||||
|
||||
return .{
|
||||
.getter = getter_fn,
|
||||
.setter = setter_fn,
|
||||
.deleter = deleter_fn,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
pub const Iterator = struct {
|
||||
func: *const fn (?*const v8.C_FunctionCallbackInfo) callconv(.c) void,
|
||||
async: bool,
|
||||
|
||||
const Opts = struct {
|
||||
async: bool = false,
|
||||
null_as_undefined: bool = false,
|
||||
};
|
||||
|
||||
fn init(comptime T: type, comptime struct_or_func: anytype, comptime opts: Opts) Iterator {
|
||||
if (@typeInfo(@TypeOf(struct_or_func)) == .type) {
|
||||
return .{
|
||||
.async = opts.async,
|
||||
.func = struct {
|
||||
fn wrap(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.c) void {
|
||||
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
|
||||
info.getReturnValue().set(info.getThis());
|
||||
}
|
||||
}.wrap,
|
||||
};
|
||||
}
|
||||
|
||||
return .{
|
||||
.async = opts.async,
|
||||
.func = struct {
|
||||
fn wrap(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.c) void {
|
||||
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
|
||||
var caller = Caller.init(info);
|
||||
defer caller.deinit();
|
||||
caller.method(T, struct_or_func, info, .{});
|
||||
}
|
||||
}.wrap,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
pub const Callable = struct {
|
||||
func: *const fn (?*const v8.C_FunctionCallbackInfo) callconv(.c) void,
|
||||
|
||||
const Opts = struct {
|
||||
null_as_undefined: bool = false,
|
||||
};
|
||||
|
||||
fn init(comptime T: type, comptime func: anytype, comptime opts: Opts) Callable {
|
||||
return .{ .func = struct {
|
||||
fn wrap(raw_info: ?*const v8.C_FunctionCallbackInfo) callconv(.c) void {
|
||||
const info = v8.FunctionCallbackInfo.initFromV8(raw_info);
|
||||
var caller = Caller.init(info);
|
||||
defer caller.deinit();
|
||||
caller.method(T, func, info, .{
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap };
|
||||
}
|
||||
};
|
||||
|
||||
pub const Property = union(enum) {
|
||||
int: i64,
|
||||
};
|
||||
|
||||
// Given a Type, returns the length of the prototype chain, including self
|
||||
fn prototypeChainLength(comptime T: type) usize {
|
||||
var l: usize = 1;
|
||||
var Next = T;
|
||||
while (PrototypeType(Next)) |N| {
|
||||
Next = N;
|
||||
l += 1;
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
// Given a Type, gets its prototype Type (if any)
|
||||
fn PrototypeType(comptime T: type) ?type {
|
||||
if (!@hasField(T, "_proto")) {
|
||||
return null;
|
||||
}
|
||||
return Struct(std.meta.fieldInfo(T, ._proto).type);
|
||||
}
|
||||
|
||||
fn flattenTypes(comptime Types: []const type) [countFlattenedTypes(Types)]type {
|
||||
var index: usize = 0;
|
||||
var flat: [countFlattenedTypes(Types)]type = undefined;
|
||||
for (Types) |T| {
|
||||
if (@hasDecl(T, "registerTypes")) {
|
||||
for (T.registerTypes()) |TT| {
|
||||
flat[index] = TT.JsApi;
|
||||
index += 1;
|
||||
}
|
||||
} else {
|
||||
flat[index] = T.JsApi;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
return flat;
|
||||
}
|
||||
|
||||
fn countFlattenedTypes(comptime Types: []const type) usize {
|
||||
var c: usize = 0;
|
||||
for (Types) |T| {
|
||||
c += if (@hasDecl(T, "registerTypes")) T.registerTypes().len else 1;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
// T => T
|
||||
// *T => T
|
||||
pub fn Struct(comptime T: type) type {
|
||||
return switch (@typeInfo(T)) {
|
||||
.@"struct" => T,
|
||||
.pointer => |ptr| ptr.child,
|
||||
else => @compileError("Expecting Struct or *Struct, got: " ++ @typeName(T)),
|
||||
};
|
||||
}
|
||||
|
||||
pub const JsApiLookup = struct {
|
||||
/// Integer type we use for `JsApiLookup` enum. Can be u8 at min.
|
||||
pub const BackingInt = std.math.IntFittingRange(0, @max(std.math.maxInt(u8), JsApis.len));
|
||||
|
||||
/// Imagine we have a type `Cat` which has a getter:
|
||||
///
|
||||
/// fn get_owner(self: *Cat) *Owner {
|
||||
/// return self.owner;
|
||||
/// }
|
||||
///
|
||||
/// When we execute `caller.getter`, we'll end up doing something like:
|
||||
///
|
||||
/// const res = @call(.auto, Cat.get_owner, .{cat_instance});
|
||||
///
|
||||
/// How do we turn `res`, which is an *Owner, into something we can return
|
||||
/// to v8? We need the ObjectTemplate associated with Owner. How do we
|
||||
/// get that? Well, we store all the ObjectTemplates in an array that's
|
||||
/// tied to env. So we do something like:
|
||||
///
|
||||
/// env.templates[index_of_owner].initInstance(...);
|
||||
///
|
||||
/// But how do we get that `index_of_owner`? `Index` is an enum
|
||||
/// that looks like:
|
||||
///
|
||||
/// pub const Enum = enum(BackingInt) {
|
||||
/// cat = 0,
|
||||
/// owner = 1,
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// (`BackingInt` is calculated at comptime regarding to interfaces we have)
|
||||
/// So to get the template index of `owner`, simply do:
|
||||
///
|
||||
/// const index_id = types.getId(@TypeOf(res));
|
||||
///
|
||||
pub const Enum = blk: {
|
||||
var fields: [JsApis.len]std.builtin.Type.EnumField = undefined;
|
||||
for (JsApis, 0..) |JsApi, i| {
|
||||
fields[i] = .{ .name = @typeName(JsApi), .value = i };
|
||||
}
|
||||
|
||||
break :blk @Type(.{
|
||||
.@"enum" = .{
|
||||
.fields = &fields,
|
||||
.tag_type = BackingInt,
|
||||
.is_exhaustive = true,
|
||||
.decls = &.{},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
/// Returns a boolean indicating if a type exist in the lookup.
|
||||
pub inline fn has(t: type) bool {
|
||||
return @hasField(Enum, @typeName(t));
|
||||
}
|
||||
|
||||
/// Returns the `Enum` for the given type.
|
||||
pub inline fn getIndex(t: type) Enum {
|
||||
return @field(Enum, @typeName(t));
|
||||
}
|
||||
|
||||
/// Returns the ID for the given type.
|
||||
pub inline fn getId(t: type) BackingInt {
|
||||
return @intFromEnum(getIndex(t));
|
||||
}
|
||||
};
|
||||
|
||||
pub const SubType = enum {
|
||||
@"error",
|
||||
array,
|
||||
arraybuffer,
|
||||
dataview,
|
||||
date,
|
||||
generator,
|
||||
iterator,
|
||||
map,
|
||||
node,
|
||||
promise,
|
||||
proxy,
|
||||
regexp,
|
||||
set,
|
||||
typedarray,
|
||||
wasmvalue,
|
||||
weakmap,
|
||||
weakset,
|
||||
webassemblymemory,
|
||||
};
|
||||
|
||||
pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/AbortController.zig"),
|
||||
@import("../webapi/AbortSignal.zig"),
|
||||
@import("../webapi/CData.zig"),
|
||||
@import("../webapi/cdata/Comment.zig"),
|
||||
@import("../webapi/cdata/Text.zig"),
|
||||
@import("../webapi/cdata/CDATASection.zig"),
|
||||
@import("../webapi/cdata/ProcessingInstruction.zig"),
|
||||
@import("../webapi/collections.zig"),
|
||||
@import("../webapi/Console.zig"),
|
||||
@import("../webapi/Crypto.zig"),
|
||||
@import("../webapi/CSS.zig"),
|
||||
@import("../webapi/css/CSSRule.zig"),
|
||||
@import("../webapi/css/CSSRuleList.zig"),
|
||||
@import("../webapi/css/CSSStyleDeclaration.zig"),
|
||||
@import("../webapi/css/CSSStyleRule.zig"),
|
||||
@import("../webapi/css/CSSStyleSheet.zig"),
|
||||
@import("../webapi/css/CSSStyleProperties.zig"),
|
||||
@import("../webapi/css/MediaQueryList.zig"),
|
||||
@import("../webapi/css/StyleSheetList.zig"),
|
||||
@import("../webapi/Document.zig"),
|
||||
@import("../webapi/HTMLDocument.zig"),
|
||||
@import("../webapi/XMLDocument.zig"),
|
||||
@import("../webapi/History.zig"),
|
||||
@import("../webapi/KeyValueList.zig"),
|
||||
@import("../webapi/DocumentFragment.zig"),
|
||||
@import("../webapi/DocumentType.zig"),
|
||||
@import("../webapi/ShadowRoot.zig"),
|
||||
@import("../webapi/DOMException.zig"),
|
||||
@import("../webapi/DOMImplementation.zig"),
|
||||
@import("../webapi/DOMTreeWalker.zig"),
|
||||
@import("../webapi/DOMNodeIterator.zig"),
|
||||
@import("../webapi/DOMRect.zig"),
|
||||
@import("../webapi/DOMParser.zig"),
|
||||
@import("../webapi/XMLSerializer.zig"),
|
||||
@import("../webapi/AbstractRange.zig"),
|
||||
@import("../webapi/Range.zig"),
|
||||
@import("../webapi/NodeFilter.zig"),
|
||||
@import("../webapi/Element.zig"),
|
||||
@import("../webapi/element/DOMStringMap.zig"),
|
||||
@import("../webapi/element/Attribute.zig"),
|
||||
@import("../webapi/element/Html.zig"),
|
||||
@import("../webapi/element/html/IFrame.zig"),
|
||||
@import("../webapi/element/html/Anchor.zig"),
|
||||
@import("../webapi/element/html/Audio.zig"),
|
||||
@import("../webapi/element/html/Body.zig"),
|
||||
@import("../webapi/element/html/BR.zig"),
|
||||
@import("../webapi/element/html/Button.zig"),
|
||||
@import("../webapi/element/html/Canvas.zig"),
|
||||
@import("../webapi/element/html/Custom.zig"),
|
||||
@import("../webapi/element/html/Data.zig"),
|
||||
@import("../webapi/element/html/Dialog.zig"),
|
||||
@import("../webapi/element/html/Div.zig"),
|
||||
@import("../webapi/element/html/Embed.zig"),
|
||||
@import("../webapi/element/html/Form.zig"),
|
||||
@import("../webapi/element/html/Generic.zig"),
|
||||
@import("../webapi/element/html/Head.zig"),
|
||||
@import("../webapi/element/html/Heading.zig"),
|
||||
@import("../webapi/element/html/HR.zig"),
|
||||
@import("../webapi/element/html/Html.zig"),
|
||||
@import("../webapi/element/html/Image.zig"),
|
||||
@import("../webapi/element/html/Input.zig"),
|
||||
@import("../webapi/element/html/LI.zig"),
|
||||
@import("../webapi/element/html/Link.zig"),
|
||||
@import("../webapi/element/html/Media.zig"),
|
||||
@import("../webapi/element/html/Meta.zig"),
|
||||
@import("../webapi/element/html/OL.zig"),
|
||||
@import("../webapi/element/html/Option.zig"),
|
||||
@import("../webapi/element/html/Paragraph.zig"),
|
||||
@import("../webapi/element/html/Script.zig"),
|
||||
@import("../webapi/element/html/Select.zig"),
|
||||
@import("../webapi/element/html/Slot.zig"),
|
||||
@import("../webapi/element/html/Style.zig"),
|
||||
@import("../webapi/element/html/Template.zig"),
|
||||
@import("../webapi/element/html/TextArea.zig"),
|
||||
@import("../webapi/element/html/Title.zig"),
|
||||
@import("../webapi/element/html/Video.zig"),
|
||||
@import("../webapi/element/html/UL.zig"),
|
||||
@import("../webapi/element/html/Unknown.zig"),
|
||||
@import("../webapi/element/Svg.zig"),
|
||||
@import("../webapi/element/svg/Generic.zig"),
|
||||
@import("../webapi/encoding/TextDecoder.zig"),
|
||||
@import("../webapi/encoding/TextEncoder.zig"),
|
||||
@import("../webapi/Event.zig"),
|
||||
@import("../webapi/event/CompositionEvent.zig"),
|
||||
@import("../webapi/event/CustomEvent.zig"),
|
||||
@import("../webapi/event/ErrorEvent.zig"),
|
||||
@import("../webapi/event/MessageEvent.zig"),
|
||||
@import("../webapi/event/ProgressEvent.zig"),
|
||||
@import("../webapi/event/NavigationCurrentEntryChangeEvent.zig"),
|
||||
@import("../webapi/event/PageTransitionEvent.zig"),
|
||||
@import("../webapi/event/PopStateEvent.zig"),
|
||||
@import("../webapi/event/UIEvent.zig"),
|
||||
@import("../webapi/event/MouseEvent.zig"),
|
||||
@import("../webapi/event/KeyboardEvent.zig"),
|
||||
@import("../webapi/MessageChannel.zig"),
|
||||
@import("../webapi/MessagePort.zig"),
|
||||
@import("../webapi/media/MediaError.zig"),
|
||||
@import("../webapi/media/TextTrackCue.zig"),
|
||||
@import("../webapi/media/VTTCue.zig"),
|
||||
@import("../webapi/animation/Animation.zig"),
|
||||
@import("../webapi/EventTarget.zig"),
|
||||
@import("../webapi/Location.zig"),
|
||||
@import("../webapi/Navigator.zig"),
|
||||
@import("../webapi/net/FormData.zig"),
|
||||
@import("../webapi/net/Headers.zig"),
|
||||
@import("../webapi/net/Request.zig"),
|
||||
@import("../webapi/net/Response.zig"),
|
||||
@import("../webapi/net/URLSearchParams.zig"),
|
||||
@import("../webapi/net/XMLHttpRequest.zig"),
|
||||
@import("../webapi/net/XMLHttpRequestEventTarget.zig"),
|
||||
@import("../webapi/streams/ReadableStream.zig"),
|
||||
@import("../webapi/streams/ReadableStreamDefaultReader.zig"),
|
||||
@import("../webapi/streams/ReadableStreamDefaultController.zig"),
|
||||
@import("../webapi/Node.zig"),
|
||||
@import("../webapi/storage/storage.zig"),
|
||||
@import("../webapi/URL.zig"),
|
||||
@import("../webapi/Window.zig"),
|
||||
@import("../webapi/Performance.zig"),
|
||||
@import("../webapi/MutationObserver.zig"),
|
||||
@import("../webapi/IntersectionObserver.zig"),
|
||||
@import("../webapi/CustomElementRegistry.zig"),
|
||||
@import("../webapi/ResizeObserver.zig"),
|
||||
@import("../webapi/IdleDeadline.zig"),
|
||||
@import("../webapi/Blob.zig"),
|
||||
@import("../webapi/File.zig"),
|
||||
@import("../webapi/Screen.zig"),
|
||||
@import("../webapi/PerformanceObserver.zig"),
|
||||
@import("../webapi/navigation/Navigation.zig"),
|
||||
@import("../webapi/navigation/NavigationEventTarget.zig"),
|
||||
@import("../webapi/navigation/NavigationHistoryEntry.zig"),
|
||||
@import("../webapi/navigation/NavigationActivation.zig"),
|
||||
});
|
||||
513
src/browser/js/js.zig
Normal file
513
src/browser/js/js.zig
Normal file
@@ -0,0 +1,513 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
pub const v8 = @import("v8");
|
||||
|
||||
const log = @import("../../log.zig");
|
||||
|
||||
pub const Env = @import("Env.zig");
|
||||
pub const bridge = @import("bridge.zig");
|
||||
pub const ExecutionWorld = @import("ExecutionWorld.zig");
|
||||
pub const Context = @import("Context.zig");
|
||||
pub const Inspector = @import("Inspector.zig");
|
||||
pub const Snapshot = @import("Snapshot.zig");
|
||||
pub const Platform = @import("Platform.zig");
|
||||
|
||||
// TODO: Is "This" really necessary?
|
||||
pub const This = @import("This.zig");
|
||||
pub const Value = @import("Value.zig");
|
||||
pub const Array = @import("Array.zig");
|
||||
pub const Object = @import("Object.zig");
|
||||
pub const TryCatch = @import("TryCatch.zig");
|
||||
pub const Function = @import("Function.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub fn Bridge(comptime T: type) type {
|
||||
return bridge.Builder(T);
|
||||
}
|
||||
|
||||
// If a function returns a []i32, should that map to a plain-old
|
||||
// JavaScript array, or a Int32Array? It's ambiguous. By default, we'll
|
||||
// map arrays/slices to the JavaScript arrays. If you want a TypedArray
|
||||
// wrap it in this.
|
||||
// Also, this type has nothing to do with the Env. But we place it here
|
||||
// for consistency. Want a callback? Env.Callback. Want a JsObject?
|
||||
// Env.JsObject. Want a TypedArray? Env.TypedArray.
|
||||
pub fn TypedArray(comptime T: type) type {
|
||||
return struct {
|
||||
values: []const T,
|
||||
|
||||
pub fn dupe(self: TypedArray(T), allocator: Allocator) !TypedArray(T) {
|
||||
return .{ .values = try allocator.dupe(T, self.values) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub const ArrayBuffer = struct {
|
||||
values: []const u8,
|
||||
|
||||
pub fn dupe(self: ArrayBuffer, allocator: Allocator) !ArrayBuffer {
|
||||
return .{ .values = try allocator.dupe(u8, self.values) };
|
||||
}
|
||||
};
|
||||
|
||||
pub const PromiseResolver = struct {
|
||||
context: *Context,
|
||||
resolver: v8.PromiseResolver,
|
||||
|
||||
pub fn promise(self: PromiseResolver) Promise {
|
||||
return self.resolver.getPromise();
|
||||
}
|
||||
|
||||
pub fn resolve(self: PromiseResolver, comptime source: []const u8, value: anytype) void {
|
||||
self._resolve(value) catch |err| {
|
||||
log.err(.bug, "resolve", .{ .source = source, .err = err, .persistent = false });
|
||||
};
|
||||
}
|
||||
fn _resolve(self: PromiseResolver, value: anytype) !void {
|
||||
const context = self.context;
|
||||
const js_value = try context.zigValueToJs(value, .{});
|
||||
|
||||
if (self.resolver.resolve(context.v8_context, js_value) == null) {
|
||||
return error.FailedToResolvePromise;
|
||||
}
|
||||
self.context.runMicrotasks();
|
||||
}
|
||||
|
||||
pub fn reject(self: PromiseResolver, comptime source: []const u8, value: anytype) void {
|
||||
self._reject(value) catch |err| {
|
||||
log.err(.bug, "reject", .{ .source = source, .err = err, .persistent = false });
|
||||
};
|
||||
}
|
||||
fn _reject(self: PromiseResolver, value: anytype) !void {
|
||||
const context = self.context;
|
||||
const js_value = try context.zigValueToJs(value);
|
||||
|
||||
if (self.resolver.reject(context.v8_context, js_value) == null) {
|
||||
return error.FailedToRejectPromise;
|
||||
}
|
||||
self.context.runMicrotasks();
|
||||
}
|
||||
};
|
||||
|
||||
pub const PersistentPromiseResolver = struct {
|
||||
context: *Context,
|
||||
resolver: v8.Persistent(v8.PromiseResolver),
|
||||
|
||||
pub fn deinit(self: *PersistentPromiseResolver) void {
|
||||
self.resolver.deinit();
|
||||
}
|
||||
|
||||
pub fn promise(self: PersistentPromiseResolver) Promise {
|
||||
return self.resolver.castToPromiseResolver().getPromise();
|
||||
}
|
||||
|
||||
pub fn resolve(self: PersistentPromiseResolver, comptime source: []const u8, value: anytype) void {
|
||||
self._resolve(value) catch |err| {
|
||||
log.err(.bug, "resolve", .{ .source = source, .err = err, .persistent = true });
|
||||
};
|
||||
}
|
||||
fn _resolve(self: PersistentPromiseResolver, value: anytype) !void {
|
||||
const context = self.context;
|
||||
const js_value = try context.zigValueToJs(value, .{});
|
||||
defer context.runMicrotasks();
|
||||
|
||||
if (self.resolver.castToPromiseResolver().resolve(context.v8_context, js_value) == null) {
|
||||
return error.FailedToResolvePromise;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reject(self: PersistentPromiseResolver, comptime source: []const u8, value: anytype) void {
|
||||
self._reject(value) catch |err| {
|
||||
log.err(.bug, "reject", .{ .source = source, .err = err, .persistent = true });
|
||||
};
|
||||
}
|
||||
|
||||
fn _reject(self: PersistentPromiseResolver, value: anytype) !void {
|
||||
const context = self.context;
|
||||
const js_value = try context.zigValueToJs(value, .{});
|
||||
defer context.runMicrotasks();
|
||||
|
||||
// resolver.reject will return null if the promise isn't pending
|
||||
if (self.resolver.castToPromiseResolver().reject(context.v8_context, js_value) == null) {
|
||||
return error.FailedToRejectPromise;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
pub const Promise = v8.Promise;
|
||||
|
||||
// When doing jsValueToZig, string ([]const u8) are managed by the
|
||||
// call_arena. That means that if the API wants to persist the string
|
||||
// (which is relatively common), it needs to dupe it again.
|
||||
// If the parameter is an Env.String rather than a []const u8, then
|
||||
// the page's arena will be used (rather than the call arena).
|
||||
pub const String = struct {
|
||||
string: []const u8,
|
||||
};
|
||||
|
||||
pub const Exception = struct {
|
||||
inner: v8.Value,
|
||||
context: *const Context,
|
||||
|
||||
// the caller needs to deinit the string returned
|
||||
pub fn exception(self: Exception, allocator: Allocator) ![]const u8 {
|
||||
return self.context.valueToString(self.inner, .{ .allocator = allocator });
|
||||
}
|
||||
};
|
||||
|
||||
pub fn UndefinedOr(comptime T: type) type {
|
||||
return union(enum) {
|
||||
undefined: void,
|
||||
value: T,
|
||||
};
|
||||
}
|
||||
|
||||
// An interface for types that want to have their jsScopeEnd function be
|
||||
// called when the call context ends
|
||||
const CallScopeEndCallback = struct {
|
||||
ptr: *anyopaque,
|
||||
callScopeEndFn: *const fn (ptr: *anyopaque) void,
|
||||
|
||||
fn init(ptr: anytype) CallScopeEndCallback {
|
||||
const T = @TypeOf(ptr);
|
||||
const ptr_info = @typeInfo(T);
|
||||
|
||||
const gen = struct {
|
||||
pub fn callScopeEnd(pointer: *anyopaque) void {
|
||||
const self: T = @ptrCast(@alignCast(pointer));
|
||||
return ptr_info.pointer.child.jsCallScopeEnd(self);
|
||||
}
|
||||
};
|
||||
|
||||
return .{
|
||||
.ptr = ptr,
|
||||
.callScopeEndFn = gen.callScopeEnd,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn callScopeEnd(self: CallScopeEndCallback) void {
|
||||
self.callScopeEndFn(self.ptr);
|
||||
}
|
||||
};
|
||||
|
||||
// Callback called on global's property missing.
|
||||
// Return true to intercept the execution or false to let the call
|
||||
// continue the chain.
|
||||
pub const GlobalMissingCallback = struct {
|
||||
ptr: *anyopaque,
|
||||
missingFn: *const fn (ptr: *anyopaque, name: []const u8, ctx: *Context) bool,
|
||||
|
||||
pub fn init(ptr: anytype) GlobalMissingCallback {
|
||||
const T = @TypeOf(ptr);
|
||||
const ptr_info = @typeInfo(T);
|
||||
|
||||
const gen = struct {
|
||||
pub fn missing(pointer: *anyopaque, name: []const u8, ctx: *Context) bool {
|
||||
const self: T = @ptrCast(@alignCast(pointer));
|
||||
return ptr_info.pointer.child.missing(self, name, ctx);
|
||||
}
|
||||
};
|
||||
|
||||
return .{
|
||||
.ptr = ptr,
|
||||
.missingFn = gen.missing,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn missing(self: GlobalMissingCallback, name: []const u8, ctx: *Context) bool {
|
||||
return self.missingFn(self.ptr, name, ctx);
|
||||
}
|
||||
};
|
||||
|
||||
// Attributes that return a primitive type are setup directly on the
|
||||
// FunctionTemplate when the Env is setup. More complex types need a v8.Context
|
||||
// and cannot be set directly on the FunctionTemplate.
|
||||
// We default to saying types are primitives because that's mostly what
|
||||
// we have. If we add a new complex type that isn't explictly handled here,
|
||||
// we'll get a compiler error in simpleZigValueToJs, and can then explicitly
|
||||
// add the type here.
|
||||
pub fn isComplexAttributeType(ti: std.builtin.Type) bool {
|
||||
return switch (ti) {
|
||||
.array => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
// These are simple types that we can convert to JS with only an isolate. This
|
||||
// is separated from the Caller's zigValueToJs to make it available when we
|
||||
// don't have a caller (i.e., when setting static attributes on types)
|
||||
pub fn simpleZigValueToJs(isolate: v8.Isolate, value: anytype, comptime fail: bool, comptime null_as_undefined: bool) if (fail) v8.Value else ?v8.Value {
|
||||
switch (@typeInfo(@TypeOf(value))) {
|
||||
.void => return v8.initUndefined(isolate).toValue(),
|
||||
.null => if (comptime null_as_undefined) return v8.initUndefined(isolate).toValue() else return v8.initNull(isolate).toValue(),
|
||||
.bool => return v8.getValue(if (value) v8.initTrue(isolate) else v8.initFalse(isolate)),
|
||||
.int => |n| switch (n.signedness) {
|
||||
.signed => {
|
||||
if (value > 0 and value <= 4_294_967_295) {
|
||||
return v8.Integer.initU32(isolate, @intCast(value)).toValue();
|
||||
}
|
||||
if (value >= -2_147_483_648 and value <= 2_147_483_647) {
|
||||
return v8.Integer.initI32(isolate, @intCast(value)).toValue();
|
||||
}
|
||||
if (comptime n.bits <= 64) {
|
||||
return v8.getValue(v8.BigInt.initI64(isolate, @intCast(value)));
|
||||
}
|
||||
@compileError(@typeName(value) ++ " is not supported");
|
||||
},
|
||||
.unsigned => {
|
||||
if (value <= 4_294_967_295) {
|
||||
return v8.Integer.initU32(isolate, @intCast(value)).toValue();
|
||||
}
|
||||
if (comptime n.bits <= 64) {
|
||||
return v8.getValue(v8.BigInt.initU64(isolate, @intCast(value)));
|
||||
}
|
||||
@compileError(@typeName(value) ++ " is not supported");
|
||||
},
|
||||
},
|
||||
.comptime_int => {
|
||||
if (value >= 0) {
|
||||
if (value <= 4_294_967_295) {
|
||||
return v8.Integer.initU32(isolate, @intCast(value)).toValue();
|
||||
}
|
||||
return v8.BigInt.initU64(isolate, @intCast(value)).toValue();
|
||||
}
|
||||
if (value >= -2_147_483_648) {
|
||||
return v8.Integer.initI32(isolate, @intCast(value)).toValue();
|
||||
}
|
||||
return v8.BigInt.initI64(isolate, @intCast(value)).toValue();
|
||||
},
|
||||
.comptime_float => return v8.Number.init(isolate, value).toValue(),
|
||||
.float => |f| switch (f.bits) {
|
||||
64 => return v8.Number.init(isolate, value).toValue(),
|
||||
32 => return v8.Number.init(isolate, @floatCast(value)).toValue(),
|
||||
else => @compileError(@typeName(value) ++ " is not supported"),
|
||||
},
|
||||
.pointer => |ptr| {
|
||||
if (ptr.size == .slice and ptr.child == u8) {
|
||||
return v8.String.initUtf8(isolate, value).toValue();
|
||||
}
|
||||
if (ptr.size == .one) {
|
||||
const one_info = @typeInfo(ptr.child);
|
||||
if (one_info == .array and one_info.array.child == u8) {
|
||||
return v8.String.initUtf8(isolate, value).toValue();
|
||||
}
|
||||
}
|
||||
},
|
||||
.array => return simpleZigValueToJs(isolate, &value, fail, null_as_undefined),
|
||||
.optional => {
|
||||
if (value) |v| {
|
||||
return simpleZigValueToJs(isolate, v, fail, null_as_undefined);
|
||||
}
|
||||
if (comptime null_as_undefined) {
|
||||
return v8.initUndefined(isolate).toValue();
|
||||
}
|
||||
return v8.initNull(isolate).toValue();
|
||||
},
|
||||
.@"struct" => {
|
||||
switch (@TypeOf(value)) {
|
||||
ArrayBuffer => {
|
||||
const values = value.values;
|
||||
const len = values.len;
|
||||
var array_buffer: v8.ArrayBuffer = undefined;
|
||||
const backing_store = v8.BackingStore.init(isolate, len);
|
||||
const data: [*]u8 = @ptrCast(@alignCast(backing_store.getData()));
|
||||
@memcpy(data[0..len], @as([]const u8, @ptrCast(values))[0..len]);
|
||||
array_buffer = v8.ArrayBuffer.initWithBackingStore(isolate, &backing_store.toSharedPtr());
|
||||
|
||||
return .{ .handle = array_buffer.handle };
|
||||
},
|
||||
// zig fmt: off
|
||||
TypedArray(u8), TypedArray(u16), TypedArray(u32), TypedArray(u64),
|
||||
TypedArray(i8), TypedArray(i16), TypedArray(i32), TypedArray(i64),
|
||||
TypedArray(f32), TypedArray(f64),
|
||||
// zig fmt: on
|
||||
=> {
|
||||
const values = value.values;
|
||||
const value_type = @typeInfo(@TypeOf(values)).pointer.child;
|
||||
const len = values.len;
|
||||
const bits = switch (@typeInfo(value_type)) {
|
||||
.int => |n| n.bits,
|
||||
.float => |f| f.bits,
|
||||
else => @compileError("Invalid TypeArray type: " ++ @typeName(value_type)),
|
||||
};
|
||||
|
||||
var array_buffer: v8.ArrayBuffer = undefined;
|
||||
if (len == 0) {
|
||||
array_buffer = v8.ArrayBuffer.init(isolate, 0);
|
||||
} else {
|
||||
const buffer_len = len * bits / 8;
|
||||
const backing_store = v8.BackingStore.init(isolate, buffer_len);
|
||||
const data: [*]u8 = @ptrCast(@alignCast(backing_store.getData()));
|
||||
@memcpy(data[0..buffer_len], @as([]const u8, @ptrCast(values))[0..buffer_len]);
|
||||
array_buffer = v8.ArrayBuffer.initWithBackingStore(isolate, &backing_store.toSharedPtr());
|
||||
}
|
||||
|
||||
switch (@typeInfo(value_type)) {
|
||||
.int => |n| switch (n.signedness) {
|
||||
.unsigned => switch (n.bits) {
|
||||
8 => return v8.Uint8Array.init(array_buffer, 0, len).toValue(),
|
||||
16 => return v8.Uint16Array.init(array_buffer, 0, len).toValue(),
|
||||
32 => return v8.Uint32Array.init(array_buffer, 0, len).toValue(),
|
||||
64 => return v8.BigUint64Array.init(array_buffer, 0, len).toValue(),
|
||||
else => {},
|
||||
},
|
||||
.signed => switch (n.bits) {
|
||||
8 => return v8.Int8Array.init(array_buffer, 0, len).toValue(),
|
||||
16 => return v8.Int16Array.init(array_buffer, 0, len).toValue(),
|
||||
32 => return v8.Int32Array.init(array_buffer, 0, len).toValue(),
|
||||
64 => return v8.BigInt64Array.init(array_buffer, 0, len).toValue(),
|
||||
else => {},
|
||||
},
|
||||
},
|
||||
.float => |f| switch (f.bits) {
|
||||
32 => return v8.Float32Array.init(array_buffer, 0, len).toValue(),
|
||||
64 => return v8.Float64Array.init(array_buffer, 0, len).toValue(),
|
||||
else => {},
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
// We normally don't fail in this function unless fail == true
|
||||
// but this can never be valid.
|
||||
@compileError("Invalid TypeArray type: " ++ @typeName(value_type));
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
},
|
||||
.@"union" => return simpleZigValueToJs(isolate, std.meta.activeTag(value), fail, null_as_undefined),
|
||||
.@"enum" => {
|
||||
const T = @TypeOf(value);
|
||||
if (@hasDecl(T, "toString")) {
|
||||
return simpleZigValueToJs(isolate, value.toString(), fail, null_as_undefined);
|
||||
}
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
if (fail) {
|
||||
@compileError("Unsupported Zig type " ++ @typeName(@TypeOf(value)));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
pub fn _createException(isolate: v8.Isolate, msg: []const u8) v8.Value {
|
||||
return v8.Exception.initError(v8.String.initUtf8(isolate, msg));
|
||||
}
|
||||
|
||||
pub fn classNameForStruct(comptime Struct: type) []const u8 {
|
||||
if (@hasDecl(Struct, "js_name")) {
|
||||
return Struct.js_name;
|
||||
}
|
||||
@setEvalBranchQuota(10_000);
|
||||
const full_name = @typeName(Struct);
|
||||
const last = std.mem.lastIndexOfScalar(u8, full_name, '.') orelse return full_name;
|
||||
return full_name[last + 1 ..];
|
||||
}
|
||||
|
||||
// When we return a Zig object to V8, we put it on the heap and pass it into
|
||||
// v8 as an *anyopaque (i.e. void *). When V8 gives us back the value, say, as a
|
||||
// function parameter, we know what type it _should_ be.
|
||||
//
|
||||
// In a simple/perfect world, we could use this knowledge to cast the *anyopaque
|
||||
// to the parameter type:
|
||||
// const arg: @typeInfo(@TypeOf(function)).@"fn".params[0] = @ptrCast(v8_data);
|
||||
//
|
||||
// But there are 2 reasons we can't do that.
|
||||
//
|
||||
// == Reason 1 ==
|
||||
// The JS code might pass the wrong type:
|
||||
//
|
||||
// var cat = new Cat();
|
||||
// cat.setOwner(new Cat());
|
||||
//
|
||||
// The zig_setOwner method expects the 2nd parameter to be an *Owner, but
|
||||
// the JS code passed a *Cat.
|
||||
//
|
||||
// To solve this issue, we tag every returned value so that we can check what
|
||||
// type it is. In the above case, we'd expect an *Owner, but the tag would tell
|
||||
// us that we got a *Cat. We use the type index in our Types lookup as the tag.
|
||||
//
|
||||
// == Reason 2 ==
|
||||
// Because of prototype inheritance, even "correct" code can be a challenge. For
|
||||
// example, say the above JavaScript is fixed:
|
||||
//
|
||||
// var cat = new Cat();
|
||||
// cat.setOwner(new Owner("Leto"));
|
||||
//
|
||||
// The issue is that setOwner might not expect an *Owner, but rather a
|
||||
// *Person, which is the prototype for Owner. Now our Zig code is expecting
|
||||
// a *Person, but it was (correctly) given an *Owner.
|
||||
// For this reason, we also store the prototype chain.
|
||||
pub const TaggedAnyOpaque = struct {
|
||||
prototype_len: u16,
|
||||
prototype_chain: [*]const PrototypeChainEntry,
|
||||
|
||||
// Ptr to the Zig instance. Between the context where it's called (i.e.
|
||||
// we have the comptime parameter info for all functions), and the index field
|
||||
// we can figure out what type this is.
|
||||
value: *anyopaque,
|
||||
|
||||
// When we're asked to describe an object via the Inspector, we _must_ include
|
||||
// the proper subtype (and description) fields in the returned JSON.
|
||||
// V8 will give us a Value and ask us for the subtype. From the v8.Value we
|
||||
// can get a v8.Object, and from the v8.Object, we can get out TaggedAnyOpaque
|
||||
// which is where we store the subtype.
|
||||
subtype: ?bridge.SubType,
|
||||
};
|
||||
|
||||
pub const PrototypeChainEntry = struct {
|
||||
index: bridge.JsApiLookup.BackingInt,
|
||||
offset: u16, // offset to the _proto field
|
||||
};
|
||||
|
||||
// These are here, and not in Inspector.zig, because Inspector.zig isn't always
|
||||
// included (e.g. in the wpt build).
|
||||
|
||||
// This is called from V8. Whenever the v8 inspector has to describe a value
|
||||
// it'll call this function to gets its [optional] subtype - which, from V8's
|
||||
// point of view, is an arbitrary string.
|
||||
pub export fn v8_inspector__Client__IMPL__valueSubtype(
|
||||
_: *v8.c.InspectorClientImpl,
|
||||
c_value: *const v8.C_Value,
|
||||
) callconv(.c) [*c]const u8 {
|
||||
const external_entry = Inspector.getTaggedAnyOpaque(.{ .handle = c_value }) orelse return null;
|
||||
return if (external_entry.subtype) |st| @tagName(st) else null;
|
||||
}
|
||||
|
||||
// Same as valueSubType above, but for the optional description field.
|
||||
// From what I can tell, some drivers _need_ the description field to be
|
||||
// present, even if it's empty. So if we have a subType for the value, we'll
|
||||
// put an empty description.
|
||||
pub export fn v8_inspector__Client__IMPL__descriptionForValueSubtype(
|
||||
_: *v8.c.InspectorClientImpl,
|
||||
v8_context: *const v8.C_Context,
|
||||
c_value: *const v8.C_Value,
|
||||
) callconv(.c) [*c]const u8 {
|
||||
_ = v8_context;
|
||||
|
||||
// We _must_ include a non-null description in order for the subtype value
|
||||
// to be included. Besides that, I don't know if the value has any meaning
|
||||
const external_entry = Inspector.getTaggedAnyOpaque(.{ .handle = c_value }) orelse return null;
|
||||
return if (external_entry.subtype == null) null else "";
|
||||
}
|
||||
|
||||
test "TaggedAnyOpaque" {
|
||||
// If we grow this, fine, but it should be a conscious decision
|
||||
try std.testing.expectEqual(24, @sizeOf(TaggedAnyOpaque));
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
// Copyright (C) 2023-2024 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const Client = @import("../http/Client.zig");
|
||||
|
||||
const user_agent = "Lightpanda.io/1.0";
|
||||
|
||||
pub const Loader = struct {
|
||||
client: Client,
|
||||
// use 64KB for headers buffer size.
|
||||
server_header_buffer: [1024 * 64]u8 = undefined,
|
||||
|
||||
pub const Response = struct {
|
||||
alloc: std.mem.Allocator,
|
||||
req: *Client.Request,
|
||||
|
||||
pub fn deinit(self: *Response) void {
|
||||
self.req.deinit();
|
||||
self.alloc.destroy(self.req);
|
||||
}
|
||||
};
|
||||
|
||||
pub fn init(alloc: std.mem.Allocator) Loader {
|
||||
return Loader{
|
||||
.client = Client{
|
||||
.allocator = alloc,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Loader) void {
|
||||
self.client.deinit();
|
||||
}
|
||||
|
||||
// see
|
||||
// https://ziglang.org/documentation/master/std/#A;std:http.Client.fetch
|
||||
// for reference.
|
||||
// The caller is responsible for calling `deinit()` on the `Response`.
|
||||
pub fn get(self: *Loader, alloc: std.mem.Allocator, uri: std.Uri) !Response {
|
||||
var resp = Response{
|
||||
.alloc = alloc,
|
||||
.req = try alloc.create(Client.Request),
|
||||
};
|
||||
errdefer alloc.destroy(resp.req);
|
||||
|
||||
resp.req.* = try self.client.open(.GET, uri, .{
|
||||
.headers = .{
|
||||
.user_agent = .{ .override = user_agent },
|
||||
},
|
||||
.extra_headers = &.{
|
||||
.{ .name = "Accept", .value = "*/*" },
|
||||
.{ .name = "Accept-Language", .value = "en-US,en;q=0.5" },
|
||||
},
|
||||
.server_header_buffer = &self.server_header_buffer,
|
||||
});
|
||||
errdefer resp.req.deinit();
|
||||
|
||||
try resp.req.send();
|
||||
try resp.req.finish();
|
||||
try resp.req.wait();
|
||||
|
||||
return resp;
|
||||
}
|
||||
};
|
||||
|
||||
test "basic url get" {
|
||||
const alloc = std.testing.allocator;
|
||||
var loader = Loader.init(alloc);
|
||||
defer loader.deinit();
|
||||
|
||||
var result = try loader.get(alloc, "https://en.wikipedia.org/wiki/Main_Page");
|
||||
defer result.deinit();
|
||||
|
||||
try std.testing.expect(result.req.response.status == std.http.Status.ok);
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
// Copyright (C) 2023-2024 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const testing = std.testing;
|
||||
|
||||
const strparser = @import("../str/parser.zig");
|
||||
const Reader = strparser.Reader;
|
||||
const trim = strparser.trim;
|
||||
|
||||
const Self = @This();
|
||||
|
||||
const MimeError = error{
|
||||
Empty,
|
||||
TooBig,
|
||||
Invalid,
|
||||
InvalidChar,
|
||||
};
|
||||
|
||||
mtype: []const u8,
|
||||
msubtype: []const u8,
|
||||
params: []const u8 = "",
|
||||
|
||||
charset: ?[]const u8 = null,
|
||||
boundary: ?[]const u8 = null,
|
||||
|
||||
pub const Empty = Self{ .mtype = "", .msubtype = "" };
|
||||
pub const HTML = Self{ .mtype = "text", .msubtype = "html" };
|
||||
pub const Javascript = Self{ .mtype = "application", .msubtype = "javascript" };
|
||||
|
||||
// https://mimesniff.spec.whatwg.org/#http-token-code-point
|
||||
fn isHTTPCodePoint(c: u8) bool {
|
||||
return switch (c) {
|
||||
'!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^' => return true,
|
||||
'_', '`', '|', '~' => return true,
|
||||
else => std.ascii.isAlphanumeric(c),
|
||||
};
|
||||
}
|
||||
|
||||
fn valid(s: []const u8) bool {
|
||||
const ln = s.len;
|
||||
var i: usize = 0;
|
||||
while (i < ln) {
|
||||
if (!isHTTPCodePoint(s[i])) return false;
|
||||
i += 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// https://mimesniff.spec.whatwg.org/#parsing-a-mime-type
|
||||
pub fn parse(s: []const u8) Self.MimeError!Self {
|
||||
const ln = s.len;
|
||||
if (ln == 0) return MimeError.Empty;
|
||||
// limit input size
|
||||
if (ln > 255) return MimeError.TooBig;
|
||||
|
||||
var res = Self{ .mtype = "", .msubtype = "" };
|
||||
var r = Reader{ .s = s };
|
||||
|
||||
res.mtype = trim(r.until('/'));
|
||||
if (res.mtype.len == 0) return MimeError.Invalid;
|
||||
if (!valid(res.mtype)) return MimeError.InvalidChar;
|
||||
|
||||
if (!r.skip()) return MimeError.Invalid;
|
||||
res.msubtype = trim(r.until(';'));
|
||||
if (res.msubtype.len == 0) return MimeError.Invalid;
|
||||
if (!valid(res.msubtype)) return MimeError.InvalidChar;
|
||||
|
||||
if (!r.skip()) return res;
|
||||
res.params = trim(r.tail());
|
||||
if (res.params.len == 0) return MimeError.Invalid;
|
||||
|
||||
// parse well known parameters.
|
||||
// don't check invalid parameter format.
|
||||
var rp = Reader{ .s = res.params };
|
||||
while (true) {
|
||||
const name = trim(rp.until('='));
|
||||
if (!rp.skip()) return res;
|
||||
const value = trim(rp.until(';'));
|
||||
|
||||
if (std.ascii.eqlIgnoreCase(name, "charset")) {
|
||||
res.charset = value;
|
||||
}
|
||||
if (std.ascii.eqlIgnoreCase(name, "boundary")) {
|
||||
res.boundary = value;
|
||||
}
|
||||
|
||||
if (!rp.skip()) return res;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
test "parse valid" {
|
||||
for ([_][]const u8{
|
||||
"text/html",
|
||||
" \ttext/html",
|
||||
"text \t/html",
|
||||
"text/ \thtml",
|
||||
"text/html \t",
|
||||
}) |tc| {
|
||||
const m = try Self.parse(tc);
|
||||
try testing.expectEqualStrings("text", m.mtype);
|
||||
try testing.expectEqualStrings("html", m.msubtype);
|
||||
}
|
||||
const m2 = try Self.parse("text/javascript1.5");
|
||||
try testing.expectEqualStrings("text", m2.mtype);
|
||||
try testing.expectEqualStrings("javascript1.5", m2.msubtype);
|
||||
|
||||
const m3 = try Self.parse("text/html; charset=utf-8");
|
||||
try testing.expectEqualStrings("text", m3.mtype);
|
||||
try testing.expectEqualStrings("html", m3.msubtype);
|
||||
try testing.expectEqualStrings("charset=utf-8", m3.params);
|
||||
try testing.expectEqualStrings("utf-8", m3.charset.?);
|
||||
|
||||
const m4 = try Self.parse("text/html; boundary=----");
|
||||
try testing.expectEqualStrings("text", m4.mtype);
|
||||
try testing.expectEqualStrings("html", m4.msubtype);
|
||||
try testing.expectEqualStrings("boundary=----", m4.params);
|
||||
try testing.expectEqualStrings("----", m4.boundary.?);
|
||||
}
|
||||
|
||||
test "parse invalid" {
|
||||
for ([_][]const u8{
|
||||
"",
|
||||
"te xt/html;",
|
||||
"te@xt/html;",
|
||||
"text/ht@ml;",
|
||||
"text/html;",
|
||||
"/text/html",
|
||||
"/html",
|
||||
}) |tc| {
|
||||
_ = Self.parse(tc) catch continue;
|
||||
try testing.expect(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Compare type and subtype.
|
||||
pub fn eql(self: Self, b: Self) bool {
|
||||
if (!std.mem.eql(u8, self.mtype, b.mtype)) return false;
|
||||
return std.mem.eql(u8, self.msubtype, b.msubtype);
|
||||
}
|
||||
438
src/browser/parser/Parser.zig
Normal file
438
src/browser/parser/Parser.zig
Normal file
@@ -0,0 +1,438 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const h5e = @import("html5ever.zig");
|
||||
|
||||
const Page = @import("../Page.zig");
|
||||
const Node = @import("../webapi/Node.zig");
|
||||
const Element = @import("../webapi/Element.zig");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub const ParsedNode = struct {
|
||||
node: *Node,
|
||||
|
||||
// Data associated with this element to be passed back to html5ever as needed
|
||||
// We only have this for Elements. For other types, like comments, it's null.
|
||||
// html5ever should never ask us for this data on a non-element, and we'll
|
||||
// assert that, with this opitonal, to make sure our assumption is correct.
|
||||
data: ?*anyopaque,
|
||||
};
|
||||
|
||||
const Parser = @This();
|
||||
|
||||
page: *Page,
|
||||
err: ?Error,
|
||||
container: ParsedNode,
|
||||
arena: Allocator,
|
||||
strings: std.StringHashMapUnmanaged(void),
|
||||
|
||||
pub fn init(arena: Allocator, node: *Node, page: *Page) Parser {
|
||||
return .{
|
||||
.err = null,
|
||||
.page = page,
|
||||
.strings = .empty,
|
||||
.arena = arena,
|
||||
.container = ParsedNode{
|
||||
.data = null,
|
||||
.node = node,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const Error = struct {
|
||||
err: anyerror,
|
||||
source: Source,
|
||||
|
||||
const Source = enum {
|
||||
pop,
|
||||
append,
|
||||
create_element,
|
||||
create_comment,
|
||||
create_processing_instruction,
|
||||
append_doctype_to_document,
|
||||
add_attrs_if_missing,
|
||||
get_template_content,
|
||||
remove_from_parent,
|
||||
reparent_children,
|
||||
append_before_sibling,
|
||||
append_based_on_parent_node,
|
||||
};
|
||||
};
|
||||
|
||||
pub fn parse(self: *Parser, html: []const u8) void {
|
||||
h5e.html5ever_parse_document(
|
||||
html.ptr,
|
||||
html.len,
|
||||
&self.container,
|
||||
self,
|
||||
createElementCallback,
|
||||
getDataCallback,
|
||||
appendCallback,
|
||||
parseErrorCallback,
|
||||
popCallback,
|
||||
createCommentCallback,
|
||||
createProcessingInstruction,
|
||||
appendDoctypeToDocument,
|
||||
addAttrsIfMissingCallback,
|
||||
getTemplateContentsCallback,
|
||||
removeFromParentCallback,
|
||||
reparentChildrenCallback,
|
||||
appendBeforeSiblingCallback,
|
||||
appendBasedOnParentNodeCallback,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn parseXML(self: *Parser, xml: []const u8) void {
|
||||
h5e.xml5ever_parse_document(
|
||||
xml.ptr,
|
||||
xml.len,
|
||||
&self.container,
|
||||
self,
|
||||
createElementCallback,
|
||||
getDataCallback,
|
||||
appendCallback,
|
||||
parseErrorCallback,
|
||||
popCallback,
|
||||
createCommentCallback,
|
||||
createProcessingInstruction,
|
||||
appendDoctypeToDocument,
|
||||
addAttrsIfMissingCallback,
|
||||
getTemplateContentsCallback,
|
||||
removeFromParentCallback,
|
||||
reparentChildrenCallback,
|
||||
appendBeforeSiblingCallback,
|
||||
appendBasedOnParentNodeCallback,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn parseFragment(self: *Parser, html: []const u8) void {
|
||||
h5e.html5ever_parse_fragment(
|
||||
html.ptr,
|
||||
html.len,
|
||||
&self.container,
|
||||
self,
|
||||
createElementCallback,
|
||||
getDataCallback,
|
||||
appendCallback,
|
||||
parseErrorCallback,
|
||||
popCallback,
|
||||
createCommentCallback,
|
||||
createProcessingInstruction,
|
||||
appendDoctypeToDocument,
|
||||
addAttrsIfMissingCallback,
|
||||
getTemplateContentsCallback,
|
||||
removeFromParentCallback,
|
||||
reparentChildrenCallback,
|
||||
appendBeforeSiblingCallback,
|
||||
appendBasedOnParentNodeCallback,
|
||||
);
|
||||
}
|
||||
|
||||
pub const Streaming = struct {
|
||||
parser: Parser,
|
||||
handle: ?*anyopaque,
|
||||
|
||||
pub fn init(arena: Allocator, node: *Node, page: *Page) Streaming {
|
||||
return .{
|
||||
.handle = null,
|
||||
.parser = Parser.init(arena, node, page),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Streaming) void {
|
||||
if (self.handle) |handle| {
|
||||
h5e.html5ever_streaming_parser_destroy(handle);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(self: *Streaming) !void {
|
||||
std.debug.assert(self.handle == null);
|
||||
|
||||
self.handle = h5e.html5ever_streaming_parser_create(
|
||||
&self.parser.container,
|
||||
&self.parser,
|
||||
createElementCallback,
|
||||
getDataCallback,
|
||||
appendCallback,
|
||||
parseErrorCallback,
|
||||
popCallback,
|
||||
createCommentCallback,
|
||||
createProcessingInstruction,
|
||||
appendDoctypeToDocument,
|
||||
addAttrsIfMissingCallback,
|
||||
getTemplateContentsCallback,
|
||||
removeFromParentCallback,
|
||||
reparentChildrenCallback,
|
||||
appendBeforeSiblingCallback,
|
||||
appendBasedOnParentNodeCallback,
|
||||
) orelse return error.ParserCreationFailed;
|
||||
}
|
||||
|
||||
pub fn read(self: *Streaming, data: []const u8) !void {
|
||||
const result = h5e.html5ever_streaming_parser_feed(
|
||||
self.handle.?,
|
||||
data.ptr,
|
||||
data.len,
|
||||
);
|
||||
|
||||
if (result != 0) {
|
||||
// Parser panicked - clean up and return error
|
||||
// Note: deinit will destroy the handle if it exists
|
||||
if (self.handle) |handle| {
|
||||
h5e.html5ever_streaming_parser_destroy(handle);
|
||||
self.handle = null;
|
||||
}
|
||||
return error.ParserPanic;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn done(self: *Streaming) void {
|
||||
h5e.html5ever_streaming_parser_finish(self.handle.?);
|
||||
}
|
||||
};
|
||||
|
||||
fn parseErrorCallback(ctx: *anyopaque, err: h5e.StringSlice) callconv(.c) void {
|
||||
_ = ctx;
|
||||
_ = err;
|
||||
// std.debug.print("PEC: {s}\n", .{err.slice()});
|
||||
}
|
||||
|
||||
fn popCallback(ctx: *anyopaque, node_ref: *anyopaque) callconv(.c) void {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
self._popCallback(getNode(node_ref)) catch |err| {
|
||||
self.err = .{ .err = err, .source = .pop };
|
||||
};
|
||||
}
|
||||
|
||||
fn _popCallback(self: *Parser, node: *Node) !void {
|
||||
try self.page.nodeComplete(node);
|
||||
}
|
||||
|
||||
fn createElementCallback(ctx: *anyopaque, data: *anyopaque, qname: h5e.QualName, attributes: h5e.AttributeIterator) callconv(.c) ?*anyopaque {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
return self._createElementCallback(data, qname, attributes) catch |err| {
|
||||
self.err = .{ .err = err, .source = .create_element };
|
||||
return null;
|
||||
};
|
||||
}
|
||||
fn _createElementCallback(self: *Parser, data: *anyopaque, qname: h5e.QualName, attributes: h5e.AttributeIterator) !*anyopaque {
|
||||
const page = self.page;
|
||||
const name = qname.local.slice();
|
||||
const namespace = qname.ns.slice();
|
||||
const node = try page.createElement(namespace, name, attributes);
|
||||
|
||||
const pn = try self.arena.create(ParsedNode);
|
||||
pn.* = .{
|
||||
.data = data,
|
||||
.node = node,
|
||||
};
|
||||
return pn;
|
||||
}
|
||||
|
||||
fn createCommentCallback(ctx: *anyopaque, str: h5e.StringSlice) callconv(.c) ?*anyopaque {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
return self._createCommentCallback(str.slice()) catch |err| {
|
||||
self.err = .{ .err = err, .source = .create_comment };
|
||||
return null;
|
||||
};
|
||||
}
|
||||
fn _createCommentCallback(self: *Parser, str: []const u8) !*anyopaque {
|
||||
const page = self.page;
|
||||
const node = try page.createComment(str);
|
||||
const pn = try self.arena.create(ParsedNode);
|
||||
pn.* = .{
|
||||
.data = null,
|
||||
.node = node,
|
||||
};
|
||||
return pn;
|
||||
}
|
||||
|
||||
fn createProcessingInstruction(ctx: *anyopaque, target: h5e.StringSlice, data: h5e.StringSlice) callconv(.c) ?*anyopaque {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
return self._createProcessingInstruction(target.slice(), data.slice()) catch |err| {
|
||||
self.err = .{ .err = err, .source = .create_processing_instruction };
|
||||
return null;
|
||||
};
|
||||
}
|
||||
fn _createProcessingInstruction(self: *Parser, target: []const u8, data: []const u8) !*anyopaque {
|
||||
const page = self.page;
|
||||
const node = try page.createProcessingInstruction(target, data);
|
||||
const pn = try self.arena.create(ParsedNode);
|
||||
pn.* = .{
|
||||
.data = null,
|
||||
.node = node,
|
||||
};
|
||||
return pn;
|
||||
}
|
||||
|
||||
fn appendDoctypeToDocument(ctx: *anyopaque, name: h5e.StringSlice, public_id: h5e.StringSlice, system_id: h5e.StringSlice) callconv(.c) void {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
self._appendDoctypeToDocument(name.slice(), public_id.slice(), system_id.slice()) catch |err| {
|
||||
self.err = .{ .err = err, .source = .append_doctype_to_document };
|
||||
};
|
||||
}
|
||||
fn _appendDoctypeToDocument(self: *Parser, name: []const u8, public_id: []const u8, system_id: []const u8) !void {
|
||||
const page = self.page;
|
||||
|
||||
// Create the DocumentType node
|
||||
const DocumentType = @import("../webapi/DocumentType.zig");
|
||||
const doctype = try page._factory.node(DocumentType{
|
||||
._proto = undefined,
|
||||
._name = try page.dupeString(name),
|
||||
._public_id = try page.dupeString(public_id),
|
||||
._system_id = try page.dupeString(system_id),
|
||||
});
|
||||
|
||||
// Append it to the document
|
||||
try page.appendNew(self.container.node, .{ .node = doctype.asNode() });
|
||||
}
|
||||
|
||||
fn addAttrsIfMissingCallback(ctx: *anyopaque, target_ref: *anyopaque, attributes: h5e.AttributeIterator) callconv(.c) void {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
self._addAttrsIfMissingCallback(getNode(target_ref), attributes) catch |err| {
|
||||
self.err = .{ .err = err, .source = .add_attrs_if_missing };
|
||||
};
|
||||
}
|
||||
fn _addAttrsIfMissingCallback(self: *Parser, node: *Node, attributes: h5e.AttributeIterator) !void {
|
||||
const element = node.as(Element);
|
||||
const page = self.page;
|
||||
|
||||
const attr_list = try element.getOrCreateAttributeList(page);
|
||||
while (attributes.next()) |attr| {
|
||||
const name = attr.name.local.slice();
|
||||
const value = attr.value.slice();
|
||||
// putNew only adds if the attribute doesn't already exist
|
||||
try attr_list.putNew(name, value, page);
|
||||
}
|
||||
}
|
||||
|
||||
fn getTemplateContentsCallback(ctx: *anyopaque, target_ref: *anyopaque) callconv(.c) ?*anyopaque {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
return self._getTemplateContentsCallback(getNode(target_ref)) catch |err| {
|
||||
self.err = .{ .err = err, .source = .get_template_content };
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
fn _getTemplateContentsCallback(self: *Parser, node: *Node) !*anyopaque {
|
||||
const element = node.as(Element);
|
||||
const template = element._type.html.is(Element.Html.Template) orelse unreachable;
|
||||
const content_node = template.getContent().asNode();
|
||||
|
||||
// Create a ParsedNode wrapper for the content DocumentFragment
|
||||
const pn = try self.arena.create(ParsedNode);
|
||||
pn.* = .{
|
||||
.data = null,
|
||||
.node = content_node,
|
||||
};
|
||||
return pn;
|
||||
}
|
||||
|
||||
fn getDataCallback(ctx: *anyopaque) callconv(.c) *anyopaque {
|
||||
const pn: *ParsedNode = @ptrCast(@alignCast(ctx));
|
||||
// For non-elements, data is null. But, we expect this to only ever
|
||||
// be called for elements.
|
||||
std.debug.assert(pn.data != null);
|
||||
return pn.data.?;
|
||||
}
|
||||
|
||||
fn appendCallback(ctx: *anyopaque, parent_ref: *anyopaque, node_or_text: h5e.NodeOrText) callconv(.c) void {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
self._appendCallback(getNode(parent_ref), node_or_text) catch |err| {
|
||||
self.err = .{ .err = err, .source = .append };
|
||||
};
|
||||
}
|
||||
fn _appendCallback(self: *Parser, parent: *Node, node_or_text: h5e.NodeOrText) !void {
|
||||
// child node is guaranteed not to belong to another parent
|
||||
switch (node_or_text.toUnion()) {
|
||||
.node => |cpn| {
|
||||
const child = getNode(cpn);
|
||||
try self.page.appendNew(parent, .{ .node = child });
|
||||
},
|
||||
.text => |txt| try self.page.appendNew(parent, .{ .text = txt }),
|
||||
}
|
||||
}
|
||||
|
||||
fn removeFromParentCallback(ctx: *anyopaque, target_ref: *anyopaque) callconv(.c) void {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
self._removeFromParentCallback(getNode(target_ref)) catch |err| {
|
||||
self.err = .{ .err = err, .source = .remove_from_parent };
|
||||
};
|
||||
}
|
||||
fn _removeFromParentCallback(self: *Parser, node: *Node) !void {
|
||||
const parent = node.parentNode() orelse return;
|
||||
_ = try parent.removeChild(node, self.page);
|
||||
}
|
||||
|
||||
fn reparentChildrenCallback(ctx: *anyopaque, node_ref: *anyopaque, new_parent_ref: *anyopaque) callconv(.c) void {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
self._reparentChildrenCallback(getNode(node_ref), getNode(new_parent_ref)) catch |err| {
|
||||
self.err = .{ .err = err, .source = .reparent_children };
|
||||
};
|
||||
}
|
||||
fn _reparentChildrenCallback(self: *Parser, node: *Node, new_parent: *Node) !void {
|
||||
try self.page.appendAllChildren(node, new_parent);
|
||||
}
|
||||
|
||||
fn appendBeforeSiblingCallback(ctx: *anyopaque, sibling_ref: *anyopaque, node_or_text: h5e.NodeOrText) callconv(.c) void {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
self._appendBeforeSiblingCallback(getNode(sibling_ref), node_or_text) catch |err| {
|
||||
self.err = .{ .err = err, .source = .append_before_sibling };
|
||||
};
|
||||
}
|
||||
fn _appendBeforeSiblingCallback(self: *Parser, sibling: *Node, node_or_text: h5e.NodeOrText) !void {
|
||||
const parent = sibling.parentNode() orelse return error.NoParent;
|
||||
const node: *Node = switch (node_or_text.toUnion()) {
|
||||
.node => |cpn| getNode(cpn),
|
||||
.text => |txt| try self.page.createTextNode(txt),
|
||||
};
|
||||
try self.page.insertNodeRelative(parent, node, .{ .before = sibling }, .{});
|
||||
}
|
||||
|
||||
fn appendBasedOnParentNodeCallback(ctx: *anyopaque, element_ref: *anyopaque, prev_element_ref: *anyopaque, node_or_text: h5e.NodeOrText) callconv(.c) void {
|
||||
const self: *Parser = @ptrCast(@alignCast(ctx));
|
||||
self._appendBasedOnParentNodeCallback(getNode(element_ref), getNode(prev_element_ref), node_or_text) catch |err| {
|
||||
self.err = .{ .err = err, .source = .append_based_on_parent_node };
|
||||
};
|
||||
}
|
||||
fn _appendBasedOnParentNodeCallback(self: *Parser, element: *Node, prev_element: *Node, node_or_text: h5e.NodeOrText) !void {
|
||||
if (element.parentNode()) |_| {
|
||||
try self._appendBeforeSiblingCallback(element, node_or_text);
|
||||
} else {
|
||||
try self._appendCallback(prev_element, node_or_text);
|
||||
}
|
||||
}
|
||||
|
||||
fn getNode(ref: *anyopaque) *Node {
|
||||
const pn: *ParsedNode = @ptrCast(@alignCast(ref));
|
||||
return pn.node;
|
||||
}
|
||||
|
||||
fn asUint(comptime string: anytype) std.meta.Int(
|
||||
.unsigned,
|
||||
@bitSizeOf(@TypeOf(string.*)) - 8, // (- 8) to exclude sentinel 0
|
||||
) {
|
||||
const byteLength = @sizeOf(@TypeOf(string.*)) - 1;
|
||||
const expectedType = *const [byteLength:0]u8;
|
||||
if (@TypeOf(string) != expectedType) {
|
||||
@compileError("expected : " ++ @typeName(expectedType) ++ ", got: " ++ @typeName(@TypeOf(string)));
|
||||
}
|
||||
|
||||
return @bitCast(@as(*const [byteLength]u8, string).*);
|
||||
}
|
||||
194
src/browser/parser/html5ever.zig
Normal file
194
src/browser/parser/html5ever.zig
Normal file
@@ -0,0 +1,194 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const ParsedNode = @import("Parser.zig").ParsedNode;
|
||||
|
||||
pub extern "c" fn html5ever_parse_document(
|
||||
html: [*c]const u8,
|
||||
len: usize,
|
||||
doc: *anyopaque,
|
||||
ctx: *anyopaque,
|
||||
createElementCallback: *const fn (ctx: *anyopaque, data: *anyopaque, QualName, AttributeIterator) callconv(.c) ?*anyopaque,
|
||||
elemNameCallback: *const fn (node_ref: *anyopaque) callconv(.c) *anyopaque,
|
||||
appendCallback: *const fn (ctx: *anyopaque, parent_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
parseErrorCallback: *const fn (ctx: *anyopaque, StringSlice) callconv(.c) void,
|
||||
popCallback: *const fn (ctx: *anyopaque, node_ref: *anyopaque) callconv(.c) void,
|
||||
createCommentCallback: *const fn (ctx: *anyopaque, StringSlice) callconv(.c) ?*anyopaque,
|
||||
createProcessingInstruction: *const fn (ctx: *anyopaque, StringSlice, StringSlice) callconv(.c) ?*anyopaque,
|
||||
appendDoctypeToDocument: *const fn (ctx: *anyopaque, StringSlice, StringSlice, StringSlice) callconv(.c) void,
|
||||
addAttrsIfMissingCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque, AttributeIterator) callconv(.c) void,
|
||||
getTemplateContentsCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque) callconv(.c) ?*anyopaque,
|
||||
removeFromParentCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque) callconv(.c) void,
|
||||
reparentChildrenCallback: *const fn (ctx: *anyopaque, node_ref: *anyopaque, new_parent_ref: *anyopaque) callconv(.c) void,
|
||||
appendBeforeSiblingCallback: *const fn (ctx: *anyopaque, sibling_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
appendBasedOnParentNodeCallback: *const fn (ctx: *anyopaque, element_ref: *anyopaque, prev_element_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
) void;
|
||||
|
||||
pub extern "c" fn html5ever_parse_fragment(
|
||||
html: [*c]const u8,
|
||||
len: usize,
|
||||
doc: *anyopaque,
|
||||
ctx: *anyopaque,
|
||||
createElementCallback: *const fn (ctx: *anyopaque, data: *anyopaque, QualName, AttributeIterator) callconv(.c) ?*anyopaque,
|
||||
elemNameCallback: *const fn (node_ref: *anyopaque) callconv(.c) *anyopaque,
|
||||
appendCallback: *const fn (ctx: *anyopaque, parent_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
parseErrorCallback: *const fn (ctx: *anyopaque, StringSlice) callconv(.c) void,
|
||||
popCallback: *const fn (ctx: *anyopaque, node_ref: *anyopaque) callconv(.c) void,
|
||||
createCommentCallback: *const fn (ctx: *anyopaque, StringSlice) callconv(.c) ?*anyopaque,
|
||||
createProcessingInstruction: *const fn (ctx: *anyopaque, StringSlice, StringSlice) callconv(.c) ?*anyopaque,
|
||||
appendDoctypeToDocument: *const fn (ctx: *anyopaque, StringSlice, StringSlice, StringSlice) callconv(.c) void,
|
||||
addAttrsIfMissingCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque, AttributeIterator) callconv(.c) void,
|
||||
getTemplateContentsCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque) callconv(.c) ?*anyopaque,
|
||||
removeFromParentCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque) callconv(.c) void,
|
||||
reparentChildrenCallback: *const fn (ctx: *anyopaque, node_ref: *anyopaque, new_parent_ref: *anyopaque) callconv(.c) void,
|
||||
appendBeforeSiblingCallback: *const fn (ctx: *anyopaque, sibling_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
appendBasedOnParentNodeCallback: *const fn (ctx: *anyopaque, element_ref: *anyopaque, prev_element_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
) void;
|
||||
|
||||
pub extern "c" fn html5ever_attribute_iterator_next(ctx: *anyopaque) Nullable(Attribute);
|
||||
pub extern "c" fn html5ever_attribute_iterator_count(ctx: *anyopaque) usize;
|
||||
|
||||
pub extern "c" fn html5ever_get_memory_usage() MemoryUsage;
|
||||
|
||||
pub const MemoryUsage = extern struct {
|
||||
resident: usize,
|
||||
allocated: usize,
|
||||
};
|
||||
|
||||
// Streaming parser API
|
||||
pub extern "c" fn html5ever_streaming_parser_create(
|
||||
doc: *anyopaque,
|
||||
ctx: *anyopaque,
|
||||
createElementCallback: *const fn (ctx: *anyopaque, data: *anyopaque, QualName, AttributeIterator) callconv(.c) ?*anyopaque,
|
||||
elemNameCallback: *const fn (node_ref: *anyopaque) callconv(.c) *anyopaque,
|
||||
appendCallback: *const fn (ctx: *anyopaque, parent_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
parseErrorCallback: *const fn (ctx: *anyopaque, StringSlice) callconv(.c) void,
|
||||
popCallback: *const fn (ctx: *anyopaque, node_ref: *anyopaque) callconv(.c) void,
|
||||
createCommentCallback: *const fn (ctx: *anyopaque, StringSlice) callconv(.c) ?*anyopaque,
|
||||
createProcessingInstruction: *const fn (ctx: *anyopaque, StringSlice, StringSlice) callconv(.c) ?*anyopaque,
|
||||
appendDoctypeToDocument: *const fn (ctx: *anyopaque, StringSlice, StringSlice, StringSlice) callconv(.c) void,
|
||||
addAttrsIfMissingCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque, AttributeIterator) callconv(.c) void,
|
||||
getTemplateContentsCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque) callconv(.c) ?*anyopaque,
|
||||
removeFromParentCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque) callconv(.c) void,
|
||||
reparentChildrenCallback: *const fn (ctx: *anyopaque, node_ref: *anyopaque, new_parent_ref: *anyopaque) callconv(.c) void,
|
||||
appendBeforeSiblingCallback: *const fn (ctx: *anyopaque, sibling_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
appendBasedOnParentNodeCallback: *const fn (ctx: *anyopaque, element_ref: *anyopaque, prev_element_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
) ?*anyopaque;
|
||||
|
||||
pub extern "c" fn html5ever_streaming_parser_feed(
|
||||
parser: *anyopaque,
|
||||
html: [*c]const u8,
|
||||
len: usize,
|
||||
) c_int;
|
||||
|
||||
pub extern "c" fn html5ever_streaming_parser_finish(
|
||||
parser: *anyopaque,
|
||||
) void;
|
||||
|
||||
pub extern "c" fn html5ever_streaming_parser_destroy(
|
||||
parser: *anyopaque,
|
||||
) void;
|
||||
|
||||
pub fn Nullable(comptime T: type) type {
|
||||
return extern struct {
|
||||
tag: u8,
|
||||
value: T,
|
||||
|
||||
pub fn unwrap(self: @This()) ?T {
|
||||
return if (self.tag == 0) null else self.value;
|
||||
}
|
||||
|
||||
pub fn none() @This() {
|
||||
return .{ .tag = 0, .value = undefined };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub const StringSlice = Slice(u8);
|
||||
pub fn Slice(comptime T: type) type {
|
||||
return extern struct {
|
||||
ptr: [*]const T,
|
||||
len: usize,
|
||||
|
||||
pub fn slice(self: @This()) []const T {
|
||||
return self.ptr[0..self.len];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub const QualName = extern struct {
|
||||
prefix: Nullable(StringSlice),
|
||||
ns: StringSlice,
|
||||
local: StringSlice,
|
||||
};
|
||||
|
||||
pub const Attribute = extern struct {
|
||||
name: QualName,
|
||||
value: StringSlice,
|
||||
};
|
||||
|
||||
pub const AttributeIterator = extern struct {
|
||||
iter: *anyopaque,
|
||||
|
||||
pub fn next(self: AttributeIterator) ?Attribute {
|
||||
return html5ever_attribute_iterator_next(self.iter).unwrap();
|
||||
}
|
||||
|
||||
pub fn count(self: AttributeIterator) usize {
|
||||
return html5ever_attribute_iterator_count(self.iter);
|
||||
}
|
||||
};
|
||||
|
||||
pub const NodeOrText = extern struct {
|
||||
tag: u8,
|
||||
node: *anyopaque,
|
||||
text: StringSlice,
|
||||
|
||||
pub fn toUnion(self: NodeOrText) Union {
|
||||
if (self.tag == 0) {
|
||||
return .{ .node = @ptrCast(@alignCast(self.node)) };
|
||||
}
|
||||
return .{ .text = self.text.slice() };
|
||||
}
|
||||
|
||||
const Union = union(enum) {
|
||||
node: *ParsedNode,
|
||||
text: []const u8,
|
||||
};
|
||||
};
|
||||
|
||||
pub extern "c" fn xml5ever_parse_document(
|
||||
html: [*c]const u8,
|
||||
len: usize,
|
||||
doc: *anyopaque,
|
||||
ctx: *anyopaque,
|
||||
createElementCallback: *const fn (ctx: *anyopaque, data: *anyopaque, QualName, AttributeIterator) callconv(.c) ?*anyopaque,
|
||||
elemNameCallback: *const fn (node_ref: *anyopaque) callconv(.c) *anyopaque,
|
||||
appendCallback: *const fn (ctx: *anyopaque, parent_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
parseErrorCallback: *const fn (ctx: *anyopaque, StringSlice) callconv(.c) void,
|
||||
popCallback: *const fn (ctx: *anyopaque, node_ref: *anyopaque) callconv(.c) void,
|
||||
createCommentCallback: *const fn (ctx: *anyopaque, StringSlice) callconv(.c) ?*anyopaque,
|
||||
createProcessingInstruction: *const fn (ctx: *anyopaque, StringSlice, StringSlice) callconv(.c) ?*anyopaque,
|
||||
appendDoctypeToDocument: *const fn (ctx: *anyopaque, StringSlice, StringSlice, StringSlice) callconv(.c) void,
|
||||
addAttrsIfMissingCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque, AttributeIterator) callconv(.c) void,
|
||||
getTemplateContentsCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque) callconv(.c) ?*anyopaque,
|
||||
removeFromParentCallback: *const fn (ctx: *anyopaque, target_ref: *anyopaque) callconv(.c) void,
|
||||
reparentChildrenCallback: *const fn (ctx: *anyopaque, node_ref: *anyopaque, new_parent_ref: *anyopaque) callconv(.c) void,
|
||||
appendBeforeSiblingCallback: *const fn (ctx: *anyopaque, sibling_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
appendBasedOnParentNodeCallback: *const fn (ctx: *anyopaque, element_ref: *anyopaque, prev_element_ref: *anyopaque, NodeOrText) callconv(.c) void,
|
||||
) void;
|
||||
64
src/browser/reflect.zig
Normal file
64
src/browser/reflect.zig
Normal file
@@ -0,0 +1,64 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as
|
||||
// published by the Free Software Foundation, either version 3 of the
|
||||
// License, or (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// Gets the Parent of child.
|
||||
// HtmlElement.of(script) -> *HTMLElement
|
||||
pub fn Struct(comptime T: type) type {
|
||||
return switch (@typeInfo(T)) {
|
||||
.pointer => |ptr| ptr.child,
|
||||
.@"struct" => T,
|
||||
.void => T,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
// Creates an enum of N enums. Doesn't perserve their underlying integer
|
||||
pub fn mergeEnums(comptime enums: []const type) type {
|
||||
const field_count = blk: {
|
||||
var count: usize = 0;
|
||||
inline for (enums) |e| {
|
||||
count += @typeInfo(e).@"enum".fields.len;
|
||||
}
|
||||
break :blk count;
|
||||
};
|
||||
|
||||
var i: usize = 0;
|
||||
var fields: [field_count]std.builtin.Type.EnumField = undefined;
|
||||
for (enums) |e| {
|
||||
for (@typeInfo(e).@"enum".fields) |f| {
|
||||
fields[i] = .{
|
||||
.name = f.name,
|
||||
.value = i,
|
||||
};
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return @Type(.{ .@"enum" = .{
|
||||
.decls = &.{},
|
||||
.tag_type = blk: {
|
||||
if (field_count <= std.math.maxInt(u8)) break :blk u8;
|
||||
if (field_count <= std.math.maxInt(u16)) break :blk u16;
|
||||
unreachable;
|
||||
},
|
||||
.fields = &fields,
|
||||
.is_exhaustive = true,
|
||||
} });
|
||||
}
|
||||
15
src/browser/tests/animation/animation.html
Normal file
15
src/browser/tests/animation/animation.html
Normal file
@@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id=animation>
|
||||
let a1 = document.createElement('div').animate(null, null);
|
||||
testing.expectEqual('finished', a1.playState);
|
||||
|
||||
let cb = [];
|
||||
a1.ready.then(() => { cb.push('ready') });
|
||||
a1.finished.then((x) => {
|
||||
cb.push('finished');
|
||||
cb.push(x == a1);
|
||||
});
|
||||
testing.eventually(() => testing.expectEqual(['finished', true], cb));
|
||||
</script>
|
||||
136
src/browser/tests/blob.html
Normal file
136
src/browser/tests/blob.html
Normal file
@@ -0,0 +1,136 @@
|
||||
<!DOCTYPE html>
|
||||
<meta charset="UTF-8">
|
||||
<script src="./testing.js"></script>
|
||||
|
||||
<script id=basic>
|
||||
{
|
||||
const parts = ["\r\nthe quick brown\rfo\rx\r", "\njumps over\r\nthe\nlazy\r", "\ndog"];
|
||||
// "transparent" ending should not modify the final buffer.
|
||||
const blob = new Blob(parts, { type: "text/html" });
|
||||
|
||||
const expected = parts.join("");
|
||||
testing.expectEqual(expected.length, blob.size);
|
||||
testing.expectEqual("text/html", blob.type);
|
||||
testing.async(async () => { testing.expectEqual(expected, await blob.text()) });
|
||||
}
|
||||
|
||||
{
|
||||
const parts = ["\rhello\r", "\nwor\r\nld"];
|
||||
// "native" ending should modify the final buffer.
|
||||
const blob = new Blob(parts, { endings: "native" });
|
||||
|
||||
const expected = "\nhello\n\nwor\nld";
|
||||
testing.expectEqual(expected.length, blob.size);
|
||||
testing.async(async () => { testing.expectEqual(expected, await blob.text()) });
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Firefox and Safari only -->
|
||||
<script id=bytes>
|
||||
{
|
||||
const parts = ["light ", "panda ", "rocks ", "!"];
|
||||
const blob = new Blob(parts);
|
||||
|
||||
testing.async(async() => {
|
||||
const expected = new Uint8Array([108, 105, 103, 104, 116, 32, 112, 97,
|
||||
110, 100, 97, 32, 114, 111, 99, 107, 115,
|
||||
32, 33]);
|
||||
const result = await blob.bytes();
|
||||
testing.expectEqual(true, result instanceof Uint8Array);
|
||||
testing.expectEqual(expected, result);
|
||||
});
|
||||
}
|
||||
|
||||
// Test for SIMD.
|
||||
{
|
||||
const parts = [
|
||||
"\rThe opened package\r\nof potato\nchi\rps",
|
||||
"held the\r\nanswer to the\r mystery. Both det\rectives looke\r\rd\r",
|
||||
"\rat it but failed to realize\nit was\r\nthe\rkey\r\n",
|
||||
"\r\nto solve the \rcrime.\r"
|
||||
];
|
||||
|
||||
const blob = new Blob(parts, { type: "text/html", endings: "native" });
|
||||
testing.expectEqual(161, blob.size);
|
||||
testing.expectEqual("text/html", blob.type);
|
||||
testing.async(async() => {
|
||||
const expected = new Uint8Array([10, 84, 104, 101, 32, 111, 112, 101, 110,
|
||||
101, 100, 32, 112, 97, 99, 107, 97, 103,
|
||||
101, 10, 111, 102, 32, 112, 111, 116, 97,
|
||||
116, 111, 10, 99, 104, 105, 10, 112, 115,
|
||||
104, 101, 108, 100, 32, 116, 104, 101, 10,
|
||||
97, 110, 115, 119, 101, 114, 32, 116, 111,
|
||||
32, 116, 104, 101, 10, 32, 109, 121, 115,
|
||||
116, 101, 114, 121, 46, 32, 66, 111, 116,
|
||||
104, 32, 100, 101, 116, 10, 101, 99, 116,
|
||||
105, 118, 101, 115, 32, 108, 111, 111, 107,
|
||||
101, 10, 10, 100, 10, 10, 97, 116, 32, 105,
|
||||
116, 32, 98, 117, 116, 32, 102, 97, 105, 108,
|
||||
101, 100, 32, 116, 111, 32, 114, 101, 97,
|
||||
108, 105, 122, 101, 10, 105, 116, 32, 119, 97,
|
||||
115, 10, 116, 104, 101, 10, 107, 101, 121,
|
||||
10, 10, 116, 111, 32, 115, 111, 108, 118, 101,
|
||||
32, 116, 104, 101, 32, 10, 99, 114, 105, 109,
|
||||
101, 46, 10]);
|
||||
const result = await blob.bytes();
|
||||
testing.expectEqual(true, result instanceof Uint8Array);
|
||||
testing.expectEqual(expected, result);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=stream>
|
||||
{
|
||||
const parts = ["may", "thy", "knife", "chip", "and", "shatter"];
|
||||
const blob = new Blob(parts);
|
||||
const reader = blob.stream().getReader();
|
||||
|
||||
testing.async(async () => {
|
||||
const {done: done, value: value} = await reader.read()
|
||||
const expected = new Uint8Array([109, 97, 121, 116, 104, 121, 107, 110,
|
||||
105, 102, 101, 99, 104, 105, 112, 97,
|
||||
110, 100, 115, 104, 97, 116, 116, 101,
|
||||
114]);
|
||||
testing.expectEqual(false, done);
|
||||
testing.expectEqual(true, value instanceof Uint8Array);
|
||||
testing.expectEqual(expected, value);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=slice>
|
||||
{
|
||||
const parts = ["la", "symphonie", "des", "éclairs"];
|
||||
const blob = new Blob(parts);
|
||||
testing.async(async () => {
|
||||
const result = await blob.arrayBuffer();
|
||||
testing.expectEqual(true, result instanceof ArrayBuffer)
|
||||
});
|
||||
|
||||
let temp = blob.slice(0);
|
||||
testing.expectEqual(blob.size, temp.size);
|
||||
testing.async(async () => {
|
||||
testing.expectEqual("lasymphoniedeséclairs", await temp.text());
|
||||
});
|
||||
|
||||
temp = blob.slice(-4, -2, "custom");
|
||||
testing.expectEqual(2, temp.size);
|
||||
testing.expectEqual("custom", temp.type);
|
||||
testing.async(async () => {
|
||||
testing.expectEqual("ai", await temp.text());
|
||||
});
|
||||
|
||||
temp = blob.slice(14);
|
||||
testing.expectEqual(8, temp.size);
|
||||
testing.async(async () => {
|
||||
testing.expectEqual("éclairs", await temp.text());
|
||||
});
|
||||
|
||||
temp = blob.slice(6, -10, "text/eclair");
|
||||
testing.expectEqual(6, temp.size);
|
||||
testing.expectEqual("text/eclair", temp.type);
|
||||
testing.async(async () => {
|
||||
testing.expectEqual("honied", await temp.text());
|
||||
});
|
||||
}
|
||||
</script>
|
||||
217
src/browser/tests/cdata/cdata_section.html
Normal file
217
src/browser/tests/cdata/cdata_section.html
Normal file
@@ -0,0 +1,217 @@
|
||||
cdataClassName<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<div id="container"></div>
|
||||
|
||||
<script id="createInHTMLDocument">
|
||||
{
|
||||
try {
|
||||
document.createCDATASection('test');
|
||||
testing.fail('Should have thrown NotSupportedError');
|
||||
} catch (err) {
|
||||
testing.expectEqual('NotSupportedError', err.name);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="createInXMLDocument">
|
||||
{
|
||||
const doc = new Document();
|
||||
const cdata = doc.createCDATASection('Hello World');
|
||||
|
||||
testing.expectEqual(4, cdata.nodeType);
|
||||
testing.expectEqual('#cdata-section', cdata.nodeName);
|
||||
testing.expectEqual('Hello World', cdata.data);
|
||||
testing.expectEqual(11, cdata.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataWithSpecialChars">
|
||||
{
|
||||
const doc = new Document();
|
||||
const cdata = doc.createCDATASection('<tag>&"quotes"</tag>');
|
||||
|
||||
testing.expectEqual('<tag>&"quotes"</tag>', cdata.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataRejectsEndMarker">
|
||||
{
|
||||
const doc = new Document();
|
||||
|
||||
testing.withError((err) => {
|
||||
testing.expectEqual('InvalidCharacterError', err.name);
|
||||
}, () => doc.createCDATASection('foo ]]> bar'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataRejectsEndMarkerEdgeCase">
|
||||
{
|
||||
const doc = new Document();
|
||||
|
||||
testing.withError((err) => {
|
||||
testing.expectEqual('InvalidCharacterError', err.name);
|
||||
}, () => doc.createCDATASection(']]>'));
|
||||
|
||||
testing.withError((err) => {
|
||||
testing.expectEqual('InvalidCharacterError', err.name);
|
||||
}, () => doc.createCDATASection('start]]>end'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataAllowsSimilarPatterns">
|
||||
{
|
||||
const doc = new Document();
|
||||
|
||||
const cdata1 = doc.createCDATASection(']>');
|
||||
testing.expectEqual(']>', cdata1.data);
|
||||
|
||||
const cdata2 = doc.createCDATASection(']]');
|
||||
testing.expectEqual(']]', cdata2.data);
|
||||
|
||||
const cdata3 = doc.createCDATASection('] ]>');
|
||||
testing.expectEqual('] ]>', cdata3.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataCharacterDataMethods">
|
||||
{
|
||||
const doc = new Document();
|
||||
const cdata = doc.createCDATASection('Hello');
|
||||
|
||||
cdata.appendData(' World');
|
||||
testing.expectEqual('Hello World', cdata.data);
|
||||
testing.expectEqual(11, cdata.length);
|
||||
|
||||
cdata.deleteData(5, 6);
|
||||
testing.expectEqual('Hello', cdata.data);
|
||||
|
||||
cdata.insertData(0, 'Hi ');
|
||||
testing.expectEqual('Hi Hello', cdata.data);
|
||||
|
||||
cdata.replaceData(0, 3, 'Bye');
|
||||
testing.expectEqual('ByeHello', cdata.data);
|
||||
|
||||
const sub = cdata.substringData(0, 3);
|
||||
testing.expectEqual('Bye', sub);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataInheritance">
|
||||
{
|
||||
const doc = new Document();
|
||||
const cdata = doc.createCDATASection('test');
|
||||
|
||||
testing.expectEqual(true, cdata instanceof CDATASection);
|
||||
testing.expectEqual(true, cdata instanceof Text);
|
||||
testing.expectEqual(true, cdata instanceof CharacterData);
|
||||
testing.expectEqual(true, cdata instanceof Node);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataWholeText">
|
||||
{
|
||||
const doc = new Document();
|
||||
const cdata = doc.createCDATASection('test data');
|
||||
|
||||
testing.expectEqual('test data', cdata.wholeText);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataClone">
|
||||
{
|
||||
const doc = new Document();
|
||||
const cdata = doc.createCDATASection('original data');
|
||||
|
||||
const clone = cdata.cloneNode(false);
|
||||
|
||||
testing.expectEqual(4, clone.nodeType);
|
||||
testing.expectEqual('#cdata-section', clone.nodeName);
|
||||
testing.expectEqual('original data', clone.data);
|
||||
testing.expectEqual(true, clone !== cdata);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataRemove">
|
||||
{
|
||||
const doc = new Document();
|
||||
const cdata = doc.createCDATASection('test');
|
||||
|
||||
const root = doc.createElement('root');
|
||||
doc.appendChild(root);
|
||||
root.appendChild(cdata);
|
||||
|
||||
testing.expectEqual(1, root.childNodes.length);
|
||||
testing.expectEqual(root, cdata.parentNode);
|
||||
|
||||
cdata.remove();
|
||||
testing.expectEqual(0, root.childNodes.length);
|
||||
testing.expectEqual(null, cdata.parentNode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataBeforeAfter">
|
||||
{
|
||||
const doc = new Document();
|
||||
const root = doc.createElement('root');
|
||||
doc.appendChild(root);
|
||||
|
||||
const cdata = doc.createCDATASection('middle');
|
||||
root.appendChild(cdata);
|
||||
|
||||
const text1 = doc.createTextNode('before');
|
||||
const text2 = doc.createTextNode('after');
|
||||
|
||||
cdata.before(text1);
|
||||
cdata.after(text2);
|
||||
|
||||
testing.expectEqual(3, root.childNodes.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataReplaceWith">
|
||||
{
|
||||
const doc = new Document();
|
||||
const root = doc.createElement('root');
|
||||
doc.appendChild(root);
|
||||
|
||||
const cdata = doc.createCDATASection('old');
|
||||
root.appendChild(cdata);
|
||||
|
||||
const replacement = doc.createTextNode('new');
|
||||
cdata.replaceWith(replacement);
|
||||
|
||||
testing.expectEqual(1, root.childNodes.length);
|
||||
testing.expectEqual('new', root.childNodes[0].data);
|
||||
testing.expectEqual(null, cdata.parentNode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataSiblingNavigation">
|
||||
{
|
||||
const doc = new Document();
|
||||
const root = doc.createElement('root');
|
||||
doc.appendChild(root);
|
||||
|
||||
const elem1 = doc.createElement('first');
|
||||
const cdata = doc.createCDATASection('middle');
|
||||
const elem2 = doc.createElement('last');
|
||||
|
||||
root.appendChild(elem1);
|
||||
root.appendChild(cdata);
|
||||
root.appendChild(elem2);
|
||||
|
||||
testing.expectEqual('LAST', cdata.nextElementSibling.tagName);
|
||||
testing.expectEqual('FIRST', cdata.previousElementSibling.tagName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="cdataEmptyString">
|
||||
{
|
||||
const doc = new Document();
|
||||
const cdata = doc.createCDATASection('');
|
||||
|
||||
testing.expectEqual('', cdata.data);
|
||||
testing.expectEqual(0, cdata.length);
|
||||
}
|
||||
</script>
|
||||
730
src/browser/tests/cdata/character_data.html
Normal file
730
src/browser/tests/cdata/character_data.html
Normal file
@@ -0,0 +1,730 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<div id="container"></div>
|
||||
|
||||
<script id="lengthProperty">
|
||||
{
|
||||
// length property
|
||||
const text = document.createTextNode('Hello');
|
||||
testing.expectEqual(5, text.length);
|
||||
testing.expectEqual(5, text.data.length);
|
||||
|
||||
const empty = document.createTextNode('');
|
||||
testing.expectEqual(0, empty.length);
|
||||
|
||||
const comment = document.createComment('test comment');
|
||||
testing.expectEqual(12, comment.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="appendDataBasic">
|
||||
{
|
||||
// appendData basic
|
||||
const text = document.createTextNode('Hello');
|
||||
text.appendData(' World');
|
||||
testing.expectEqual('Hello World', text.data);
|
||||
testing.expectEqual(11, text.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="appendDataEmpty">
|
||||
{
|
||||
// appendData to empty
|
||||
const text = document.createTextNode('');
|
||||
text.appendData('First');
|
||||
testing.expectEqual('First', text.data);
|
||||
|
||||
// appendData empty string
|
||||
text.appendData('');
|
||||
testing.expectEqual('First', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="deleteDataBasic">
|
||||
{
|
||||
// deleteData from middle
|
||||
const text = document.createTextNode('Hello World');
|
||||
text.deleteData(5, 6); // Remove ' World'
|
||||
testing.expectEqual('Hello', text.data);
|
||||
testing.expectEqual(5, text.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="deleteDataStart">
|
||||
{
|
||||
// deleteData from start
|
||||
const text = document.createTextNode('Hello World');
|
||||
text.deleteData(0, 6); // Remove 'Hello '
|
||||
testing.expectEqual('World', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="deleteDataEnd">
|
||||
{
|
||||
// deleteData from end
|
||||
const text = document.createTextNode('Hello World');
|
||||
text.deleteData(5, 100); // Remove ' World' (count exceeds length)
|
||||
testing.expectEqual('Hello', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="deleteDataAll">
|
||||
{
|
||||
// deleteData everything
|
||||
const text = document.createTextNode('Hello');
|
||||
text.deleteData(0, 5);
|
||||
testing.expectEqual('', text.data);
|
||||
testing.expectEqual(0, text.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="deleteDataZeroCount">
|
||||
{
|
||||
// deleteData with count=0
|
||||
const text = document.createTextNode('Hello');
|
||||
text.deleteData(2, 0);
|
||||
testing.expectEqual('Hello', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="deleteDataInvalidOffset">
|
||||
{
|
||||
// deleteData with invalid offset
|
||||
const text = document.createTextNode('Hello');
|
||||
testing.expectError('IndexSizeError: Index or size is negative or greater than the allowed amount', () => text.deleteData(10, 5));
|
||||
testing.expectEqual('Hello', text.data); // unchanged
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="insertDataMiddle">
|
||||
{
|
||||
// insertData in middle
|
||||
const text = document.createTextNode('Hello');
|
||||
text.insertData(5, ' World');
|
||||
testing.expectEqual('Hello World', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="insertDataStart">
|
||||
{
|
||||
// insertData at start
|
||||
const text = document.createTextNode('World');
|
||||
text.insertData(0, 'Hello ');
|
||||
testing.expectEqual('Hello World', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="insertDataEnd">
|
||||
{
|
||||
// insertData at end
|
||||
const text = document.createTextNode('Hello');
|
||||
text.insertData(5, ' World');
|
||||
testing.expectEqual('Hello World', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="insertDataEmpty">
|
||||
{
|
||||
// insertData into empty
|
||||
const text = document.createTextNode('');
|
||||
text.insertData(0, 'Hello');
|
||||
testing.expectEqual('Hello', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="insertDataInvalidOffset">
|
||||
{
|
||||
// insertData with invalid offset
|
||||
const text = document.createTextNode('Hello');
|
||||
testing.expectError('IndexSizeError: Index or size is negative or greater than the allowed amount', () => text.insertData(10, 'X'));
|
||||
testing.expectEqual('Hello', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="replaceDataBasic">
|
||||
{
|
||||
// replaceData basic
|
||||
const text = document.createTextNode('Hello World');
|
||||
text.replaceData(6, 5, 'Universe');
|
||||
testing.expectEqual('Hello Universe', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="replaceDataShorter">
|
||||
{
|
||||
// replaceData with shorter string
|
||||
const text = document.createTextNode('Hello World');
|
||||
text.replaceData(6, 5, 'Hi');
|
||||
testing.expectEqual('Hello Hi', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="replaceDataLonger">
|
||||
{
|
||||
// replaceData with longer string
|
||||
const text = document.createTextNode('Hello Hi');
|
||||
text.replaceData(6, 2, 'World');
|
||||
testing.expectEqual('Hello World', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="replaceDataExceedingCount">
|
||||
{
|
||||
// replaceData with count exceeding length
|
||||
const text = document.createTextNode('Hello World');
|
||||
text.replaceData(6, 100, 'Everyone');
|
||||
testing.expectEqual('Hello Everyone', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="replaceDataZeroCount">
|
||||
{
|
||||
// replaceData with count=0 (acts like insert)
|
||||
const text = document.createTextNode('Hello World');
|
||||
text.replaceData(5, 0, '!!!');
|
||||
testing.expectEqual('Hello!!! World', text.data);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="substringDataBasic">
|
||||
{
|
||||
// substringData basic
|
||||
const text = document.createTextNode('Hello World');
|
||||
const sub = text.substringData(0, 5);
|
||||
testing.expectEqual('Hello', sub);
|
||||
testing.expectEqual('Hello World', text.data); // original unchanged
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="substringDataMiddle">
|
||||
{
|
||||
// substringData from middle
|
||||
const text = document.createTextNode('Hello World');
|
||||
const sub = text.substringData(6, 5);
|
||||
testing.expectEqual('World', sub);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="substringDataExceedingCount">
|
||||
{
|
||||
// substringData with count exceeding length
|
||||
const text = document.createTextNode('Hello World');
|
||||
const sub = text.substringData(6, 100);
|
||||
testing.expectEqual('World', sub);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="substringDataZeroCount">
|
||||
{
|
||||
// substringData with count=0
|
||||
const text = document.createTextNode('Hello');
|
||||
const sub = text.substringData(0, 0);
|
||||
testing.expectEqual('', sub);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="substringDataInvalidOffset">
|
||||
{
|
||||
// substringData with invalid offset
|
||||
const text = document.createTextNode('Hello');
|
||||
testing.expectError('IndexSizeError: Index or size is negative or greater than the allowed amount', () => text.substringData(10, 5));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="commentCharacterData">
|
||||
{
|
||||
// CharacterData methods work on comments too
|
||||
const comment = document.createComment('Hello');
|
||||
|
||||
comment.appendData(' World');
|
||||
testing.expectEqual('Hello World', comment.data);
|
||||
|
||||
comment.deleteData(5, 6);
|
||||
testing.expectEqual('Hello', comment.data);
|
||||
|
||||
comment.insertData(0, 'Start: ');
|
||||
testing.expectEqual('Start: Hello', comment.data);
|
||||
|
||||
comment.replaceData(0, 7, 'End: ');
|
||||
testing.expectEqual('End: Hello', comment.data);
|
||||
|
||||
const sub = comment.substringData(5, 5);
|
||||
testing.expectEqual('Hello', sub);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="dataChangeNotifications">
|
||||
{
|
||||
// Verify data changes are reflected in DOM
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text = document.createTextNode('Original');
|
||||
container.appendChild(text);
|
||||
|
||||
text.appendData(' Text');
|
||||
testing.expectEqual('Original Text', container.textContent);
|
||||
|
||||
text.deleteData(0, 9);
|
||||
testing.expectEqual('Text', container.textContent);
|
||||
|
||||
text.data = 'Changed';
|
||||
testing.expectEqual('Changed', container.textContent);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="removeWithSiblings">
|
||||
{
|
||||
// remove() when node has siblings
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text1 = document.createTextNode('A');
|
||||
const text2 = document.createTextNode('B');
|
||||
const text3 = document.createTextNode('C');
|
||||
container.appendChild(text1);
|
||||
container.appendChild(text2);
|
||||
container.appendChild(text3);
|
||||
|
||||
testing.expectEqual(3, container.childNodes.length);
|
||||
testing.expectEqual('ABC', container.textContent);
|
||||
|
||||
text2.remove();
|
||||
|
||||
testing.expectEqual(2, container.childNodes.length);
|
||||
testing.expectEqual('AC', container.textContent);
|
||||
testing.expectEqual(null, text2.parentNode);
|
||||
testing.expectEqual(text3, text1.nextSibling);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="removeOnlyChild">
|
||||
{
|
||||
// remove() when node is only child
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text = document.createTextNode('Only');
|
||||
container.appendChild(text);
|
||||
|
||||
testing.expectEqual(1, container.childNodes.length);
|
||||
|
||||
text.remove();
|
||||
|
||||
testing.expectEqual(0, container.childNodes.length);
|
||||
testing.expectEqual(null, text.parentNode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="removeNoParent">
|
||||
{
|
||||
// remove() when node has no parent (should do nothing)
|
||||
const text = document.createTextNode('Orphan');
|
||||
text.remove(); // Should not throw
|
||||
testing.expectEqual(null, text.parentNode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="removeCommentWithElementSiblings">
|
||||
{
|
||||
// remove() comment with element siblings
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const div1 = document.createElement('div');
|
||||
div1.textContent = 'First';
|
||||
const comment = document.createComment('middle');
|
||||
const div2 = document.createElement('div');
|
||||
div2.textContent = 'Last';
|
||||
|
||||
container.appendChild(div1);
|
||||
container.appendChild(comment);
|
||||
container.appendChild(div2);
|
||||
|
||||
testing.expectEqual(3, container.childNodes.length);
|
||||
|
||||
comment.remove();
|
||||
|
||||
testing.expectEqual(2, container.childNodes.length);
|
||||
testing.expectEqual('DIV', container.childNodes[0].tagName);
|
||||
testing.expectEqual('DIV', container.childNodes[1].tagName);
|
||||
testing.expectEqual(div2, div1.nextSibling);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="beforeWithSiblings">
|
||||
{
|
||||
// before() when node has siblings
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text1 = document.createTextNode('A');
|
||||
const text2 = document.createTextNode('C');
|
||||
container.appendChild(text1);
|
||||
container.appendChild(text2);
|
||||
|
||||
const textB = document.createTextNode('B');
|
||||
text2.before(textB);
|
||||
|
||||
testing.expectEqual(3, container.childNodes.length);
|
||||
testing.expectEqual('ABC', container.textContent);
|
||||
testing.expectEqual(textB, text1.nextSibling);
|
||||
testing.expectEqual(text2, textB.nextSibling);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="beforeMultipleNodes">
|
||||
{
|
||||
// before() with multiple nodes
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text = document.createTextNode('Z');
|
||||
container.appendChild(text);
|
||||
|
||||
const text1 = document.createTextNode('A');
|
||||
const text2 = document.createTextNode('B');
|
||||
const text3 = document.createTextNode('C');
|
||||
|
||||
text.before(text1, text2, text3);
|
||||
|
||||
testing.expectEqual(4, container.childNodes.length);
|
||||
testing.expectEqual('ABCZ', container.textContent);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="beforeMixedTypes">
|
||||
{
|
||||
// before() with mixed node types
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const target = document.createTextNode('Target');
|
||||
container.appendChild(target);
|
||||
|
||||
const elem = document.createElement('span');
|
||||
elem.textContent = 'E';
|
||||
const text = document.createTextNode('T');
|
||||
const comment = document.createComment('C');
|
||||
|
||||
target.before(elem, text, comment);
|
||||
|
||||
testing.expectEqual(4, container.childNodes.length);
|
||||
testing.expectEqual(1, container.childNodes[0].nodeType); // ELEMENT_NODE
|
||||
testing.expectEqual(3, container.childNodes[1].nodeType); // TEXT_NODE
|
||||
testing.expectEqual(8, container.childNodes[2].nodeType); // COMMENT_NODE
|
||||
testing.expectEqual(3, container.childNodes[3].nodeType); // TEXT_NODE (target)
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="beforeNoParent">
|
||||
{
|
||||
// before() when node has no parent (should do nothing)
|
||||
const orphan = document.createTextNode('Orphan');
|
||||
const text = document.createTextNode('Test');
|
||||
orphan.before(text);
|
||||
|
||||
testing.expectEqual(null, orphan.parentNode);
|
||||
testing.expectEqual(null, text.parentNode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="beforeOnlyChild">
|
||||
{
|
||||
// before() when target is only child
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const target = document.createTextNode('B');
|
||||
container.appendChild(target);
|
||||
|
||||
const textA = document.createTextNode('A');
|
||||
target.before(textA);
|
||||
|
||||
testing.expectEqual(2, container.childNodes.length);
|
||||
testing.expectEqual('AB', container.textContent);
|
||||
testing.expectEqual(textA, container.firstChild);
|
||||
testing.expectEqual(target, textA.nextSibling);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="afterWithSiblings">
|
||||
{
|
||||
// after() when node has siblings
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text1 = document.createTextNode('A');
|
||||
const text2 = document.createTextNode('C');
|
||||
container.appendChild(text1);
|
||||
container.appendChild(text2);
|
||||
|
||||
const textB = document.createTextNode('B');
|
||||
text1.after(textB);
|
||||
|
||||
testing.expectEqual(3, container.childNodes.length);
|
||||
testing.expectEqual('ABC', container.textContent);
|
||||
testing.expectEqual(textB, text1.nextSibling);
|
||||
testing.expectEqual(text2, textB.nextSibling);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="afterMultipleNodes">
|
||||
{
|
||||
// after() with multiple nodes
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text = document.createTextNode('A');
|
||||
container.appendChild(text);
|
||||
|
||||
const text1 = document.createTextNode('B');
|
||||
const text2 = document.createTextNode('C');
|
||||
const text3 = document.createTextNode('D');
|
||||
|
||||
text.after(text1, text2, text3);
|
||||
|
||||
testing.expectEqual(4, container.childNodes.length);
|
||||
testing.expectEqual('ABCD', container.textContent);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="afterMixedTypes">
|
||||
{
|
||||
// after() with mixed node types
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const target = document.createTextNode('Start');
|
||||
container.appendChild(target);
|
||||
|
||||
const elem = document.createElement('div');
|
||||
elem.textContent = 'E';
|
||||
const comment = document.createComment('comment');
|
||||
const text = document.createTextNode('T');
|
||||
|
||||
target.after(elem, comment, text);
|
||||
|
||||
testing.expectEqual(4, container.childNodes.length);
|
||||
testing.expectEqual(3, container.childNodes[0].nodeType); // TEXT_NODE (target)
|
||||
testing.expectEqual(1, container.childNodes[1].nodeType); // ELEMENT_NODE
|
||||
testing.expectEqual(8, container.childNodes[2].nodeType); // COMMENT_NODE
|
||||
testing.expectEqual(3, container.childNodes[3].nodeType); // TEXT_NODE
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="afterNoParent">
|
||||
{
|
||||
// after() when node has no parent (should do nothing)
|
||||
const orphan = document.createTextNode('Orphan');
|
||||
const text = document.createTextNode('Test');
|
||||
orphan.after(text);
|
||||
|
||||
testing.expectEqual(null, orphan.parentNode);
|
||||
testing.expectEqual(null, text.parentNode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="afterAsLastChild">
|
||||
{
|
||||
// after() when target is last child
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const target = document.createTextNode('A');
|
||||
container.appendChild(target);
|
||||
|
||||
const textB = document.createTextNode('B');
|
||||
target.after(textB);
|
||||
|
||||
testing.expectEqual(2, container.childNodes.length);
|
||||
testing.expectEqual('AB', container.textContent);
|
||||
testing.expectEqual(target, container.firstChild);
|
||||
testing.expectEqual(textB, container.lastChild);
|
||||
testing.expectEqual(null, textB.nextSibling);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="replaceWithSingleNode">
|
||||
{
|
||||
// replaceWith() with single node
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const old = document.createTextNode('Old');
|
||||
container.appendChild(old);
|
||||
|
||||
const replacement = document.createTextNode('New');
|
||||
old.replaceWith(replacement);
|
||||
|
||||
testing.expectEqual(1, container.childNodes.length);
|
||||
testing.expectEqual('New', container.textContent);
|
||||
testing.expectEqual(null, old.parentNode);
|
||||
testing.expectEqual(container, replacement.parentNode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="replaceWithMultipleNodes">
|
||||
{
|
||||
// replaceWith() with multiple nodes
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const old = document.createTextNode('X');
|
||||
container.appendChild(old);
|
||||
|
||||
const text1 = document.createTextNode('A');
|
||||
const text2 = document.createTextNode('B');
|
||||
const text3 = document.createTextNode('C');
|
||||
|
||||
old.replaceWith(text1, text2, text3);
|
||||
|
||||
testing.expectEqual(3, container.childNodes.length);
|
||||
testing.expectEqual('ABC', container.textContent);
|
||||
testing.expectEqual(null, old.parentNode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="replaceWithOnlyChild">
|
||||
{
|
||||
// replaceWith() when target is only child
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const old = document.createTextNode('Only');
|
||||
container.appendChild(old);
|
||||
|
||||
testing.expectEqual(1, container.childNodes.length);
|
||||
|
||||
const replacement = document.createTextNode('Replaced');
|
||||
old.replaceWith(replacement);
|
||||
|
||||
testing.expectEqual(1, container.childNodes.length);
|
||||
testing.expectEqual('Replaced', container.textContent);
|
||||
testing.expectEqual(replacement, container.firstChild);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="replaceWithBetweenSiblings">
|
||||
{
|
||||
// replaceWith() when node has siblings on both sides
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text1 = document.createTextNode('A');
|
||||
const text2 = document.createTextNode('X');
|
||||
const text3 = document.createTextNode('C');
|
||||
container.appendChild(text1);
|
||||
container.appendChild(text2);
|
||||
container.appendChild(text3);
|
||||
|
||||
const replacement = document.createTextNode('B');
|
||||
text2.replaceWith(replacement);
|
||||
|
||||
testing.expectEqual(3, container.childNodes.length);
|
||||
testing.expectEqual('ABC', container.textContent);
|
||||
testing.expectEqual(replacement, text1.nextSibling);
|
||||
testing.expectEqual(text3, replacement.nextSibling);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="replaceWithMixedTypes">
|
||||
{
|
||||
// replaceWith() with mixed node types
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const old = document.createComment('old');
|
||||
container.appendChild(old);
|
||||
|
||||
const elem = document.createElement('span');
|
||||
elem.textContent = 'E';
|
||||
const text = document.createTextNode('T');
|
||||
const comment = document.createComment('C');
|
||||
|
||||
old.replaceWith(elem, text, comment);
|
||||
|
||||
testing.expectEqual(3, container.childNodes.length);
|
||||
testing.expectEqual(1, container.childNodes[0].nodeType); // ELEMENT_NODE
|
||||
testing.expectEqual(3, container.childNodes[1].nodeType); // TEXT_NODE
|
||||
testing.expectEqual(8, container.childNodes[2].nodeType); // COMMENT_NODE
|
||||
testing.expectEqual(null, old.parentNode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="nextElementSiblingText">
|
||||
{
|
||||
// nextElementSibling on text node with element siblings
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text1 = document.createTextNode('A');
|
||||
const comment = document.createComment('comment');
|
||||
const div = document.createElement('div');
|
||||
div.id = 'found';
|
||||
const text2 = document.createTextNode('B');
|
||||
|
||||
container.appendChild(text1);
|
||||
container.appendChild(comment);
|
||||
container.appendChild(div);
|
||||
container.appendChild(text2);
|
||||
|
||||
testing.expectEqual('found', text1.nextElementSibling.id);
|
||||
testing.expectEqual('found', comment.nextElementSibling.id);
|
||||
testing.expectEqual(null, text2.nextElementSibling);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="nextElementSiblingNoElement">
|
||||
{
|
||||
// nextElementSibling when there's no element sibling
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text = document.createTextNode('A');
|
||||
const comment = document.createComment('B');
|
||||
container.appendChild(text);
|
||||
container.appendChild(comment);
|
||||
|
||||
testing.expectEqual(null, text.nextElementSibling);
|
||||
testing.expectEqual(null, comment.nextElementSibling);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="previousElementSiblingComment">
|
||||
{
|
||||
// previousElementSibling on comment with element siblings
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const div = document.createElement('div');
|
||||
div.id = 'found';
|
||||
const text = document.createTextNode('text');
|
||||
const comment = document.createComment('comment');
|
||||
|
||||
container.appendChild(div);
|
||||
container.appendChild(text);
|
||||
container.appendChild(comment);
|
||||
|
||||
testing.expectEqual('found', text.previousElementSibling.id);
|
||||
testing.expectEqual('found', comment.previousElementSibling.id);
|
||||
testing.expectEqual(null, div.previousElementSibling);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="previousElementSiblingNoElement">
|
||||
{
|
||||
// previousElementSibling when there's no element sibling
|
||||
const container = $('#container');
|
||||
container.innerHTML = '';
|
||||
|
||||
const text = document.createTextNode('A');
|
||||
const comment = document.createComment('B');
|
||||
container.appendChild(text);
|
||||
container.appendChild(comment);
|
||||
|
||||
testing.expectEqual(null, text.previousElementSibling);
|
||||
testing.expectEqual(null, comment.previousElementSibling);
|
||||
}
|
||||
</script>
|
||||
7
src/browser/tests/cdata/comment.html
Normal file
7
src/browser/tests/cdata/comment.html
Normal file
@@ -0,0 +1,7 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id=comment>
|
||||
testing.expectEqual('', new Comment().data);
|
||||
testing.expectEqual('over 9000! ', new Comment('over 9000! ').data);
|
||||
</script>
|
||||
10
src/browser/tests/cdata/data.html
Normal file
10
src/browser/tests/cdata/data.html
Normal file
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<div id=a><!-- spice --></div>
|
||||
<div id=b>flow</div>
|
||||
|
||||
<script id=data>
|
||||
testing.expectEqual(' spice ', $('#a').firstChild.data);
|
||||
testing.expectEqual('flow', $('#b').firstChild.data);
|
||||
</script>
|
||||
19
src/browser/tests/cdata/text/text.html
Normal file
19
src/browser/tests/cdata/text/text.html
Normal file
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<a id="link" href="foo" class="ok">OK</a>
|
||||
|
||||
<script src="../../testing.js"></script>
|
||||
<script id=text>
|
||||
let t = new Text('foo');
|
||||
testing.expectEqual('foo', t.data);
|
||||
|
||||
let emptyt = new Text();
|
||||
testing.expectEqual('', emptyt.data);
|
||||
|
||||
let text = $('#link').firstChild;
|
||||
testing.expectEqual('OK', text.wholeText);
|
||||
|
||||
text.data = 'OK modified';
|
||||
let split = text.splitText('OK'.length);
|
||||
testing.expectEqual(' modified', split.data);
|
||||
testing.expectEqual('OK', text.data);
|
||||
</script>
|
||||
1
src/browser/tests/cdp/dom1.html
Normal file
1
src/browser/tests/cdp/dom1.html
Normal file
@@ -0,0 +1 @@
|
||||
<p>1</p> <p>2</p>
|
||||
1
src/browser/tests/cdp/dom2.html
Normal file
1
src/browser/tests/cdp/dom2.html
Normal file
@@ -0,0 +1 @@
|
||||
<div><p>2</p></div>
|
||||
1
src/browser/tests/cdp/registry1.html
Normal file
1
src/browser/tests/cdp/registry1.html
Normal file
@@ -0,0 +1 @@
|
||||
<a id=a1>link1</a><div id=d2><p>other</p></div>
|
||||
1
src/browser/tests/cdp/registry2.html
Normal file
1
src/browser/tests/cdp/registry2.html
Normal file
@@ -0,0 +1 @@
|
||||
<a id=a1></a><a id=a2></a>
|
||||
1
src/browser/tests/cdp/registry3.html
Normal file
1
src/browser/tests/cdp/registry3.html
Normal file
@@ -0,0 +1 @@
|
||||
<a id=a1></a><div id=d2><a id=a2></a></div>
|
||||
213
src/browser/tests/collections/radio_node_list.html
Normal file
213
src/browser/tests/collections/radio_node_list.html
Normal file
@@ -0,0 +1,213 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<!-- Test fixtures for RadioNodeList -->
|
||||
<form id="test_form">
|
||||
<input type="radio" name="color" value="red">
|
||||
<input type="radio" name="color" value="green">
|
||||
<input type="radio" name="color" value="blue">
|
||||
<input type="text" name="single_field" value="test">
|
||||
</form>
|
||||
|
||||
<script id="multiple_returns_radio_node_list">
|
||||
{
|
||||
const form = $('#test_form');
|
||||
const result = form.elements.namedItem('color');
|
||||
|
||||
testing.expectEqual('RadioNodeList', result.constructor.name);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="single_returns_element">
|
||||
{
|
||||
const form = $('#test_form');
|
||||
const result = form.elements.namedItem('single_field');
|
||||
|
||||
testing.expectEqual('HTMLInputElement', result.constructor.name);
|
||||
testing.expectEqual('single_field', result.name);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="none_returns_null">
|
||||
{
|
||||
const form = $('#test_form');
|
||||
const result = form.elements.namedItem('nonexistent');
|
||||
|
||||
testing.expectEqual(null, result);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="length">
|
||||
{
|
||||
const form = $('#test_form');
|
||||
const radios = form.elements.namedItem('color');
|
||||
|
||||
testing.expectEqual(3, radios.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="indexed_access">
|
||||
{
|
||||
const form = $('#test_form');
|
||||
const radios = form.elements.namedItem('color');
|
||||
|
||||
testing.expectEqual('red', radios[0].value);
|
||||
testing.expectEqual('green', radios[1].value);
|
||||
testing.expectEqual('blue', radios[2].value);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="value_getter_no_checked">
|
||||
{
|
||||
const form = $('#test_form');
|
||||
const radios = form.elements.namedItem('color');
|
||||
|
||||
testing.expectEqual('', radios.value);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="value_getter_with_checked">
|
||||
{
|
||||
const form = $('#test_form');
|
||||
const inputs = form.querySelectorAll('input[name="color"]');
|
||||
inputs[1].checked = true;
|
||||
|
||||
const radios = form.elements.namedItem('color');
|
||||
testing.expectEqual('green', radios.value);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="value_getter_on_default">
|
||||
{
|
||||
const form = document.createElement('form');
|
||||
const r1 = document.createElement('input');
|
||||
r1.type = 'radio';
|
||||
r1.name = 'test';
|
||||
r1.checked = true;
|
||||
// no value attribute
|
||||
|
||||
const r2 = document.createElement('input');
|
||||
r2.type = 'radio';
|
||||
r2.name = 'test';
|
||||
// no value attribute
|
||||
|
||||
form.appendChild(r1);
|
||||
form.appendChild(r2);
|
||||
document.body.appendChild(form);
|
||||
|
||||
// Multiple elements with same name returns RadioNodeList
|
||||
const radios = form.elements.namedItem('test');
|
||||
testing.expectEqual('RadioNodeList', radios.constructor.name);
|
||||
testing.expectEqual('on', radios.value); // Checked radio with no value returns "on"
|
||||
|
||||
form.remove();
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="value_setter">
|
||||
{
|
||||
const form = $('#test_form');
|
||||
const radios = form.elements.namedItem('color');
|
||||
const inputs = form.querySelectorAll('input[name="color"]');
|
||||
|
||||
radios.value = 'blue';
|
||||
|
||||
testing.expectEqual(false, inputs[0].checked);
|
||||
testing.expectEqual(false, inputs[1].checked);
|
||||
testing.expectEqual(true, inputs[2].checked);
|
||||
testing.expectEqual('blue', radios.value);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="value_setter_on">
|
||||
{
|
||||
const form = document.createElement('form');
|
||||
const r1 = document.createElement('input');
|
||||
r1.type = 'radio';
|
||||
r1.name = 'test';
|
||||
// no value attribute
|
||||
|
||||
const r2 = document.createElement('input');
|
||||
r2.type = 'radio';
|
||||
r2.name = 'test';
|
||||
r2.value = 'on';
|
||||
|
||||
const r3 = document.createElement('input');
|
||||
r3.type = 'radio';
|
||||
r3.name = 'test';
|
||||
r3.value = 'other';
|
||||
|
||||
form.appendChild(r1);
|
||||
form.appendChild(r2);
|
||||
form.appendChild(r3);
|
||||
document.body.appendChild(form);
|
||||
|
||||
const radios = form.elements.namedItem('test');
|
||||
radios.value = 'on';
|
||||
|
||||
// Should check first match (r1 with no value attribute)
|
||||
testing.expectEqual(true, r1.checked);
|
||||
testing.expectEqual(false, r2.checked);
|
||||
testing.expectEqual(false, r3.checked);
|
||||
|
||||
form.remove();
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="live_collection">
|
||||
{
|
||||
const form = document.createElement('form');
|
||||
const r1 = document.createElement('input');
|
||||
r1.type = 'radio';
|
||||
r1.name = 'dynamic';
|
||||
r1.value = 'a';
|
||||
|
||||
const r2 = document.createElement('input');
|
||||
r2.type = 'radio';
|
||||
r2.name = 'dynamic';
|
||||
r2.value = 'b';
|
||||
|
||||
form.appendChild(r1);
|
||||
form.appendChild(r2);
|
||||
document.body.appendChild(form);
|
||||
|
||||
const radios = form.elements.namedItem('dynamic');
|
||||
testing.expectEqual('RadioNodeList', radios.constructor.name);
|
||||
testing.expectEqual(2, radios.length);
|
||||
|
||||
const r3 = document.createElement('input');
|
||||
r3.type = 'radio';
|
||||
r3.name = 'dynamic';
|
||||
r3.value = 'c';
|
||||
form.appendChild(r3);
|
||||
|
||||
testing.expectEqual(3, radios.length);
|
||||
testing.expectEqual('c', radios[2].value);
|
||||
|
||||
r1.remove();
|
||||
testing.expectEqual(2, radios.length);
|
||||
testing.expectEqual('b', radios[0].value);
|
||||
|
||||
form.remove();
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Test non-radio elements with same name -->
|
||||
<form id="mixed_form">
|
||||
<input type="text" name="mixed" value="text1">
|
||||
<input type="text" name="mixed" value="text2">
|
||||
</form>
|
||||
|
||||
<script id="non_radio_elements">
|
||||
{
|
||||
const form = $('#mixed_form');
|
||||
const result = form.elements.namedItem('mixed');
|
||||
|
||||
// Should still return RadioNodeList even for non-radio elements
|
||||
testing.expectEqual('RadioNodeList', result.constructor.name);
|
||||
testing.expectEqual(2, result.length);
|
||||
|
||||
// getValue should return "" for non-radio elements
|
||||
testing.expectEqual('', result.value);
|
||||
}
|
||||
</script>
|
||||
56
src/browser/tests/crypto.html
Normal file
56
src/browser/tests/crypto.html
Normal file
@@ -0,0 +1,56 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="testing.js"></script>
|
||||
|
||||
<script id=getRandomValues>
|
||||
function isRandom(ta) {
|
||||
let uniq = new Set(Array.from(ta));
|
||||
testing.expectEqual(true, (uniq.size / ta.length) * 100 > 0.7)
|
||||
}
|
||||
{
|
||||
let tu8a = new Uint8Array(100)
|
||||
testing.expectEqual(tu8a, crypto.getRandomValues(tu8a))
|
||||
isRandom(tu8a)
|
||||
|
||||
let ti8a = new Int8Array(100)
|
||||
testing.expectEqual(ti8a, crypto.getRandomValues(ti8a))
|
||||
isRandom(ti8a)
|
||||
}
|
||||
|
||||
// {
|
||||
// let tu16a = new Uint16Array(100)
|
||||
// testing.expectEqual(tu16a, crypto.getRandomValues(tu16a))
|
||||
// isRandom(tu16a)
|
||||
|
||||
// let ti16a = new Int16Array(100)
|
||||
// testing.expectEqual(ti16a, crypto.getRandomValues(ti16a))
|
||||
// isRandom(ti16a)
|
||||
// }
|
||||
|
||||
// {
|
||||
// let tu32a = new Uint32Array(100)
|
||||
// testing.expectEqual(tu32a, crypto.getRandomValues(tu32a))
|
||||
// isRandom(tu32a)
|
||||
|
||||
// let ti32a = new Int32Array(100)
|
||||
// testing.expectEqual(ti32a, crypto.getRandomValues(ti32a))
|
||||
// isRandom(ti32a)
|
||||
// }
|
||||
|
||||
// {
|
||||
// let tu64a = new BigUint64Array(100)
|
||||
// testing.expectEqual(tu64a, crypto.getRandomValues(tu64a))
|
||||
// isRandom(tu64a)
|
||||
|
||||
// let ti64a = new BigInt64Array(100)
|
||||
// testing.expectEqual(ti64a, crypto.getRandomValues(ti64a))
|
||||
// isRandom(ti64a)
|
||||
// }
|
||||
</script>
|
||||
|
||||
<!-- <script id="randomUUID">
|
||||
const uuid = crypto.randomUUID();
|
||||
testing.expectEqual('string', typeof uuid);
|
||||
testing.expectEqual(36, uuid.length);
|
||||
const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
testing.expectEqual(true, regex.test(uuid));
|
||||
</script> -->
|
||||
69
src/browser/tests/css.html
Normal file
69
src/browser/tests/css.html
Normal file
@@ -0,0 +1,69 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="testing.js"></script>
|
||||
|
||||
<script id="exists">
|
||||
testing.expectEqual('object', typeof CSS);
|
||||
testing.expectEqual('function', typeof CSS.escape);
|
||||
testing.expectEqual('function', typeof CSS.supports);
|
||||
</script>
|
||||
|
||||
<script id="escape_basic">
|
||||
{
|
||||
testing.expectEqual('hello', CSS.escape('hello'));
|
||||
testing.expectEqual('world123', CSS.escape('world123'));
|
||||
testing.expectEqual('foo-bar', CSS.escape('foo-bar'));
|
||||
testing.expectEqual('_test', CSS.escape('_test'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="escape_first_character">
|
||||
{
|
||||
testing.expectEqual('\\30 abc', CSS.escape('0abc'));
|
||||
testing.expectEqual('\\31 23', CSS.escape('123'));
|
||||
testing.expectEqual('\\-test', CSS.escape('-test'));
|
||||
testing.expectEqual('\\--test', CSS.escape('--test'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="escape_special_characters">
|
||||
{
|
||||
testing.expectEqual('hello\\ world', CSS.escape('hello world'));
|
||||
testing.expectEqual('test\\!', CSS.escape('test!'));
|
||||
testing.expectEqual('foo\\#bar', CSS.escape('foo#bar'));
|
||||
testing.expectEqual('a\\(b\\)', CSS.escape('a(b)'));
|
||||
testing.expectEqual('test\\@example', CSS.escape('test@example'));
|
||||
testing.expectEqual('a\\[b\\]', CSS.escape('a[b]'));
|
||||
testing.expectEqual('a\\{b\\}', CSS.escape('a{b}'));
|
||||
testing.expectEqual('test\\:value', CSS.escape('test:value'));
|
||||
testing.expectEqual('a\\.b', CSS.escape('a.b'));
|
||||
testing.expectEqual('a\\,b', CSS.escape('a,b'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="escape_quotes">
|
||||
{
|
||||
testing.expectEqual('test\\"value', CSS.escape('test"value'));
|
||||
testing.expectEqual('test\\\'value', CSS.escape("test'value"));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="supports_basic">
|
||||
{
|
||||
testing.expectEqual(true, CSS.supports('display', 'block'));
|
||||
testing.expectEqual(true, CSS.supports('position', 'relative'));
|
||||
testing.expectEqual(true, CSS.supports('width', '100px'));
|
||||
testing.expectEqual(true, CSS.supports('color', 'red'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="supports_common_properties">
|
||||
{
|
||||
testing.expectEqual(true, CSS.supports('margin', '10px'));
|
||||
testing.expectEqual(true, CSS.supports('padding', '5px'));
|
||||
testing.expectEqual(true, CSS.supports('border', '1px solid black'));
|
||||
testing.expectEqual(true, CSS.supports('background-color', 'blue'));
|
||||
testing.expectEqual(true, CSS.supports('font-size', '16px'));
|
||||
testing.expectEqual(true, CSS.supports('opacity', '0.5'));
|
||||
testing.expectEqual(true, CSS.supports('z-index', '10'));
|
||||
}
|
||||
</script>
|
||||
37
src/browser/tests/css/media_query_list.html
Normal file
37
src/browser/tests/css/media_query_list.html
Normal file
@@ -0,0 +1,37 @@
|
||||
<!DOCTYPE html>
|
||||
<head>
|
||||
<script src="../testing.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
</body>
|
||||
|
||||
<script id=matchMedia_basic>
|
||||
{
|
||||
const mql = window.matchMedia('(min-width: 600px)');
|
||||
testing.expectEqual('object', typeof mql);
|
||||
testing.expectEqual('(min-width: 600px)', mql.media);
|
||||
testing.expectEqual(false, mql.matches);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=matchMedia_different_queries>
|
||||
{
|
||||
const mql1 = window.matchMedia('(max-width: 1024px)');
|
||||
testing.expectEqual('(max-width: 1024px)', mql1.media);
|
||||
testing.expectEqual(false, mql1.matches);
|
||||
|
||||
const mql2 = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
testing.expectEqual('(prefers-color-scheme: dark)', mql2.media);
|
||||
testing.expectEqual(false, mql2.matches);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=matchMedia_event_target>
|
||||
{
|
||||
const mql = window.matchMedia('(orientation: portrait)');
|
||||
testing.expectEqual('function', typeof mql.addEventListener);
|
||||
testing.expectEqual('function', typeof mql.removeEventListener);
|
||||
testing.expectEqual('function', typeof mql.dispatchEvent);
|
||||
}
|
||||
</script>
|
||||
207
src/browser/tests/css/stylesheet.html
Normal file
207
src/browser/tests/css/stylesheet.html
Normal file
@@ -0,0 +1,207 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id="document_styleSheets">
|
||||
{
|
||||
const sheets = document.styleSheets;
|
||||
testing.expectTrue(sheets !== null);
|
||||
testing.expectEqual(0, sheets.length);
|
||||
|
||||
// Should return same instance
|
||||
const sheets2 = document.styleSheets;
|
||||
testing.expectTrue(sheets === sheets2);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleSheet_basic">
|
||||
{
|
||||
const sheets = document.styleSheets;
|
||||
testing.expectEqual('StyleSheetList', sheets.constructor.name);
|
||||
|
||||
// Test indexed access on empty list
|
||||
testing.expectEqual(undefined, sheets[0]);
|
||||
testing.expectEqual(undefined, sheets[99]);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_basic">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Set single property
|
||||
style.cssText = 'color: red';
|
||||
testing.expectEqual('red', style.getPropertyValue('color'));
|
||||
testing.expectEqual(1, style.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_multiple">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Set multiple properties
|
||||
style.cssText = 'color: red; background: blue; margin: 10px';
|
||||
testing.expectEqual('red', style.getPropertyValue('color'));
|
||||
testing.expectEqual('blue', style.getPropertyValue('background'));
|
||||
testing.expectEqual('10px', style.getPropertyValue('margin'));
|
||||
testing.expectEqual(3, style.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_important">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Set property with !important
|
||||
style.cssText = 'color: red !important';
|
||||
testing.expectEqual('red', style.getPropertyValue('color'));
|
||||
testing.expectEqual('important', style.getPropertyPriority('color'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_important_multiple">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Mix of important and non-important
|
||||
style.cssText = 'color: red !important; background: blue; margin: 10px !important';
|
||||
testing.expectEqual('important', style.getPropertyPriority('color'));
|
||||
testing.expectEqual('', style.getPropertyPriority('background'));
|
||||
testing.expectEqual('important', style.getPropertyPriority('margin'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_whitespace">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Test whitespace handling
|
||||
style.cssText = ' color : red ; background : blue ';
|
||||
testing.expectEqual('red', style.getPropertyValue('color'));
|
||||
testing.expectEqual('blue', style.getPropertyValue('background'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_trailing_semicolon">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Trailing semicolon should be handled
|
||||
style.cssText = 'color: red;';
|
||||
testing.expectEqual('red', style.getPropertyValue('color'));
|
||||
testing.expectEqual(1, style.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_no_semicolon">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Single property without semicolon
|
||||
style.cssText = 'color: red';
|
||||
testing.expectEqual('red', style.getPropertyValue('color'));
|
||||
testing.expectEqual(1, style.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_empty_declarations">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Multiple semicolons should be ignored
|
||||
style.cssText = 'color: red;;; background: blue';
|
||||
testing.expectEqual('red', style.getPropertyValue('color'));
|
||||
testing.expectEqual('blue', style.getPropertyValue('background'));
|
||||
testing.expectEqual(2, style.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_replace">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Set initial properties
|
||||
style.cssText = 'color: red; background: blue';
|
||||
testing.expectEqual(2, style.length);
|
||||
|
||||
// Replace with new properties
|
||||
style.cssText = 'margin: 10px';
|
||||
testing.expectEqual('', style.getPropertyValue('color'));
|
||||
testing.expectEqual('', style.getPropertyValue('background'));
|
||||
testing.expectEqual('10px', style.getPropertyValue('margin'));
|
||||
testing.expectEqual(1, style.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_clear">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
style.cssText = 'color: red; background: blue';
|
||||
testing.expectEqual(2, style.length);
|
||||
|
||||
// Clear all properties
|
||||
style.cssText = '';
|
||||
testing.expectEqual(0, style.length);
|
||||
testing.expectEqual('', style.getPropertyValue('color'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_colon_in_value">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// URL value with colon
|
||||
style.cssText = 'background: url(http://example.com/image.png)';
|
||||
testing.expectEqual('url(http://example.com/image.png)', style.getPropertyValue('background'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_important_whitespace">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Various whitespace around !important
|
||||
style.cssText = 'color: red!important';
|
||||
testing.expectEqual('important', style.getPropertyPriority('color'));
|
||||
|
||||
style.cssText = 'color: red ! important';
|
||||
testing.expectEqual('important', style.getPropertyPriority('color'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_case_insensitive_property">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Property names should be normalized to lowercase
|
||||
style.cssText = 'COLOR: red; BACKGROUND: blue';
|
||||
testing.expectEqual('red', style.getPropertyValue('color'));
|
||||
testing.expectEqual('blue', style.getPropertyValue('background'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_setCssText_exclamation_not_important">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const style = div.style;
|
||||
|
||||
// Exclamation mark without "important" should be kept in value
|
||||
style.cssText = 'content: "hello!"';
|
||||
testing.expectEqual('"hello!"', style.getPropertyValue('content'));
|
||||
testing.expectEqual('', style.getPropertyPriority('content'));
|
||||
}
|
||||
</script>
|
||||
165
src/browser/tests/custom_elements/attribute_changed.html
Normal file
165
src/browser/tests/custom_elements/attribute_changed.html
Normal file
@@ -0,0 +1,165 @@
|
||||
<!DOCTYPE html>
|
||||
<body>
|
||||
<script src="../testing.js"></script>
|
||||
<script id="attribute_changed">
|
||||
{
|
||||
let callbackCalls = [];
|
||||
|
||||
class MyElement extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['data-foo', 'data-bar'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
callbackCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('my-element', MyElement);
|
||||
|
||||
const el = document.createElement('my-element');
|
||||
testing.expectEqual(0, callbackCalls.length);
|
||||
|
||||
el.setAttribute('data-foo', 'value1');
|
||||
testing.expectEqual(1, callbackCalls.length);
|
||||
testing.expectEqual('data-foo', callbackCalls[0].name);
|
||||
testing.expectEqual(null, callbackCalls[0].oldValue);
|
||||
testing.expectEqual('value1', callbackCalls[0].newValue);
|
||||
|
||||
el.setAttribute('data-foo', 'value2');
|
||||
testing.expectEqual(2, callbackCalls.length);
|
||||
testing.expectEqual('data-foo', callbackCalls[1].name);
|
||||
testing.expectEqual('value1', callbackCalls[1].oldValue);
|
||||
testing.expectEqual('value2', callbackCalls[1].newValue);
|
||||
|
||||
el.setAttribute('data-bar', 'bar-value');
|
||||
testing.expectEqual(3, callbackCalls.length);
|
||||
testing.expectEqual('data-bar', callbackCalls[2].name);
|
||||
testing.expectEqual(null, callbackCalls[2].oldValue);
|
||||
testing.expectEqual('bar-value', callbackCalls[2].newValue);
|
||||
}
|
||||
|
||||
{
|
||||
let callbackCalls = [];
|
||||
|
||||
class ObservedElement extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['watched'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
callbackCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('observed-element', ObservedElement);
|
||||
|
||||
const el = document.createElement('observed-element');
|
||||
el.setAttribute('unwatched', 'value');
|
||||
testing.expectEqual(0, callbackCalls.length);
|
||||
|
||||
el.setAttribute('watched', 'value');
|
||||
testing.expectEqual(1, callbackCalls.length);
|
||||
}
|
||||
|
||||
{
|
||||
let callbackCalls = [];
|
||||
|
||||
class RemoveAttrElement extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['test'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
callbackCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('remove-attr-element', RemoveAttrElement);
|
||||
|
||||
const el = document.createElement('remove-attr-element');
|
||||
el.setAttribute('test', 'value');
|
||||
testing.expectEqual(1, callbackCalls.length);
|
||||
|
||||
el.removeAttribute('test');
|
||||
testing.expectEqual(2, callbackCalls.length);
|
||||
testing.expectEqual('test', callbackCalls[1].name);
|
||||
testing.expectEqual('value', callbackCalls[1].oldValue);
|
||||
testing.expectEqual(null, callbackCalls[1].newValue);
|
||||
}
|
||||
|
||||
{
|
||||
let callbackCalls = [];
|
||||
|
||||
class NoObservedElement extends HTMLElement {
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
callbackCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('no-observed-element', NoObservedElement);
|
||||
|
||||
const el = document.createElement('no-observed-element');
|
||||
el.setAttribute('test', 'value');
|
||||
testing.expectEqual(0, callbackCalls.length);
|
||||
}
|
||||
|
||||
{
|
||||
let callbackCalls = [];
|
||||
|
||||
class UpgradeAttrElement extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['existing'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
callbackCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
const el = document.createElement('upgrade-attr-element');
|
||||
el.setAttribute('existing', 'before-upgrade');
|
||||
testing.expectEqual(0, callbackCalls.length);
|
||||
|
||||
customElements.define('upgrade-attr-element', UpgradeAttrElement);
|
||||
testing.expectEqual(0, callbackCalls.length);
|
||||
|
||||
document.body.appendChild(el);
|
||||
|
||||
testing.expectEqual(1, callbackCalls.length);
|
||||
testing.expectEqual('existing', callbackCalls[0].name);
|
||||
testing.expectEqual(null, callbackCalls[0].oldValue);
|
||||
testing.expectEqual('before-upgrade', callbackCalls[0].newValue);
|
||||
|
||||
el.setAttribute('existing', 'after-upgrade');
|
||||
testing.expectEqual(2, callbackCalls.length);
|
||||
testing.expectEqual('existing', callbackCalls[1].name);
|
||||
testing.expectEqual('before-upgrade', callbackCalls[1].oldValue);
|
||||
testing.expectEqual('after-upgrade', callbackCalls[1].newValue);
|
||||
}
|
||||
|
||||
{
|
||||
let callbackCalls = [];
|
||||
|
||||
class SetAttrMethodElement extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['test'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
callbackCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('set-attr-method-element', SetAttrMethodElement);
|
||||
|
||||
const el = document.createElement('set-attr-method-element');
|
||||
el.setAttribute('test', 'initial');
|
||||
testing.expectEqual(1, callbackCalls.length);
|
||||
|
||||
el.setAttribute('test', 'initial');
|
||||
testing.expectEqual(2, callbackCalls.length);
|
||||
testing.expectEqual('initial', callbackCalls[1].oldValue);
|
||||
testing.expectEqual('initial', callbackCalls[1].newValue);
|
||||
}
|
||||
</script>
|
||||
137
src/browser/tests/custom_elements/built_in.html
Normal file
137
src/browser/tests/custom_elements/built_in.html
Normal file
@@ -0,0 +1,137 @@
|
||||
<!DOCTYPE html>
|
||||
<body>
|
||||
<script src="../testing.js"></script>
|
||||
<script id="built_in">
|
||||
{
|
||||
class FancyButton extends HTMLElement {}
|
||||
customElements.define('fancy-button', FancyButton, { extends: 'button' });
|
||||
|
||||
const definition = customElements.get('fancy-button');
|
||||
testing.expectEqual(FancyButton, definition);
|
||||
}
|
||||
|
||||
{
|
||||
let threw = false;
|
||||
try {
|
||||
class BadExtends extends HTMLElement {}
|
||||
customElements.define('bad-extends', BadExtends, { extends: 'not-a-real-element' });
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
testing.expectEqual(true, threw);
|
||||
}
|
||||
|
||||
{
|
||||
let threw = false;
|
||||
try {
|
||||
class ExtendCustom extends HTMLElement {}
|
||||
customElements.define('extend-custom', ExtendCustom, { extends: 'fancy-button' });
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
testing.expectEqual(true, threw);
|
||||
}
|
||||
|
||||
{
|
||||
class FancyParagraph extends HTMLElement {}
|
||||
customElements.define('fancy-paragraph', FancyParagraph, { extends: 'p' });
|
||||
|
||||
const definition = customElements.get('fancy-paragraph');
|
||||
testing.expectEqual(FancyParagraph, definition);
|
||||
}
|
||||
|
||||
{
|
||||
let constructorCalled = 0;
|
||||
|
||||
class ConstructedButton extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
constructorCalled++;
|
||||
this.clicked = false;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('constructed-button', ConstructedButton, { extends: 'button' });
|
||||
|
||||
const btn = document.createElement('button', { is: 'constructed-button' });
|
||||
testing.expectEqual(1, constructorCalled);
|
||||
testing.expectEqual('BUTTON', btn.tagName);
|
||||
testing.expectEqual(false, btn.clicked);
|
||||
}
|
||||
|
||||
{
|
||||
class WrongTag extends HTMLElement {}
|
||||
customElements.define('wrong-tag', WrongTag, { extends: 'button' });
|
||||
|
||||
const div = document.createElement('div', { is: 'wrong-tag' });
|
||||
testing.expectEqual('DIV', div.tagName);
|
||||
}
|
||||
|
||||
{
|
||||
let connectedCount = 0;
|
||||
let disconnectedCount = 0;
|
||||
let attributeChanges = [];
|
||||
|
||||
class LifecycleButton extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['data-test'];
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
connectedCount++;
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
disconnectedCount++;
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
attributeChanges.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('lifecycle-button', LifecycleButton, { extends: 'button' });
|
||||
|
||||
const btn = document.createElement('button', { is: 'lifecycle-button' });
|
||||
testing.expectEqual(0, connectedCount);
|
||||
|
||||
document.body.appendChild(btn);
|
||||
testing.expectEqual(1, connectedCount);
|
||||
|
||||
btn.setAttribute('data-test', 'value1');
|
||||
testing.expectEqual(1, attributeChanges.length);
|
||||
testing.expectEqual('data-test', attributeChanges[0].name);
|
||||
testing.expectEqual(null, attributeChanges[0].oldValue);
|
||||
testing.expectEqual('value1', attributeChanges[0].newValue);
|
||||
|
||||
btn.remove();
|
||||
testing.expectEqual(1, disconnectedCount);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script>
|
||||
{
|
||||
let constructorCalled = 0;
|
||||
let connectedCalled = 0;
|
||||
|
||||
class ParsedButton extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
constructorCalled++;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
connectedCalled++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('parsed-button', ParsedButton, { extends: 'button' });
|
||||
}
|
||||
</script>
|
||||
<button is="parsed-button" id="parsed"></button>
|
||||
<script>
|
||||
{
|
||||
const btn = document.getElementById('parsed');
|
||||
testing.expectEqual('BUTTON', btn.tagName);
|
||||
}
|
||||
</script>
|
||||
94
src/browser/tests/custom_elements/connected.html
Normal file
94
src/browser/tests/custom_elements/connected.html
Normal file
@@ -0,0 +1,94 @@
|
||||
<!DOCTYPE html>
|
||||
<body>
|
||||
<script src="../testing.js"></script>
|
||||
<script id="connected">
|
||||
{
|
||||
let connectedCount = 0;
|
||||
|
||||
class MyElement extends HTMLElement {
|
||||
connectedCallback() {
|
||||
connectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('my-element', MyElement);
|
||||
|
||||
const el = document.createElement('my-element');
|
||||
testing.expectEqual(0, connectedCount);
|
||||
|
||||
document.body.appendChild(el);
|
||||
testing.expectEqual(1, connectedCount);
|
||||
}
|
||||
|
||||
{
|
||||
let order = [];
|
||||
|
||||
class ParentElement extends HTMLElement {
|
||||
connectedCallback() {
|
||||
order.push('parent');
|
||||
}
|
||||
}
|
||||
|
||||
class ChildElement extends HTMLElement {
|
||||
connectedCallback() {
|
||||
order.push('child');
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('parent-element', ParentElement);
|
||||
customElements.define('child-element', ChildElement);
|
||||
|
||||
const parent = document.createElement('parent-element');
|
||||
const child = document.createElement('child-element');
|
||||
parent.appendChild(child);
|
||||
|
||||
testing.expectEqual(0, order.length);
|
||||
|
||||
document.body.appendChild(parent);
|
||||
testing.expectEqual(2, order.length);
|
||||
testing.expectEqual('parent', order[0]);
|
||||
testing.expectEqual('child', order[1]);
|
||||
}
|
||||
|
||||
{
|
||||
let connectedCount = 0;
|
||||
|
||||
class MoveElement extends HTMLElement {
|
||||
connectedCallback() {
|
||||
connectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('move-element', MoveElement);
|
||||
|
||||
const el = document.createElement('move-element');
|
||||
document.body.appendChild(el);
|
||||
testing.expectEqual(1, connectedCount);
|
||||
|
||||
const div = document.createElement('div');
|
||||
document.body.appendChild(div);
|
||||
div.appendChild(el);
|
||||
testing.expectEqual(1, connectedCount);
|
||||
}
|
||||
|
||||
{
|
||||
let connectedCount = 0;
|
||||
|
||||
class DetachedElement extends HTMLElement {
|
||||
connectedCallback() {
|
||||
connectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('detached-element', DetachedElement);
|
||||
|
||||
const container = document.createElement('div');
|
||||
const el = document.createElement('detached-element');
|
||||
container.appendChild(el);
|
||||
testing.expectEqual(0, connectedCount);
|
||||
|
||||
document.body.appendChild(container);
|
||||
testing.expectEqual(1, connectedCount);
|
||||
}
|
||||
</script>
|
||||
|
||||
122
src/browser/tests/custom_elements/connected_from_parser.html
Normal file
122
src/browser/tests/custom_elements/connected_from_parser.html
Normal file
@@ -0,0 +1,122 @@
|
||||
<!DOCTYPE html>
|
||||
<head>
|
||||
<script src="../testing.js"></script>
|
||||
<script>
|
||||
{
|
||||
// Define the custom element BEFORE the HTML is parsed
|
||||
window.preParseConnectedCount = 0;
|
||||
|
||||
class PreParseElement extends HTMLElement {
|
||||
connectedCallback() {
|
||||
window.preParseConnectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('pre-parse-element', PreParseElement);
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<!-- This element is in the HTML and should have connectedCallback invoked -->
|
||||
<pre-parse-element id="static-element"></pre-parse-element>
|
||||
|
||||
<script id="test-static-element">
|
||||
{
|
||||
// connectedCallback should have been called for the element in HTML
|
||||
testing.expectEqual(1, window.preParseConnectedCount);
|
||||
|
||||
const el = document.getElementById('static-element');
|
||||
testing.expectTrue(el !== null);
|
||||
testing.expectEqual('PRE-PARSE-ELEMENT', el.tagName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="test-programmatic-still-works">
|
||||
{
|
||||
// Reset counter
|
||||
window.preParseConnectedCount = 0;
|
||||
|
||||
// This should still work (programmatic creation)
|
||||
const el = document.createElement('pre-parse-element');
|
||||
testing.expectEqual(0, window.preParseConnectedCount);
|
||||
|
||||
document.body.appendChild(el);
|
||||
testing.expectEqual(1, window.preParseConnectedCount);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script>
|
||||
{
|
||||
window.nestedParentCount = 0;
|
||||
window.nestedChildCount = 0;
|
||||
|
||||
class NestedParent extends HTMLElement {
|
||||
connectedCallback() {
|
||||
window.nestedParentCount++;
|
||||
}
|
||||
}
|
||||
|
||||
class NestedChild extends HTMLElement {
|
||||
connectedCallback() {
|
||||
window.nestedChildCount++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('nested-parent', NestedParent);
|
||||
customElements.define('nested-child', NestedChild);
|
||||
}
|
||||
</script>
|
||||
|
||||
<nested-parent id="parent-element">
|
||||
<nested-child id="child-element"></nested-child>
|
||||
</nested-parent>
|
||||
|
||||
<script id="verify-nested">
|
||||
{
|
||||
// Both parent and child should have connectedCallback invoked
|
||||
testing.expectEqual(1, window.nestedParentCount);
|
||||
testing.expectEqual(1, window.nestedChildCount);
|
||||
|
||||
const parent = document.getElementById('parent-element');
|
||||
const child = document.getElementById('child-element');
|
||||
testing.expectTrue(parent !== null);
|
||||
testing.expectTrue(child !== null);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script>
|
||||
{
|
||||
// Test attributeChangedCallback for initial attributes during parsing
|
||||
window.attrChangedCalls = [];
|
||||
|
||||
class AttrElement extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['foo', 'bar'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
window.attrChangedCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('attr-element', AttrElement);
|
||||
}
|
||||
</script>
|
||||
|
||||
<attr-element foo="value1" bar="value2" ignored="value3"></attr-element>
|
||||
|
||||
<script id="verify-attribute-changed">
|
||||
{
|
||||
// attributeChangedCallback should have been called for initial attributes
|
||||
testing.expectEqual(2, window.attrChangedCalls.length);
|
||||
|
||||
testing.expectEqual('foo', window.attrChangedCalls[0].name);
|
||||
testing.expectEqual(null, window.attrChangedCalls[0].oldValue);
|
||||
testing.expectEqual('value1', window.attrChangedCalls[0].newValue);
|
||||
|
||||
testing.expectEqual('bar', window.attrChangedCalls[1].name);
|
||||
testing.expectEqual(null, window.attrChangedCalls[1].oldValue);
|
||||
testing.expectEqual('value2', window.attrChangedCalls[1].newValue);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
55
src/browser/tests/custom_elements/constructor.html
Normal file
55
src/browser/tests/custom_elements/constructor.html
Normal file
@@ -0,0 +1,55 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
<script id="constructor">
|
||||
{
|
||||
let constructorCalled = false;
|
||||
let constructorThis = null;
|
||||
|
||||
class MyElement extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
constructorCalled = true;
|
||||
constructorThis = this;
|
||||
this.customProperty = 'initialized';
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('my-element', MyElement);
|
||||
|
||||
const el = document.createElement('my-element');
|
||||
testing.expectEqual(true, constructorCalled);
|
||||
testing.expectEqual(el, constructorThis);
|
||||
testing.expectEqual('initialized', el.customProperty);
|
||||
}
|
||||
|
||||
{
|
||||
class CounterElement extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
this.count = 0;
|
||||
}
|
||||
|
||||
increment() {
|
||||
this.count++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('counter-element', CounterElement);
|
||||
|
||||
const counter = document.createElement('counter-element');
|
||||
testing.expectEqual(0, counter.count);
|
||||
counter.increment();
|
||||
testing.expectEqual(1, counter.count);
|
||||
counter.increment();
|
||||
testing.expectEqual(2, counter.count);
|
||||
}
|
||||
|
||||
{
|
||||
class NoConstructorElement extends HTMLElement {}
|
||||
|
||||
customElements.define('no-constructor-element', NoConstructorElement);
|
||||
|
||||
const el = document.createElement('no-constructor-element');
|
||||
testing.expectEqual('NO-CONSTRUCTOR-ELEMENT', el.tagName);
|
||||
}
|
||||
</script>
|
||||
151
src/browser/tests/custom_elements/disconnected.html
Normal file
151
src/browser/tests/custom_elements/disconnected.html
Normal file
@@ -0,0 +1,151 @@
|
||||
<!DOCTYPE html>
|
||||
<body>
|
||||
<script src="../testing.js"></script>
|
||||
<script id="disconnected">
|
||||
{
|
||||
let disconnectedCount = 0;
|
||||
|
||||
class MyElement extends HTMLElement {
|
||||
disconnectedCallback() {
|
||||
disconnectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('my-element', MyElement);
|
||||
|
||||
const el = document.createElement('my-element');
|
||||
document.body.appendChild(el);
|
||||
testing.expectEqual(0, disconnectedCount);
|
||||
|
||||
el.remove();
|
||||
testing.expectEqual(1, disconnectedCount);
|
||||
}
|
||||
|
||||
{
|
||||
let order = [];
|
||||
|
||||
class ParentElement extends HTMLElement {
|
||||
disconnectedCallback() {
|
||||
order.push('parent');
|
||||
}
|
||||
}
|
||||
|
||||
class ChildElement extends HTMLElement {
|
||||
disconnectedCallback() {
|
||||
order.push('child');
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('parent-element', ParentElement);
|
||||
customElements.define('child-element', ChildElement);
|
||||
|
||||
const parent = document.createElement('parent-element');
|
||||
const child = document.createElement('child-element');
|
||||
parent.appendChild(child);
|
||||
document.body.appendChild(parent);
|
||||
|
||||
testing.expectEqual(0, order.length);
|
||||
|
||||
parent.remove();
|
||||
testing.expectEqual(2, order.length);
|
||||
testing.expectEqual('parent', order[0]);
|
||||
testing.expectEqual('child', order[1]);
|
||||
}
|
||||
|
||||
{
|
||||
let disconnectedCount = 0;
|
||||
|
||||
class RemoveChildElement extends HTMLElement {
|
||||
disconnectedCallback() {
|
||||
disconnectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('remove-child-element', RemoveChildElement);
|
||||
|
||||
const el = document.createElement('remove-child-element');
|
||||
document.body.appendChild(el);
|
||||
testing.expectEqual(0, disconnectedCount);
|
||||
|
||||
document.body.removeChild(el);
|
||||
testing.expectEqual(1, disconnectedCount);
|
||||
}
|
||||
|
||||
{
|
||||
let disconnectedCount = 0;
|
||||
|
||||
class MoveElement extends HTMLElement {
|
||||
disconnectedCallback() {
|
||||
disconnectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('move-element', MoveElement);
|
||||
|
||||
const el = document.createElement('move-element');
|
||||
document.body.appendChild(el);
|
||||
testing.expectEqual(0, disconnectedCount);
|
||||
|
||||
const div = document.createElement('div');
|
||||
document.body.appendChild(div);
|
||||
div.appendChild(el);
|
||||
testing.expectEqual(0, disconnectedCount);
|
||||
}
|
||||
|
||||
{
|
||||
let disconnectedCount = 0;
|
||||
|
||||
class ReplaceChildElement extends HTMLElement {
|
||||
disconnectedCallback() {
|
||||
disconnectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('replace-child-element', ReplaceChildElement);
|
||||
|
||||
const el = document.createElement('replace-child-element');
|
||||
const replacement = document.createElement('div');
|
||||
document.body.appendChild(el);
|
||||
testing.expectEqual(0, disconnectedCount);
|
||||
|
||||
document.body.replaceChild(replacement, el);
|
||||
testing.expectEqual(1, disconnectedCount);
|
||||
}
|
||||
|
||||
{
|
||||
let connectedCount = 0;
|
||||
let disconnectedCount = 0;
|
||||
|
||||
class LifecycleElement extends HTMLElement {
|
||||
connectedCallback() {
|
||||
connectedCount++;
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
disconnectedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('lifecycle-element', LifecycleElement);
|
||||
|
||||
const el = document.createElement('lifecycle-element');
|
||||
testing.expectEqual(0, connectedCount);
|
||||
testing.expectEqual(0, disconnectedCount);
|
||||
|
||||
document.body.appendChild(el);
|
||||
testing.expectEqual(1, connectedCount);
|
||||
testing.expectEqual(0, disconnectedCount);
|
||||
|
||||
el.remove();
|
||||
testing.expectEqual(1, connectedCount);
|
||||
testing.expectEqual(1, disconnectedCount);
|
||||
|
||||
document.body.appendChild(el);
|
||||
testing.expectEqual(2, connectedCount);
|
||||
testing.expectEqual(1, disconnectedCount);
|
||||
|
||||
el.remove();
|
||||
testing.expectEqual(2, connectedCount);
|
||||
testing.expectEqual(2, disconnectedCount);
|
||||
}
|
||||
</script>
|
||||
121
src/browser/tests/custom_elements/registry.html
Normal file
121
src/browser/tests/custom_elements/registry.html
Normal file
@@ -0,0 +1,121 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
<script id="registry">
|
||||
{
|
||||
testing.expectEqual(true, window.customElements !== undefined);
|
||||
testing.expectEqual('function', typeof window.customElements.define);
|
||||
testing.expectEqual('function', typeof window.customElements.get);
|
||||
}
|
||||
|
||||
{
|
||||
class MyElement extends HTMLElement {}
|
||||
customElements.define('my-element', MyElement);
|
||||
const retrieved = customElements.get('my-element');
|
||||
testing.expectEqual(true, retrieved === MyElement);
|
||||
}
|
||||
|
||||
{
|
||||
const retrieved = customElements.get('not-defined');
|
||||
testing.expectEqual(undefined, retrieved);
|
||||
}
|
||||
|
||||
{
|
||||
class AnotherElement extends HTMLElement {}
|
||||
customElements.define('another-element', AnotherElement);
|
||||
|
||||
let threw = false;
|
||||
try {
|
||||
customElements.define('another-element', AnotherElement);
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
testing.expectEqual(true, threw);
|
||||
}
|
||||
|
||||
{
|
||||
let threw = false;
|
||||
try {
|
||||
customElements.define('nohyphen', class extends HTMLElement {});
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
testing.expectEqual(true, threw);
|
||||
}
|
||||
|
||||
{
|
||||
let threw = false;
|
||||
try {
|
||||
customElements.define('UPPERCASE-ELEMENT', class extends HTMLElement {});
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
testing.expectEqual(true, threw);
|
||||
}
|
||||
|
||||
{
|
||||
let threw = false;
|
||||
try {
|
||||
customElements.define('annotation-xml', class extends HTMLElement {});
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
testing.expectEqual(true, threw);
|
||||
}
|
||||
|
||||
{
|
||||
class TestElement extends HTMLElement {}
|
||||
customElements.define('test-element', TestElement);
|
||||
|
||||
const el = document.createElement('test-element');
|
||||
testing.expectEqual('TEST-ELEMENT', el.tagName);
|
||||
testing.expectEqual(true, el instanceof HTMLElement);
|
||||
}
|
||||
|
||||
{
|
||||
const el = document.createElement('undefined-element');
|
||||
testing.expectEqual('UNDEFINED-ELEMENT', el.tagName);
|
||||
}
|
||||
|
||||
{
|
||||
const el = document.createElement('no-hyphen-invalid');
|
||||
testing.expectEqual('NO-HYPHEN-INVALID', el.tagName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="whenDefined_already_defined">
|
||||
{
|
||||
class AlreadyDefined extends HTMLElement {}
|
||||
customElements.define('already-defined', AlreadyDefined);
|
||||
|
||||
const promise = customElements.whenDefined('already-defined');
|
||||
testing.expectEqual('object', typeof promise);
|
||||
testing.expectEqual(true, promise instanceof Promise);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="whenDefined_not_yet_defined">
|
||||
{
|
||||
const promise = customElements.whenDefined('future-element');
|
||||
testing.expectEqual('object', typeof promise);
|
||||
testing.expectEqual(true, promise instanceof Promise);
|
||||
|
||||
// Now define it
|
||||
class FutureElement extends HTMLElement {}
|
||||
customElements.define('future-element', FutureElement);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="whenDefined_same_promise">
|
||||
{
|
||||
const promise1 = customElements.whenDefined('pending-element');
|
||||
const promise2 = customElements.whenDefined('pending-element');
|
||||
|
||||
// Should return the same promise for the same name
|
||||
testing.expectEqual(true, promise1 === promise2);
|
||||
|
||||
// Define it so cleanup happens
|
||||
class PendingElement extends HTMLElement {}
|
||||
customElements.define('pending-element', PendingElement);
|
||||
}
|
||||
</script>
|
||||
|
||||
355
src/browser/tests/custom_elements/upgrade.html
Normal file
355
src/browser/tests/custom_elements/upgrade.html
Normal file
@@ -0,0 +1,355 @@
|
||||
<!DOCTYPE html>
|
||||
<body>
|
||||
<my-early id="early"></my-early>
|
||||
<script src="../testing.js"></script>
|
||||
<script id="upgrade">
|
||||
{
|
||||
let constructorCalled = 0;
|
||||
let connectedCalled = 0;
|
||||
|
||||
class MyEarly extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
constructorCalled++;
|
||||
this.upgraded = true;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
connectedCalled++;
|
||||
}
|
||||
}
|
||||
|
||||
const early = document.getElementById('early');
|
||||
testing.expectEqual(undefined, early.upgraded);
|
||||
testing.expectEqual(0, constructorCalled);
|
||||
testing.expectEqual(0, connectedCalled);
|
||||
|
||||
customElements.define('my-early', MyEarly);
|
||||
testing.expectEqual(true, early.upgraded);
|
||||
testing.expectEqual(1, constructorCalled);
|
||||
testing.expectEqual(1, connectedCalled);
|
||||
}
|
||||
|
||||
{
|
||||
let order = [];
|
||||
|
||||
class UpgradeParent extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
order.push('parent-constructor');
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
order.push('parent-connected');
|
||||
}
|
||||
}
|
||||
|
||||
class UpgradeChild extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
order.push('child-constructor');
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
order.push('child-connected');
|
||||
}
|
||||
}
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = '<upgrade-parent><upgrade-child></upgrade-child></upgrade-parent>';
|
||||
document.body.appendChild(container);
|
||||
|
||||
testing.expectEqual(0, order.length);
|
||||
|
||||
customElements.define('upgrade-parent', UpgradeParent);
|
||||
testing.expectEqual(2, order.length);
|
||||
testing.expectEqual('parent-constructor', order[0]);
|
||||
testing.expectEqual('parent-connected', order[1]);
|
||||
|
||||
customElements.define('upgrade-child', UpgradeChild);
|
||||
testing.expectEqual(4, order.length);
|
||||
testing.expectEqual('child-constructor', order[2]);
|
||||
testing.expectEqual('child-connected', order[3]);
|
||||
}
|
||||
|
||||
{
|
||||
let connectedCalled = 0;
|
||||
|
||||
class DetachedUpgrade extends HTMLElement {
|
||||
connectedCallback() {
|
||||
connectedCalled++;
|
||||
}
|
||||
}
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = '<detached-upgrade></detached-upgrade>';
|
||||
|
||||
testing.expectEqual(0, connectedCalled);
|
||||
|
||||
customElements.define('detached-upgrade', DetachedUpgrade);
|
||||
testing.expectEqual(0, connectedCalled);
|
||||
|
||||
document.body.appendChild(container);
|
||||
testing.expectEqual(1, connectedCalled);
|
||||
}
|
||||
|
||||
{
|
||||
let constructorCalled = 0;
|
||||
let connectedCalled = 0;
|
||||
|
||||
class ManualUpgrade extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
constructorCalled++;
|
||||
this.manuallyUpgraded = true;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
connectedCalled++;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('manual-upgrade', ManualUpgrade);
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = '<manual-upgrade id="m1"><manual-upgrade id="m2"></manual-upgrade></manual-upgrade>';
|
||||
|
||||
testing.expectEqual(2, constructorCalled);
|
||||
testing.expectEqual(0, connectedCalled);
|
||||
|
||||
customElements.upgrade(container);
|
||||
|
||||
testing.expectEqual(2, constructorCalled);
|
||||
testing.expectEqual(0, connectedCalled);
|
||||
|
||||
const m1 = container.querySelector('#m1');
|
||||
const m2 = container.querySelector('#m2');
|
||||
testing.expectEqual(true, m1.manuallyUpgraded);
|
||||
testing.expectEqual(true, m2.manuallyUpgraded);
|
||||
|
||||
document.body.appendChild(container);
|
||||
testing.expectEqual(2, connectedCalled);
|
||||
}
|
||||
|
||||
{
|
||||
let alreadyUpgradedCalled = 0;
|
||||
|
||||
class AlreadyUpgraded extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
alreadyUpgradedCalled++;
|
||||
}
|
||||
}
|
||||
|
||||
const elem = document.createElement('div');
|
||||
elem.innerHTML = '<already-upgraded></already-upgraded>';
|
||||
document.body.appendChild(elem);
|
||||
|
||||
customElements.define('already-upgraded', AlreadyUpgraded);
|
||||
testing.expectEqual(1, alreadyUpgradedCalled);
|
||||
|
||||
customElements.upgrade(elem);
|
||||
testing.expectEqual(1, alreadyUpgradedCalled);
|
||||
}
|
||||
|
||||
{
|
||||
let attributeChangedCalls = [];
|
||||
|
||||
class UpgradeWithAttrs extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['data-foo', 'data-bar'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
attributeChangedCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = '<upgrade-with-attrs data-foo="hello" data-bar="world"></upgrade-with-attrs>';
|
||||
document.body.appendChild(container);
|
||||
|
||||
testing.expectEqual(0, attributeChangedCalls.length);
|
||||
|
||||
customElements.define('upgrade-with-attrs', UpgradeWithAttrs);
|
||||
|
||||
testing.expectEqual(2, attributeChangedCalls.length);
|
||||
testing.expectEqual('data-foo', attributeChangedCalls[0].name);
|
||||
testing.expectEqual(null, attributeChangedCalls[0].oldValue);
|
||||
testing.expectEqual('hello', attributeChangedCalls[0].newValue);
|
||||
testing.expectEqual('data-bar', attributeChangedCalls[1].name);
|
||||
testing.expectEqual(null, attributeChangedCalls[1].oldValue);
|
||||
testing.expectEqual('world', attributeChangedCalls[1].newValue);
|
||||
}
|
||||
|
||||
{
|
||||
let attributeChangedCalls = [];
|
||||
let connectedCalls = 0;
|
||||
|
||||
class DetachedWithAttrs extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['foo'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
attributeChangedCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
connectedCalls++;
|
||||
}
|
||||
}
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = '<detached-with-attrs foo="bar"></detached-with-attrs>';
|
||||
|
||||
testing.expectEqual(0, attributeChangedCalls.length);
|
||||
|
||||
customElements.define('detached-with-attrs', DetachedWithAttrs);
|
||||
|
||||
testing.expectEqual(0, attributeChangedCalls.length);
|
||||
testing.expectEqual(0, connectedCalls);
|
||||
|
||||
document.body.appendChild(container);
|
||||
|
||||
testing.expectEqual(1, attributeChangedCalls.length);
|
||||
testing.expectEqual('foo', attributeChangedCalls[0].name);
|
||||
testing.expectEqual(null, attributeChangedCalls[0].oldValue);
|
||||
testing.expectEqual('bar', attributeChangedCalls[0].newValue);
|
||||
testing.expectEqual(1, connectedCalls);
|
||||
}
|
||||
|
||||
{
|
||||
let attributeChangedCalls = [];
|
||||
let constructorCalled = 0;
|
||||
|
||||
class ManualUpgradeWithAttrs extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['x', 'y'];
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
constructorCalled++;
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
attributeChangedCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('manual-upgrade-with-attrs', ManualUpgradeWithAttrs);
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = '<manual-upgrade-with-attrs x="1" y="2"></manual-upgrade-with-attrs>';
|
||||
|
||||
testing.expectEqual(1, constructorCalled);
|
||||
testing.expectEqual(2, attributeChangedCalls.length);
|
||||
|
||||
const elem = container.querySelector('manual-upgrade-with-attrs');
|
||||
elem.setAttribute('z', '3');
|
||||
|
||||
customElements.upgrade(container);
|
||||
|
||||
testing.expectEqual(1, constructorCalled);
|
||||
testing.expectEqual(2, attributeChangedCalls.length);
|
||||
}
|
||||
|
||||
{
|
||||
let attributeChangedCalls = [];
|
||||
|
||||
class MixedAttrs extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['watched'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
attributeChangedCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = '<mixed-attrs watched="yes" ignored="no" also-ignored="maybe"></mixed-attrs>';
|
||||
document.body.appendChild(container);
|
||||
|
||||
testing.expectEqual(0, attributeChangedCalls.length);
|
||||
|
||||
customElements.define('mixed-attrs', MixedAttrs);
|
||||
|
||||
testing.expectEqual(1, attributeChangedCalls.length);
|
||||
testing.expectEqual('watched', attributeChangedCalls[0].name);
|
||||
testing.expectEqual('yes', attributeChangedCalls[0].newValue);
|
||||
}
|
||||
|
||||
{
|
||||
let attributeChangedCalls = [];
|
||||
|
||||
class EmptyAttr extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['empty', 'non-empty'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
attributeChangedCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = '<empty-attr empty="" non-empty="value"></empty-attr>';
|
||||
document.body.appendChild(container);
|
||||
|
||||
customElements.define('empty-attr', EmptyAttr);
|
||||
|
||||
testing.expectEqual(2, attributeChangedCalls.length);
|
||||
testing.expectEqual('empty', attributeChangedCalls[0].name);
|
||||
testing.expectEqual('', attributeChangedCalls[0].newValue);
|
||||
testing.expectEqual('non-empty', attributeChangedCalls[1].name);
|
||||
testing.expectEqual('value', attributeChangedCalls[1].newValue);
|
||||
}
|
||||
|
||||
{
|
||||
let parentCalls = [];
|
||||
let childCalls = [];
|
||||
|
||||
class NestedParent extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['parent-attr'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
parentCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
class NestedChild extends HTMLElement {
|
||||
static get observedAttributes() {
|
||||
return ['child-attr'];
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldValue, newValue) {
|
||||
childCalls.push({ name, oldValue, newValue });
|
||||
}
|
||||
}
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = '<nested-parent parent-attr="p"><nested-child child-attr="c"></nested-child></nested-parent>';
|
||||
document.body.appendChild(container);
|
||||
|
||||
testing.expectEqual(0, parentCalls.length);
|
||||
testing.expectEqual(0, childCalls.length);
|
||||
|
||||
customElements.define('nested-parent', NestedParent);
|
||||
|
||||
testing.expectEqual(1, parentCalls.length);
|
||||
testing.expectEqual('parent-attr', parentCalls[0].name);
|
||||
testing.expectEqual('p', parentCalls[0].newValue);
|
||||
testing.expectEqual(0, childCalls.length);
|
||||
|
||||
customElements.define('nested-child', NestedChild);
|
||||
|
||||
testing.expectEqual(1, parentCalls.length);
|
||||
testing.expectEqual(1, childCalls.length);
|
||||
testing.expectEqual('child-attr', childCalls[0].name);
|
||||
testing.expectEqual('c', childCalls[0].newValue);
|
||||
}
|
||||
</script>
|
||||
217
src/browser/tests/document/adopt_import.html
Normal file
217
src/browser/tests/document/adopt_import.html
Normal file
@@ -0,0 +1,217 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
<div id="test-container">
|
||||
<p id="test-p" class="test-class" data-foo="bar">
|
||||
<span>Child 1</span>
|
||||
<span>Child 2</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<script id="importNodeShallow">
|
||||
{
|
||||
const original = $('#test-p');
|
||||
const imported = document.importNode(original, false);
|
||||
|
||||
testing.expectEqual(1, imported.nodeType);
|
||||
testing.expectEqual('P', imported.tagName);
|
||||
testing.expectEqual('test-class', imported.className);
|
||||
testing.expectEqual('bar', imported.getAttribute('data-foo'));
|
||||
testing.expectEqual(null, imported.parentNode);
|
||||
testing.expectEqual(false, imported.hasChildNodes());
|
||||
testing.expectEqual(false, original.isSameNode(imported));
|
||||
testing.expectEqual(document, imported.ownerDocument);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="importNodeDeep">
|
||||
{
|
||||
const original = $('#test-p');
|
||||
const imported = document.importNode(original, true);
|
||||
|
||||
testing.expectEqual(1, imported.nodeType);
|
||||
testing.expectEqual('P', imported.tagName);
|
||||
testing.expectEqual('test-class', imported.className);
|
||||
testing.expectEqual('bar', imported.getAttribute('data-foo'));
|
||||
testing.expectEqual(null, imported.parentNode);
|
||||
testing.expectEqual(true, imported.hasChildNodes());
|
||||
|
||||
testing.expectEqual(false, original.isSameNode(imported));
|
||||
testing.expectEqual(false, original.firstChild.isSameNode(imported.firstChild));
|
||||
|
||||
const spans = imported.querySelectorAll('span');
|
||||
testing.expectEqual(2, spans.length);
|
||||
testing.expectEqual('Child 1', spans[0].textContent);
|
||||
testing.expectEqual('Child 2', spans[1].textContent);
|
||||
testing.expectEqual(document, imported.ownerDocument);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="importNodeDefault">
|
||||
{
|
||||
const el = document.createElement('div');
|
||||
el.appendChild(document.createElement('span'));
|
||||
|
||||
const imported = document.importNode(el);
|
||||
testing.expectEqual(false, imported.hasChildNodes());
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="importNodeDetached">
|
||||
{
|
||||
const detached = document.createElement('div');
|
||||
detached.textContent = 'detached';
|
||||
|
||||
const imported = document.importNode(detached, true);
|
||||
testing.expectEqual('DIV', imported.tagName);
|
||||
testing.expectEqual('detached', imported.textContent);
|
||||
testing.expectEqual(null, imported.parentNode);
|
||||
testing.expectEqual(false, detached.isSameNode(imported));
|
||||
testing.expectEqual(document, imported.ownerDocument);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="importNodeTextNode">
|
||||
{
|
||||
const text = document.createTextNode('Hello World');
|
||||
const imported = document.importNode(text, false);
|
||||
|
||||
testing.expectEqual(3, imported.nodeType);
|
||||
testing.expectEqual('Hello World', imported.nodeValue);
|
||||
testing.expectEqual(null, imported.parentNode);
|
||||
testing.expectEqual(false, text.isSameNode(imported));
|
||||
testing.expectEqual(document, imported.ownerDocument);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="importNodeComment">
|
||||
{
|
||||
const comment = document.createComment('test comment');
|
||||
const imported = document.importNode(comment, false);
|
||||
|
||||
testing.expectEqual(8, imported.nodeType);
|
||||
testing.expectEqual('test comment', imported.nodeValue);
|
||||
testing.expectEqual(null, imported.parentNode);
|
||||
testing.expectEqual(false, comment.isSameNode(imported));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="importNodeDoesNotModifyOriginal">
|
||||
{
|
||||
const original = $('#test-p');
|
||||
const originalParent = original.parentNode;
|
||||
const imported = document.importNode(original, true);
|
||||
|
||||
testing.expectEqual(originalParent, original.parentNode);
|
||||
testing.expectEqual(true, original.isConnected);
|
||||
testing.expectEqual(null, imported.parentNode);
|
||||
testing.expectEqual(false, imported.isConnected);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="adoptNodeDetached">
|
||||
{
|
||||
const detached = document.createElement('div');
|
||||
detached.textContent = 'detached';
|
||||
|
||||
const adopted = document.adoptNode(detached);
|
||||
testing.expectEqual(detached, adopted);
|
||||
testing.expectEqual('DIV', adopted.tagName);
|
||||
testing.expectEqual('detached', adopted.textContent);
|
||||
testing.expectEqual(null, adopted.parentNode);
|
||||
testing.expectEqual(document, adopted.ownerDocument);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="adoptNodeRemovesFromParent">
|
||||
{
|
||||
const container = $('#test-container');
|
||||
const p = $('#test-p');
|
||||
|
||||
testing.expectEqual(container, p.parentNode);
|
||||
testing.expectEqual(true, p.isConnected);
|
||||
|
||||
const adopted = document.adoptNode(p);
|
||||
|
||||
testing.expectEqual(p, adopted);
|
||||
testing.expectEqual(null, adopted.parentNode);
|
||||
testing.expectEqual(false, adopted.isConnected);
|
||||
testing.expectEqual(false, container.contains(p));
|
||||
testing.expectEqual(document, adopted.ownerDocument);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="adoptNodeTextNode">
|
||||
{
|
||||
const text = document.createTextNode('Hello');
|
||||
const adopted = document.adoptNode(text);
|
||||
|
||||
testing.expectEqual(text, adopted);
|
||||
testing.expectEqual(3, adopted.nodeType);
|
||||
testing.expectEqual('Hello', adopted.nodeValue);
|
||||
testing.expectEqual(null, adopted.parentNode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="adoptNodePreservesChildren">
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
const span = document.createElement('span');
|
||||
span.textContent = 'child';
|
||||
div.appendChild(span);
|
||||
|
||||
const adopted = document.adoptNode(div);
|
||||
|
||||
testing.expectEqual(div, adopted);
|
||||
testing.expectEqual(true, adopted.hasChildNodes());
|
||||
testing.expectEqual(span, adopted.firstChild);
|
||||
testing.expectEqual('child', adopted.firstChild.textContent);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="importThenAppend">
|
||||
{
|
||||
const original = document.createElement('div');
|
||||
original.textContent = 'test';
|
||||
|
||||
const imported = document.importNode(original, true);
|
||||
document.body.appendChild(imported);
|
||||
|
||||
testing.expectEqual(document.body, imported.parentNode);
|
||||
testing.expectEqual(true, imported.isConnected);
|
||||
testing.expectEqual('test', imported.textContent);
|
||||
|
||||
imported.remove();
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="adoptThenAppend">
|
||||
{
|
||||
const detached = document.createElement('div');
|
||||
detached.textContent = 'adopted';
|
||||
|
||||
const adopted = document.adoptNode(detached);
|
||||
document.body.appendChild(adopted);
|
||||
|
||||
testing.expectEqual(document.body, adopted.parentNode);
|
||||
testing.expectEqual(true, adopted.isConnected);
|
||||
testing.expectEqual('adopted', adopted.textContent);
|
||||
|
||||
adopted.remove();
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="importNodeWithAttributes">
|
||||
{
|
||||
const input = document.createElement('input');
|
||||
input.setAttribute('type', 'text');
|
||||
input.setAttribute('name', 'username');
|
||||
input.setAttribute('value', 'test');
|
||||
input.setAttribute('data-custom', 'custom-value');
|
||||
|
||||
const imported = document.importNode(input, false);
|
||||
testing.expectEqual('text', imported.getAttribute('type'));
|
||||
testing.expectEqual('username', imported.getAttribute('name'));
|
||||
testing.expectEqual('test', imported.getAttribute('value'));
|
||||
testing.expectEqual('custom-value', imported.getAttribute('data-custom'));
|
||||
}
|
||||
</script>
|
||||
68
src/browser/tests/document/all_collection.html
Normal file
68
src/browser/tests/document/all_collection.html
Normal file
@@ -0,0 +1,68 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test Page</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="first">First</div>
|
||||
<span name="second">Second</span>
|
||||
<p id="third">Third</p>
|
||||
<a href="#" name="link">Link</a>
|
||||
<script src="../testing.js"></script>
|
||||
<script id=all_collection>
|
||||
testing.expectEqual('undefined', typeof document.all);
|
||||
testing.expectEqual('HTMLAllCollection', document.all.constructor.name);
|
||||
testing.expectEqual(true, document.all == null);
|
||||
testing.expectEqual(true, document.all == undefined);
|
||||
testing.expectEqual(false, document.all === undefined);
|
||||
testing.expectEqual(true, !document.all);
|
||||
testing.expectEqual(false, !!document.all);
|
||||
|
||||
testing.expectEqual(10, document.all.length);
|
||||
|
||||
testing.expectEqual('HTML', document.all[0].tagName);
|
||||
testing.expectEqual('HEAD', document.all[1].tagName);
|
||||
testing.expectEqual('TITLE', document.all[2].tagName);
|
||||
testing.expectEqual('BODY', document.all[3].tagName);
|
||||
testing.expectEqual('DIV', document.all[4].tagName);
|
||||
|
||||
testing.expectEqual('DIV', document.all.first.tagName);
|
||||
testing.expectEqual('First', document.all.first.textContent);
|
||||
testing.expectEqual('P', document.all.third.tagName);
|
||||
testing.expectEqual('Third', document.all.third.textContent);
|
||||
|
||||
testing.expectEqual('SPAN', document.all.second.tagName);
|
||||
testing.expectEqual('Second', document.all.second.textContent);
|
||||
testing.expectEqual('A', document.all.link.tagName);
|
||||
|
||||
testing.expectEqual('SPAN', document.all.item(5).tagName);
|
||||
testing.expectEqual(null, document.all.item(999));
|
||||
testing.expectEqual(null, document.all.item(-1));
|
||||
|
||||
testing.expectEqual('DIV', document.all.namedItem('first').tagName);
|
||||
testing.expectEqual('SPAN', document.all.namedItem('second').tagName);
|
||||
testing.expectEqual(null, document.all.namedItem('nonexistent'));
|
||||
|
||||
// Test callable functionality: document.all(index) and document.all(name)
|
||||
testing.expectEqual('HTML', document.all(0).tagName);
|
||||
testing.expectEqual('HEAD', document.all(1).tagName);
|
||||
testing.expectEqual('DIV', document.all(4).tagName);
|
||||
testing.expectEqual('DIV', document.all('first').tagName);
|
||||
testing.expectEqual('First', document.all('first').textContent);
|
||||
testing.expectEqual('SPAN', document.all('second').tagName);
|
||||
testing.expectEqual('Second', document.all('second').textContent);
|
||||
testing.expectEqual('P', document.all('third').tagName);
|
||||
testing.expectEqual(undefined, document.all(999));
|
||||
testing.expectEqual(undefined, document.all('nonexistent'));
|
||||
|
||||
let count = 0;
|
||||
for (const el of document.all) {
|
||||
count++;
|
||||
}
|
||||
testing.expectEqual(10, count);
|
||||
|
||||
const plainDoc = new Document();
|
||||
testing.expectEqual('undefined', typeof plainDoc.all);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
28
src/browser/tests/document/children.html
Normal file
28
src/browser/tests/document/children.html
Normal file
@@ -0,0 +1,28 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<head>
|
||||
<title>Test</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="test">Content</div>
|
||||
</body>
|
||||
|
||||
<script id=document_children_basic>
|
||||
{
|
||||
const children = document.children;
|
||||
testing.expectEqual('HTMLCollection', children.constructor.name);
|
||||
testing.expectEqual(1, children.length);
|
||||
testing.expectEqual('HTML', children[0].tagName);
|
||||
testing.expectEqual(document.documentElement, children[0]);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=document_children_live>
|
||||
{
|
||||
const children = document.children;
|
||||
const initialLength = children.length;
|
||||
|
||||
testing.expectEqual(1, initialLength);
|
||||
}
|
||||
</script>
|
||||
24
src/browser/tests/document/collections.html
Normal file
24
src/browser/tests/document/collections.html
Normal file
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<form id="form1"></form>
|
||||
<img id="img1" src="about:blank">
|
||||
<script></script>
|
||||
<a id="link1" href="#"></a>
|
||||
<a id="link2" href="/page2"></a>
|
||||
|
||||
<script id=collections>
|
||||
testing.expectEqual(1, document.forms.length);
|
||||
testing.expectEqual($('#form1'), document.forms[0]);
|
||||
testing.expectEqual(1, document.images.length);
|
||||
testing.expectEqual($('#img1'), document.images[0]);
|
||||
testing.expectEqual(3, document.scripts.length);
|
||||
|
||||
testing.expectEqual(true, document.scripts[0].src.endsWith('testing.js'));
|
||||
testing.expectEqual(document.scripts[1].src, '');
|
||||
testing.expectEqual($('#collections'), document.scripts[2]);
|
||||
// document.links only includes <a> elements with href attribute
|
||||
testing.expectEqual(2, document.links.length);
|
||||
testing.expectEqual($('#link1'), document.links[0]);
|
||||
testing.expectEqual($('#link2'), document.links[1]);
|
||||
</script>
|
||||
13
src/browser/tests/document/create_element.html
Normal file
13
src/browser/tests/document/create_element.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<body></body>
|
||||
<script src="../testing.js"></script>
|
||||
<script id=createElement>
|
||||
const div = document.createElement('div');
|
||||
testing.expectEqual("DIV", div.tagName);
|
||||
div.id = "hello";
|
||||
testing.expectEqual(null, $('#hello'));
|
||||
|
||||
document.getElementsByTagName('body')[0].appendChild(div);
|
||||
testing.expectEqual(div, $('#hello'));
|
||||
</script>
|
||||
|
||||
40
src/browser/tests/document/create_element_ns.html
Normal file
40
src/browser/tests/document/create_element_ns.html
Normal file
@@ -0,0 +1,40 @@
|
||||
<!DOCTYPE html>
|
||||
<body></body>
|
||||
<script src="../testing.js"></script>
|
||||
<script id=createElementNS>
|
||||
const htmlDiv = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
|
||||
testing.expectEqual('DIV', htmlDiv.tagName);
|
||||
testing.expectEqual('http://www.w3.org/1999/xhtml', htmlDiv.namespaceURI);
|
||||
|
||||
const svgRect = document.createElementNS('http://www.w3.org/2000/svg', 'RecT');
|
||||
testing.expectEqual('RecT', svgRect.tagName);
|
||||
testing.expectEqual('http://www.w3.org/2000/svg', svgRect.namespaceURI);
|
||||
|
||||
const mathElement = document.createElementNS('http://www.w3.org/1998/Math/MathML', 'math');
|
||||
testing.expectEqual('math', mathElement.tagName);
|
||||
testing.expectEqual('http://www.w3.org/1998/Math/MathML', mathElement.namespaceURI);
|
||||
|
||||
const xmlElement = document.createElementNS('http://www.w3.org/XML/1998/namespace', 'TEst');
|
||||
testing.expectEqual('TEst', xmlElement.tagName);
|
||||
testing.expectEqual('http://www.w3.org/XML/1998/namespace', xmlElement.namespaceURI);
|
||||
|
||||
const nullNsElement = document.createElementNS(null, 'span');
|
||||
testing.expectEqual('SPAN', nullNsElement.tagName);
|
||||
testing.expectEqual('http://www.w3.org/1999/xhtml', nullNsElement.namespaceURI);
|
||||
|
||||
const unknownNsElement = document.createElementNS('http://example.com/unknown', 'custom');
|
||||
testing.expectEqual('CUSTOM', unknownNsElement.tagName);
|
||||
testing.expectEqual('http://www.w3.org/1999/xhtml', unknownNsElement.namespaceURI);
|
||||
|
||||
const regularDiv = document.createElement('div');
|
||||
testing.expectEqual('DIV', regularDiv.tagName);
|
||||
testing.expectEqual('div', regularDiv.localName);
|
||||
testing.expectEqual(null, regularDiv.prefix);
|
||||
testing.expectEqual('http://www.w3.org/1999/xhtml', regularDiv.namespaceURI);
|
||||
|
||||
const custom = document.createElementNS('test', 'te:ST');
|
||||
testing.expectEqual('te:ST', custom.tagName);
|
||||
testing.expectEqual('te', custom.prefix);
|
||||
testing.expectEqual('ST', custom.localName);
|
||||
testing.expectEqual('http://www.w3.org/1999/xhtml', custom.namespaceURI); // Should be test
|
||||
</script>
|
||||
34
src/browser/tests/document/document-title.html
Normal file
34
src/browser/tests/document/document-title.html
Normal file
@@ -0,0 +1,34 @@
|
||||
<!DOCTYPE html>
|
||||
<head id="the_head">
|
||||
<script src="../testing.js"></script>
|
||||
</head>
|
||||
|
||||
<body id=the_body>
|
||||
</body>
|
||||
|
||||
<script id=title_initially_empty>
|
||||
testing.expectEqual('', document.title);
|
||||
</script>
|
||||
|
||||
<script id=title_set_without_existing>
|
||||
document.title = 'New Title';
|
||||
testing.expectEqual('New Title', document.title);
|
||||
|
||||
const titleElement = document.head.querySelector('title');
|
||||
testing.expectEqual(true, titleElement !== null);
|
||||
testing.expectEqual('New Title', titleElement.textContent);
|
||||
</script>
|
||||
|
||||
<script id=title_update_existing>
|
||||
document.title = 'Updated Title';
|
||||
testing.expectEqual('Updated Title', document.title);
|
||||
|
||||
const titleElements = document.head.querySelectorAll('title');
|
||||
testing.expectEqual(1, titleElements.length);
|
||||
testing.expectEqual('Updated Title', titleElements[0].textContent);
|
||||
</script>
|
||||
|
||||
<script id=title_set_empty>
|
||||
document.title = '';
|
||||
testing.expectEqual('', document.title);
|
||||
</script>
|
||||
284
src/browser/tests/document/document.html
Normal file
284
src/browser/tests/document/document.html
Normal file
@@ -0,0 +1,284 @@
|
||||
<!DOCTYPE html>
|
||||
<head id="the_head">
|
||||
<title>Test Document Title</title>
|
||||
<script src="../testing.js"></script>
|
||||
</head>
|
||||
|
||||
<body id=the_body>
|
||||
</body>
|
||||
|
||||
<script id=document>
|
||||
testing.expectEqual(10, document.childNodes[0].nodeType);
|
||||
testing.expectEqual(null, document.parentNode);
|
||||
testing.expectEqual(undefined, document.getCurrentScript);
|
||||
testing.expectEqual("http://127.0.0.1:9582/src/browser/tests/document/document.html", document.URL);
|
||||
testing.expectEqual(window, document.defaultView);
|
||||
</script>
|
||||
|
||||
<script id=headAndbody>
|
||||
testing.expectEqual($('#the_head'), document.head);
|
||||
testing.expectEqual($('#the_body'), document.body);
|
||||
</script>
|
||||
|
||||
<script id=documentElement>
|
||||
testing.expectEqual($('#the_body').parentNode, document.documentElement);
|
||||
</script>
|
||||
|
||||
<script id=title>
|
||||
testing.expectEqual('Test Document Title', document.title);
|
||||
document.title = 'New Title';
|
||||
testing.expectEqual('New Title', document.title);
|
||||
document.title = '';
|
||||
testing.expectEqual('', document.title);
|
||||
</script>
|
||||
|
||||
<script id=createTextNode>
|
||||
const textNode = document.createTextNode('Hello World');
|
||||
testing.expectEqual(3, textNode.nodeType);
|
||||
testing.expectEqual('Hello World', textNode.nodeValue);
|
||||
testing.expectEqual('Hello World', textNode.textContent);
|
||||
|
||||
const emptyText = document.createTextNode('');
|
||||
testing.expectEqual('', emptyText.nodeValue);
|
||||
</script>
|
||||
|
||||
<script id=document_metadata>
|
||||
// Test document metadata properties on HTML document
|
||||
testing.expectEqual('text/html', document.contentType);
|
||||
testing.expectEqual('UTF-8', document.characterSet);
|
||||
testing.expectEqual('UTF-8', document.charset);
|
||||
testing.expectEqual('UTF-8', document.inputEncoding);
|
||||
testing.expectEqual('CSS1Compat', document.compatMode);
|
||||
testing.expectEqual(document.URL, document.documentURI);
|
||||
testing.expectEqual('', document.referrer);
|
||||
testing.expectEqual('127.0.0.1', document.domain);
|
||||
</script>
|
||||
|
||||
<script id=programmatic_document_metadata>
|
||||
// Test document metadata properties on programmatically created document
|
||||
const doc = new Document();
|
||||
testing.expectEqual('application/xml', doc.contentType);
|
||||
testing.expectEqual('UTF-8', doc.characterSet);
|
||||
testing.expectEqual('UTF-8', doc.charset);
|
||||
testing.expectEqual('UTF-8', doc.inputEncoding);
|
||||
testing.expectEqual('CSS1Compat', doc.compatMode);
|
||||
testing.expectEqual('', doc.referrer);
|
||||
// Programmatic document should have empty domain (no URL/origin)
|
||||
testing.expectEqual('127.0.0.1', doc.domain);
|
||||
</script>
|
||||
|
||||
<!-- Test anchors and links -->
|
||||
<a id="link1" href="/page1">Link 1</a>
|
||||
<a id="link2" href="/page2">Link 2</a>
|
||||
<a id="anchor1" name="section1">Anchor 1</a>
|
||||
<a id="anchor2" name="section2">Anchor 2</a>
|
||||
<a id="both" href="/page3" name="section3">Both href and name</a>
|
||||
<a id="no_attrs">No attributes</a>
|
||||
|
||||
<script id=document_links>
|
||||
{
|
||||
// document.links should only include <a> elements with href attribute
|
||||
const links = document.links;
|
||||
testing.expectEqual('HTMLCollection', links.constructor.name);
|
||||
testing.expectEqual(3, links.length);
|
||||
|
||||
// Should include link1, link2, and both
|
||||
testing.expectEqual($('#link1'), links[0]);
|
||||
testing.expectEqual($('#link2'), links[1]);
|
||||
testing.expectEqual($('#both'), links[2]);
|
||||
|
||||
// Indexed access
|
||||
testing.expectEqual($('#link1'), links.item(0));
|
||||
testing.expectEqual($('#link2'), links.item(1));
|
||||
testing.expectEqual($('#both'), links.item(2));
|
||||
testing.expectEqual(null, links.item(3));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=document_anchors>
|
||||
{
|
||||
// document.anchors should only include <a> elements with name attribute
|
||||
const anchors = document.anchors;
|
||||
testing.expectEqual('HTMLCollection', anchors.constructor.name);
|
||||
testing.expectEqual(3, anchors.length);
|
||||
|
||||
// Should include anchor1, anchor2, and both
|
||||
testing.expectEqual($('#anchor1'), anchors[0]);
|
||||
testing.expectEqual($('#anchor2'), anchors[1]);
|
||||
testing.expectEqual($('#both'), anchors[2]);
|
||||
|
||||
// Indexed access
|
||||
testing.expectEqual($('#anchor1'), anchors.item(0));
|
||||
testing.expectEqual($('#anchor2'), anchors.item(1));
|
||||
testing.expectEqual($('#both'), anchors.item(2));
|
||||
testing.expectEqual(null, anchors.item(3));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=links_live_collection>
|
||||
{
|
||||
// Test that document.links is a live collection
|
||||
const links = document.links;
|
||||
const initialLength = links.length;
|
||||
|
||||
// Add a new link
|
||||
const newLink = document.createElement('a');
|
||||
newLink.href = '/new-page';
|
||||
newLink.textContent = 'New Link';
|
||||
document.body.appendChild(newLink);
|
||||
|
||||
testing.expectEqual(initialLength + 1, links.length);
|
||||
testing.expectEqual(newLink, links[links.length - 1]);
|
||||
|
||||
// Remove href attribute - should no longer be in links
|
||||
newLink.removeAttribute('href');
|
||||
testing.expectEqual(initialLength, links.length);
|
||||
|
||||
// Add it back
|
||||
newLink.href = '/another-page';
|
||||
testing.expectEqual(initialLength + 1, links.length);
|
||||
|
||||
// Remove the element
|
||||
newLink.remove();
|
||||
testing.expectEqual(initialLength, links.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=anchors_live_collection>
|
||||
// Test that document.anchors is a live collection
|
||||
const anchors = document.anchors;
|
||||
const initialLength = anchors.length;
|
||||
|
||||
// Add a new anchor
|
||||
const newAnchor = document.createElement('a');
|
||||
newAnchor.name = 'new-section';
|
||||
newAnchor.textContent = 'New Anchor';
|
||||
document.body.appendChild(newAnchor);
|
||||
|
||||
testing.expectEqual(initialLength + 1, anchors.length);
|
||||
testing.expectEqual(newAnchor, anchors[anchors.length - 1]);
|
||||
|
||||
// Remove name attribute - should no longer be in anchors
|
||||
newAnchor.removeAttribute('name');
|
||||
testing.expectEqual(initialLength, anchors.length);
|
||||
|
||||
// Add it back
|
||||
newAnchor.name = 'another-section';
|
||||
testing.expectEqual(initialLength + 1, anchors.length);
|
||||
|
||||
// Remove the element
|
||||
newAnchor.remove();
|
||||
testing.expectEqual(initialLength, anchors.length);
|
||||
</script>
|
||||
|
||||
<script id=cookie>
|
||||
testing.expectEqual('', document.cookie);
|
||||
document.cookie = 'name=Oeschger;';
|
||||
document.cookie = 'favorite_food=tripe;';
|
||||
|
||||
testing.expectEqual('name=Oeschger; favorite_food=tripe', document.cookie);
|
||||
// "" should be returned, but the framework overrules it atm
|
||||
document.cookie = 'IgnoreMy=Ghost; HttpOnly';
|
||||
testing.expectEqual('name=Oeschger; favorite_food=tripe', document.cookie);
|
||||
</script>
|
||||
|
||||
<script id=createAttribute>
|
||||
{
|
||||
var attr = document.createAttribute('hello');
|
||||
testing.expectEqual('hello', attr.name);
|
||||
testing.expectEqual('', attr.value);
|
||||
|
||||
testing.withError((err) => {
|
||||
testing.expectEqual(5, err.code);
|
||||
testing.expectEqual("InvalidCharacterError", err.name);
|
||||
}, () => document.createAttribute(''));
|
||||
|
||||
testing.withError((err) => {
|
||||
testing.expectEqual(5, err.code);
|
||||
testing.expectEqual("InvalidCharacterError", err.name);
|
||||
}, () => document.createAttribute('.over'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=append>
|
||||
{
|
||||
const doc = new Document();
|
||||
const html = doc.createElement('html');
|
||||
const body = doc.createElement('body');
|
||||
const div1 = doc.createElement('div');
|
||||
const div2 = doc.createElement('div');
|
||||
|
||||
doc.append(html);
|
||||
testing.expectEqual(1, doc.childNodes.length);
|
||||
testing.expectEqual(html, doc.childNodes[0]);
|
||||
|
||||
html.append(body);
|
||||
testing.expectEqual(1, html.childNodes.length);
|
||||
testing.expectEqual(body, html.childNodes[0]);
|
||||
|
||||
body.append(div1, div2);
|
||||
testing.expectEqual(2, body.childNodes.length);
|
||||
testing.expectEqual(div1, body.childNodes[0]);
|
||||
testing.expectEqual(div2, body.childNodes[1]);
|
||||
|
||||
body.append('text node');
|
||||
testing.expectEqual(3, body.childNodes.length);
|
||||
testing.expectEqual(3, body.childNodes[2].nodeType);
|
||||
testing.expectEqual('text node', body.childNodes[2].textContent);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=prepend>
|
||||
{
|
||||
const doc = new Document();
|
||||
const html = doc.createElement('html');
|
||||
const body = doc.createElement('body');
|
||||
const div1 = doc.createElement('div');
|
||||
const div2 = doc.createElement('div');
|
||||
const div3 = doc.createElement('div');
|
||||
|
||||
doc.prepend(html);
|
||||
testing.expectEqual(1, doc.childNodes.length);
|
||||
testing.expectEqual(html, doc.childNodes[0]);
|
||||
|
||||
html.prepend(body);
|
||||
testing.expectEqual(1, html.childNodes.length);
|
||||
testing.expectEqual(body, html.childNodes[0]);
|
||||
|
||||
body.append(div1);
|
||||
body.prepend(div2, div3);
|
||||
testing.expectEqual(3, body.childNodes.length);
|
||||
testing.expectEqual(div2, body.childNodes[0]);
|
||||
testing.expectEqual(div3, body.childNodes[1]);
|
||||
testing.expectEqual(div1, body.childNodes[2]);
|
||||
|
||||
body.prepend('text node');
|
||||
testing.expectEqual(4, body.childNodes.length);
|
||||
testing.expectEqual(3, body.childNodes[0].nodeType);
|
||||
testing.expectEqual('text node', body.childNodes[0].textContent);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=children>
|
||||
testing.expectEqual(1, document.children.length);
|
||||
testing.expectEqual('HTML', document.children.item(0).nodeName)
|
||||
testing.expectEqual('HTML', document.firstElementChild.nodeName);
|
||||
testing.expectEqual('HTML', document.lastElementChild.nodeName);
|
||||
testing.expectEqual(1, document.childElementCount);
|
||||
|
||||
let nd = new Document();
|
||||
testing.expectEqual(0, nd.children.length);
|
||||
testing.expectEqual(null, nd.children.item(0));
|
||||
testing.expectEqual(null, nd.firstElementChild);
|
||||
testing.expectEqual(null, nd.lastElementChild);
|
||||
testing.expectEqual(0, nd.childElementCount);
|
||||
</script>
|
||||
|
||||
<script id=adoptedStyleSheets>
|
||||
{
|
||||
const acss = document.adoptedStyleSheets;
|
||||
testing.expectEqual(0, acss.length);
|
||||
acss.push(new CSSStyleSheet());
|
||||
testing.expectEqual(1, acss.length);
|
||||
}
|
||||
</script>
|
||||
237
src/browser/tests/document/element_from_point.html
Normal file
237
src/browser/tests/document/element_from_point.html
Normal file
@@ -0,0 +1,237 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<body>
|
||||
<div id="div1" style="width: 100px; height: 50px;">Div 1</div>
|
||||
<div id="div2" style="width: 100px; height: 50px;">Div 2</div>
|
||||
<div id="hidden" style="display: none; width: 100px; height: 50px;">Hidden</div>
|
||||
<div id="parent" style="width: 100px; height: 50px;">
|
||||
<div id="child" style="width: 80px; height: 30px;">Child</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
<script id="basic_usage">
|
||||
{
|
||||
// Test finding an element at a specific point
|
||||
const div1 = document.getElementById('div1');
|
||||
const rect1 = div1.getBoundingClientRect();
|
||||
|
||||
// Query near the top of div1 to avoid overlap with later elements
|
||||
const x = rect1.left + 10;
|
||||
const y = rect1.top + 5;
|
||||
const element = document.elementFromPoint(x, y);
|
||||
|
||||
// Should return div1 or a parent (body/html) - not null
|
||||
testing.expectTrue(element !== null);
|
||||
// If it returns div1 specifically, that's ideal
|
||||
// But we also accept parent elements
|
||||
testing.expectTrue(element === div1 || element.tagName === 'BODY' || element.tagName === 'HTML');
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="nested_elements">
|
||||
{
|
||||
// Test that nested elements are found (topmost in document order)
|
||||
const child = document.getElementById('child');
|
||||
const parent = document.getElementById('parent');
|
||||
const rect = child.getBoundingClientRect();
|
||||
|
||||
const centerX = (rect.left + rect.right) / 2;
|
||||
const centerY = (rect.top + rect.bottom) / 2;
|
||||
const element = document.elementFromPoint(centerX, centerY);
|
||||
|
||||
// Should return the child element (topmost in document order) or parent
|
||||
testing.expectTrue(element !== null);
|
||||
testing.expectTrue(element === child || element === parent ||
|
||||
element.tagName === 'BODY' || element.tagName === 'HTML');
|
||||
}
|
||||
</script>
|
||||
<!-- ZIGDOM new CSS Parser -->
|
||||
<!-- <script id="hidden_elements">
|
||||
{
|
||||
// Test that hidden elements are not returned
|
||||
const hidden = document.getElementById('hidden');
|
||||
console.warn('pre');
|
||||
console.warn(hidden.checkVisibility());
|
||||
const rect = hidden.getBoundingClientRect();
|
||||
|
||||
// Even though hidden element has dimensions, it shouldn't be returned
|
||||
// because it has display: none
|
||||
const centerX = (rect.left + rect.right) / 2;
|
||||
const centerY = (rect.top + rect.bottom) / 2;
|
||||
const element = document.elementFromPoint(centerX, centerY);
|
||||
|
||||
// Should not return the hidden element (should return body or html instead)
|
||||
testing.expectTrue(element === null || element.id !== 'hidden');
|
||||
}
|
||||
</script> -->
|
||||
|
||||
<script id="outside_viewport">
|
||||
{
|
||||
// Test points outside all elements
|
||||
const element = document.elementFromPoint(-1000, -1000);
|
||||
testing.expectEqual(null, element);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="at_element_center">
|
||||
{
|
||||
// Test querying at the center of an element
|
||||
const div1 = document.getElementById('div1');
|
||||
const rect = div1.getBoundingClientRect();
|
||||
|
||||
const centerX = (rect.left + rect.right) / 2;
|
||||
const centerY = (rect.top + rect.bottom) / 2;
|
||||
const element = document.elementFromPoint(centerX, centerY);
|
||||
|
||||
// Should return div1 or one of its ancestors (body/html)
|
||||
testing.expectTrue(element !== null);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="dynamically_created">
|
||||
{
|
||||
// Test with dynamically created elements
|
||||
const newDiv = document.createElement('div');
|
||||
newDiv.style.width = '50px';
|
||||
newDiv.style.height = '50px';
|
||||
newDiv.textContent = 'Dynamic';
|
||||
document.body.appendChild(newDiv);
|
||||
|
||||
const rect = newDiv.getBoundingClientRect();
|
||||
const centerX = (rect.left + rect.right) / 2;
|
||||
const centerY = (rect.top + rect.bottom) / 2;
|
||||
const element = document.elementFromPoint(centerX, centerY);
|
||||
|
||||
testing.expectEqual(newDiv, element);
|
||||
|
||||
// Clean up
|
||||
newDiv.remove();
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="elementsFromPoint_basic">
|
||||
{
|
||||
// Test that elementsFromPoint returns array of element and its ancestors
|
||||
const div1 = document.getElementById('div1');
|
||||
const rect = div1.getBoundingClientRect();
|
||||
|
||||
const x = rect.left + 10;
|
||||
const y = rect.top + 5;
|
||||
const elements = document.elementsFromPoint(x, y);
|
||||
|
||||
// Should return an array
|
||||
testing.expectTrue(Array.isArray(elements));
|
||||
testing.expectTrue(elements.length > 0);
|
||||
|
||||
// First element should be div1 or one of its ancestors
|
||||
testing.expectTrue(elements[0] !== null);
|
||||
|
||||
// All elements should be ancestors of each other (parent chain)
|
||||
for (let i = 1; i < elements.length; i++) {
|
||||
let found = false;
|
||||
let parent = elements[i - 1].parentElement;
|
||||
while (parent) {
|
||||
if (parent === elements[i]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
parent = parent.parentElement;
|
||||
}
|
||||
testing.expectTrue(found || elements[i].tagName === 'HTML');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="elementsFromPoint_nested">
|
||||
{
|
||||
// Test with nested elements - should return child, parent, body, html in order
|
||||
const child = document.getElementById('child');
|
||||
const parent = document.getElementById('parent');
|
||||
const rect = child.getBoundingClientRect();
|
||||
|
||||
const centerX = (rect.left + rect.right) / 2;
|
||||
const centerY = (rect.top + rect.bottom) / 2;
|
||||
const elements = document.elementsFromPoint(centerX, centerY);
|
||||
|
||||
testing.expectTrue(Array.isArray(elements));
|
||||
testing.expectTrue(elements.length >= 2); // At least child and parent (or more ancestors)
|
||||
|
||||
// First element should be the deepest (child or parent)
|
||||
testing.expectTrue(elements[0] === child || elements[0] === parent ||
|
||||
elements[0].tagName === 'BODY' || elements[0].tagName === 'HTML');
|
||||
|
||||
// If we got child as first element, parent should be in the array
|
||||
if (elements[0] === child) {
|
||||
let foundParent = false;
|
||||
for (let el of elements) {
|
||||
if (el === parent) {
|
||||
foundParent = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
testing.expectTrue(foundParent);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="elementsFromPoint_order">
|
||||
{
|
||||
// Test that elements are returned in order from topmost to deepest
|
||||
const child = document.getElementById('child');
|
||||
const parent = document.getElementById('parent');
|
||||
const rect = child.getBoundingClientRect();
|
||||
|
||||
const centerX = (rect.left + rect.right) / 2;
|
||||
const centerY = (rect.top + rect.bottom) / 2;
|
||||
const elements = document.elementsFromPoint(centerX, centerY);
|
||||
|
||||
// Elements should be ordered such that each element is a parent of the previous
|
||||
for (let i = 1; i < elements.length; i++) {
|
||||
const current = elements[i - 1];
|
||||
const next = elements[i];
|
||||
|
||||
// next should be an ancestor of current
|
||||
let isAncestor = false;
|
||||
let p = current.parentElement;
|
||||
while (p) {
|
||||
if (p === next) {
|
||||
isAncestor = true;
|
||||
break;
|
||||
}
|
||||
p = p.parentElement;
|
||||
}
|
||||
|
||||
testing.expectTrue(isAncestor || next.tagName === 'HTML');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="elementsFromPoint_outside">
|
||||
{
|
||||
// Test with point outside all elements
|
||||
const elements = document.elementsFromPoint(-1000, -1000);
|
||||
|
||||
testing.expectTrue(Array.isArray(elements));
|
||||
testing.expectEqual(0, elements.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- ZIGDOM new CSS Parser -->
|
||||
<!-- <script id="elementsFromPoint_hidden">
|
||||
{
|
||||
// Test that hidden elements are not included
|
||||
const hidden = document.getElementById('hidden');
|
||||
const rect = hidden.getBoundingClientRect();
|
||||
|
||||
const centerX = (rect.left + rect.right) / 2;
|
||||
const centerY = (rect.top + rect.bottom) / 2;
|
||||
const elements = document.elementsFromPoint(centerX, centerY);
|
||||
|
||||
// Should not include the hidden element
|
||||
for (let el of elements) {
|
||||
testing.expectTrue(el.id !== 'hidden');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
-->
|
||||
90
src/browser/tests/document/focus.html
Normal file
90
src/browser/tests/document/focus.html
Normal file
@@ -0,0 +1,90 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
<body>
|
||||
<input id="input1" type="text">
|
||||
<input id="input2" type="text">
|
||||
<button id="btn1">Button</button>
|
||||
</body>
|
||||
|
||||
<script id="activeElement_default">
|
||||
{
|
||||
const body = document.querySelector('body');
|
||||
body.focus();
|
||||
testing.expectEqual('BODY', document.activeElement.tagName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="focus_method">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
input1.focus();
|
||||
testing.expectEqual(input1, document.activeElement);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="focus_events">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
const input2 = $('#input2');
|
||||
|
||||
// Explicitly blur any focused element
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
let focusCount = 0;
|
||||
let blurCount = 0;
|
||||
|
||||
input1.addEventListener('focus', () => focusCount++);
|
||||
input1.addEventListener('blur', () => blurCount++);
|
||||
input2.addEventListener('focus', () => focusCount++);
|
||||
|
||||
input1.focus();
|
||||
testing.expectEqual(1, focusCount);
|
||||
testing.expectEqual(0, blurCount);
|
||||
|
||||
input2.focus();
|
||||
testing.expectEqual(2, focusCount);
|
||||
testing.expectEqual(1, blurCount);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="blur_method">
|
||||
{
|
||||
const btn = $('#btn1');
|
||||
btn.focus();
|
||||
testing.expectEqual(btn, document.activeElement);
|
||||
|
||||
btn.blur();
|
||||
testing.expectEqual('BODY', document.activeElement.tagName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="focus_already_focused">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
|
||||
// Explicitly blur any focused element
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
let focusCount = 0;
|
||||
input1.addEventListener('focus', () => focusCount++);
|
||||
|
||||
input1.focus();
|
||||
testing.expectEqual(1, focusCount);
|
||||
|
||||
input1.focus();
|
||||
testing.expectEqual(1, focusCount);
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
<script id="focus_disconnected">
|
||||
{
|
||||
const focused = document.activeElement;
|
||||
document.createElement('a').focus();
|
||||
testing.expectEqual(focused, document.activeElement);
|
||||
}
|
||||
</script>
|
||||
35
src/browser/tests/document/get_element_by_id.html
Normal file
35
src/browser/tests/document/get_element_by_id.html
Normal file
@@ -0,0 +1,35 @@
|
||||
<!DOCTYPE html>
|
||||
<body>
|
||||
<script src="../testing.js"></script>
|
||||
<div id="div-1">x: <p id=p1>d1</p></div>
|
||||
</body>
|
||||
|
||||
<script id=getElementById>
|
||||
testing.expectEqual(null, document.getElementById(null));
|
||||
testing.expectEqual(null, document.getElementById(23));
|
||||
testing.expectEqual(null, document.getElementById('value'));
|
||||
testing.expectEqual('x: d1', document.getElementById('div-1').textContent);
|
||||
testing.expectEqual('d1', document.getElementById('p1').textContent);
|
||||
document.getElementById('p1').id = 'p2'
|
||||
testing.expectEqual(null, document.getElementById('p1'));
|
||||
testing.expectEqual('d1', document.getElementById('p2').textContent);
|
||||
|
||||
const div = document.createElement('div');
|
||||
div.id = 'hello';
|
||||
testing.expectEqual(null, document.getElementById('hello'));
|
||||
const body = document.getElementsByTagName('body')[0];
|
||||
body.appendChild(div);
|
||||
testing.expectEqual('hello', document.getElementById('hello').id);
|
||||
|
||||
div.setAttribute('ID', 'world')
|
||||
testing.expectEqual(null, document.getElementById('hello'));
|
||||
testing.expectEqual('world', document.getElementById('world').id);
|
||||
|
||||
body.replaceChildren(div);
|
||||
testing.expectEqual('world', document.getElementById('world').id);
|
||||
testing.expectEqual(null, document.getElementById('div-1'));
|
||||
testing.expectEqual(null, document.getElementById('p1'));
|
||||
|
||||
div.removeAttribute('id');
|
||||
testing.expectEqual(null, document.getElementById('world'));
|
||||
</script>
|
||||
@@ -0,0 +1,48 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<div id="div1" class="foo bar">Div 1</div>
|
||||
<div id="div2" class="bar foo">Div 2</div>
|
||||
<div id="div3" class="foo bar baz">Div 3</div>
|
||||
<div id="div4" class="foo">Div 4</div>
|
||||
<div id="div5" class="bar">Div 5</div>
|
||||
<div id="div6" class="baz foo bar">Div 6</div>
|
||||
|
||||
<script id=getElementsByClassName_single>
|
||||
{
|
||||
const fooElements = document.getElementsByClassName('foo');
|
||||
testing.expectEqual(5, fooElements.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=getElementsByClassName_multiple>
|
||||
{
|
||||
// Should match elements that have BOTH foo AND bar
|
||||
const fooBarElements = document.getElementsByClassName('foo bar');
|
||||
testing.expectEqual(4, fooBarElements.length);
|
||||
|
||||
// Order shouldn't matter
|
||||
const barFooElements = document.getElementsByClassName('bar foo');
|
||||
testing.expectEqual(4, barFooElements.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=getElementsByClassName_three>
|
||||
{
|
||||
// Should match elements that have ALL three classes
|
||||
const threeClasses = document.getElementsByClassName('foo bar baz');
|
||||
testing.expectEqual(2, threeClasses.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=getElementsByClassName_whitespace>
|
||||
{
|
||||
// Multiple spaces, tabs, newlines should be treated as separators
|
||||
const multiSpace = document.getElementsByClassName('foo bar');
|
||||
testing.expectEqual(4, multiSpace.length);
|
||||
|
||||
// Leading/trailing whitespace should be ignored
|
||||
const withSpaces = document.getElementsByClassName(' foo bar ');
|
||||
testing.expectEqual(4, withSpaces.length);
|
||||
}
|
||||
</script>
|
||||
98
src/browser/tests/document/get_elements_by_class_name.html
Normal file
98
src/browser/tests/document/get_elements_by_class_name.html
Normal file
@@ -0,0 +1,98 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<div class="foo">foo1</div>
|
||||
<span class="foo">foo2</span>
|
||||
<p class="foo" id="foo3">foo3</p>
|
||||
<div class="bar">bar1</div>
|
||||
<div class="baz">baz1</div>
|
||||
|
||||
<div class="multi class names">multi1</div>
|
||||
<span class="class multi">multi2</span>
|
||||
|
||||
<div id="container">
|
||||
<div class="nested">nested1</div>
|
||||
<div class="nested">nested2</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const foos = document.getElementsByClassName('foo');
|
||||
</script>
|
||||
|
||||
<script id=basic>
|
||||
// testing.expectEqual(0, document.getElementsByClassName('nonexistent').length);
|
||||
// testing.expectEqual(0, document.getElementsByClassName('unknown').length);
|
||||
|
||||
testing.expectEqual(true, foos instanceof HTMLCollection);
|
||||
testing.expectEqual(3, foos.length);
|
||||
testing.expectEqual(3, foos.length); // cache test
|
||||
testing.expectEqual('foo1', foos[0].textContent);
|
||||
testing.expectEqual('foo2', foos[1].textContent);
|
||||
testing.expectEqual('foo3', foos[2].textContent);
|
||||
testing.expectEqual('foo1', foos[0].textContent); // cache test
|
||||
testing.expectEqual('foo3', foos[2].textContent);
|
||||
testing.expectEqual('foo2', foos[1].textContent);
|
||||
testing.expectEqual(undefined, foos[-1]);
|
||||
testing.expectEqual(undefined, foos[3]);
|
||||
testing.expectEqual(undefined, foos[100]);
|
||||
|
||||
const bars = document.getElementsByClassName('bar');
|
||||
testing.expectEqual(1, bars.length);
|
||||
testing.expectEqual('bar1', bars[0].textContent);
|
||||
|
||||
const bazs = document.getElementsByClassName('baz');
|
||||
testing.expectEqual(1, bazs.length);
|
||||
testing.expectEqual('baz1', bazs[0].textContent);
|
||||
</script>
|
||||
|
||||
<script id=item>
|
||||
testing.expectEqual('foo2', foos.item(1).textContent);
|
||||
testing.expectEqual(null, foos.item(-1));
|
||||
testing.expectEqual('foo1', foos.item(0).textContent);
|
||||
testing.expectEqual(null, foos.item(-100));
|
||||
testing.expectEqual(null, foos.item(3));
|
||||
testing.expectEqual(null, foos.item(100));
|
||||
</script>
|
||||
|
||||
<script id=namedItem>
|
||||
testing.expectEqual('foo3', foos.namedItem('foo3').id);
|
||||
testing.expectEqual(null, foos.namedItem('foo1'));
|
||||
testing.expectEqual(null, foos.namedItem('bar'));
|
||||
testing.expectEqual(null, foos.namedItem('nonexistent'));
|
||||
|
||||
testing.expectEqual('foo3', foos['foo3'].id);
|
||||
</script>
|
||||
|
||||
<script id=iterator>
|
||||
let acc = [];
|
||||
for (let x of foos) {
|
||||
acc.push(x.textContent);
|
||||
}
|
||||
testing.expectEqual(['foo1', 'foo2', 'foo3'], acc);
|
||||
</script>
|
||||
|
||||
<script id=emptyString>
|
||||
const empty = document.getElementsByClassName('');
|
||||
testing.expectEqual(0, empty.length);
|
||||
</script>
|
||||
|
||||
<script id=multipleClasses>
|
||||
const multi = document.getElementsByClassName('multi');
|
||||
testing.expectEqual(2, multi.length);
|
||||
testing.expectEqual('multi1', multi[0].textContent);
|
||||
testing.expectEqual('multi2', multi[1].textContent);
|
||||
|
||||
const classCol = document.getElementsByClassName('class');
|
||||
testing.expectEqual(2, classCol.length);
|
||||
|
||||
const names = document.getElementsByClassName('names');
|
||||
testing.expectEqual(1, names.length);
|
||||
testing.expectEqual('multi1', names[0].textContent);
|
||||
</script>
|
||||
|
||||
<script id=nested>
|
||||
const nested = document.getElementsByClassName('nested');
|
||||
testing.expectEqual(2, nested.length);
|
||||
testing.expectEqual('nested1', nested[0].textContent);
|
||||
testing.expectEqual('nested2', nested[1].textContent);
|
||||
</script>
|
||||
60
src/browser/tests/document/get_elements_by_name.html
Normal file
60
src/browser/tests/document/get_elements_by_name.html
Normal file
@@ -0,0 +1,60 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<input name="username" value="john">
|
||||
<input name="password" type="password">
|
||||
<input name="username" value="jane">
|
||||
<button name="submit">Submit</button>
|
||||
<a name="section1">Section 1</a>
|
||||
<a name="username">User Link</a>
|
||||
|
||||
<script id=getElementsByName_basic>
|
||||
{
|
||||
const usernames = document.getElementsByName('username');
|
||||
testing.expectEqual(3, usernames.length);
|
||||
testing.expectEqual('INPUT', usernames[0].tagName);
|
||||
testing.expectEqual('john', usernames[0].value);
|
||||
testing.expectEqual('INPUT', usernames[1].tagName);
|
||||
testing.expectEqual('jane', usernames[1].value);
|
||||
testing.expectEqual('A', usernames[2].tagName);
|
||||
|
||||
const passwords = document.getElementsByName('password');
|
||||
testing.expectEqual(1, passwords.length);
|
||||
testing.expectEqual('password', passwords[0].type);
|
||||
|
||||
const submits = document.getElementsByName('submit');
|
||||
testing.expectEqual(1, submits.length);
|
||||
testing.expectEqual('BUTTON', submits[0].tagName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=getElementsByName_empty>
|
||||
{
|
||||
const nonexistent = document.getElementsByName('nonexistent');
|
||||
testing.expectEqual(0, nonexistent.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=getElementsByName_live_collection>
|
||||
{
|
||||
const usernames = document.getElementsByName('username');
|
||||
const initialLength = usernames.length;
|
||||
|
||||
const newInput = document.createElement('input');
|
||||
newInput.name = 'username';
|
||||
newInput.value = 'bob';
|
||||
document.body.appendChild(newInput);
|
||||
|
||||
testing.expectEqual(initialLength + 1, usernames.length);
|
||||
testing.expectEqual(newInput, usernames[usernames.length - 1]);
|
||||
|
||||
newInput.removeAttribute('name');
|
||||
testing.expectEqual(initialLength, usernames.length);
|
||||
|
||||
newInput.name = 'username';
|
||||
testing.expectEqual(initialLength + 1, usernames.length);
|
||||
|
||||
newInput.remove();
|
||||
testing.expectEqual(initialLength, usernames.length);
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,39 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<head>
|
||||
<title>Test</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="div1">
|
||||
<span id="span1">Text</span>
|
||||
</div>
|
||||
<p id="p1">Paragraph</p>
|
||||
</body>
|
||||
|
||||
<script id=getElementsByTagName_wildcard>
|
||||
{
|
||||
const allElements = document.getElementsByTagName('*');
|
||||
testing.expectEqual('HTMLCollection', allElements.constructor.name);
|
||||
|
||||
// Should include: html, head, title, script (testing.js), body, div, span, p, script (this one)
|
||||
// At least 9 elements
|
||||
testing.expectEqual(true, allElements.length >= 9);
|
||||
|
||||
// Check some specific elements are included
|
||||
let foundDiv = false;
|
||||
let foundSpan = false;
|
||||
let foundP = false;
|
||||
|
||||
for (let i = 0; i < allElements.length; i++) {
|
||||
const el = allElements[i];
|
||||
if (el.tagName === 'DIV') foundDiv = true;
|
||||
if (el.tagName === 'SPAN') foundSpan = true;
|
||||
if (el.tagName === 'P') foundP = true;
|
||||
}
|
||||
|
||||
testing.expectEqual(true, foundDiv);
|
||||
testing.expectEqual(true, foundSpan);
|
||||
testing.expectEqual(true, foundP);
|
||||
}
|
||||
</script>
|
||||
164
src/browser/tests/document/get_elements_by_tag_name.html
Normal file
164
src/browser/tests/document/get_elements_by_tag_name.html
Normal file
@@ -0,0 +1,164 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
<div>0</div>
|
||||
<div>1</div>
|
||||
<div>2</div>
|
||||
|
||||
<p id=p1></p>
|
||||
<p id=p2></p>
|
||||
<p id=p3></p>
|
||||
|
||||
<h1>H1</h1>
|
||||
<h2>H2</h2>
|
||||
<h3>H3</h3>
|
||||
<h4>H4</h4>
|
||||
<h5>H5</h5>
|
||||
<h6>H6</h6>
|
||||
<b>Bold</b>
|
||||
<i>Italic</i>
|
||||
<em>Emphasized</em>
|
||||
<strong>Strong</strong>
|
||||
<header>Header</header>
|
||||
<nav>Nav</nav>
|
||||
<main>Main</main>
|
||||
|
||||
<script id=basic>
|
||||
testing.expectEqual(24, document.getElementsByTagName('*').length);
|
||||
testing.expectEqual(0, document.getElementsByTagName('a').length);
|
||||
testing.expectEqual(0, document.getElementsByTagName('unknown').length);
|
||||
|
||||
const divs = document.getElementsByTagName('div');
|
||||
testing.expectEqual(true, divs instanceof HTMLCollection);
|
||||
testing.expectEqual(3, divs.length);
|
||||
testing.expectEqual(3, divs.length);
|
||||
testing.expectEqual('0', divs[0].textContent);
|
||||
testing.expectEqual('0', divs[0].textContent);
|
||||
testing.expectEqual('0', divs[0].textContent);
|
||||
testing.expectEqual('1', divs[1].textContent);
|
||||
testing.expectEqual('2', divs[2].textContent);
|
||||
testing.expectEqual('2', divs[2].textContent);
|
||||
testing.expectEqual('1', divs[1].textContent);
|
||||
testing.expectEqual('1', divs[1].textContent);
|
||||
testing.expectEqual('2', divs[2].textContent);
|
||||
testing.expectEqual('0', divs[0].textContent);
|
||||
testing.expectEqual(undefined, divs[-1]);
|
||||
testing.expectEqual(undefined, divs[4]);
|
||||
|
||||
testing.expectEqual('2', divs.item(2).textContent);
|
||||
testing.expectEqual(null, divs.item(-3));
|
||||
testing.expectEqual('0', divs.item(0).textContent);
|
||||
testing.expectEqual(null, divs.item(-100));
|
||||
</script>
|
||||
|
||||
<script id=namedItem>
|
||||
testing.expectEqual(null, divs.namedItem('d1'));
|
||||
|
||||
const ps = document.getElementsByTagName('p');
|
||||
testing.expectEqual('p1', ps.namedItem('p1').id);
|
||||
testing.expectEqual('p2', ps.namedItem('p2').id);
|
||||
testing.expectEqual('p3', ps.namedItem('p3').id);
|
||||
testing.expectEqual(null, ps.namedItem('p4'));
|
||||
|
||||
testing.expectEqual('p1', ps['p1'].id);
|
||||
</script>
|
||||
|
||||
<script id=iterator>
|
||||
let acc = [];
|
||||
for (let x of ps) {
|
||||
acc.push(x.id);
|
||||
}
|
||||
testing.expectEqual(['p1', 'p2', 'p3'], acc);
|
||||
</script>
|
||||
|
||||
<script id=extendedTags>
|
||||
// Test headings
|
||||
testing.expectEqual(1, document.getElementsByTagName('h1').length);
|
||||
testing.expectEqual('H1', document.getElementsByTagName('h1')[0].textContent);
|
||||
testing.expectEqual(1, document.getElementsByTagName('h2').length);
|
||||
testing.expectEqual('H2', document.getElementsByTagName('h2')[0].textContent);
|
||||
testing.expectEqual(1, document.getElementsByTagName('h3').length);
|
||||
testing.expectEqual(1, document.getElementsByTagName('h4').length);
|
||||
testing.expectEqual(1, document.getElementsByTagName('h5').length);
|
||||
testing.expectEqual(1, document.getElementsByTagName('h6').length);
|
||||
|
||||
// Test case insensitivity
|
||||
testing.expectEqual(1, document.getElementsByTagName('H1').length);
|
||||
testing.expectEqual('H1', document.getElementsByTagName('H1')[0].textContent);
|
||||
|
||||
// Test text formatting elements
|
||||
testing.expectEqual(1, document.getElementsByTagName('b').length);
|
||||
testing.expectEqual('Bold', document.getElementsByTagName('b')[0].textContent);
|
||||
testing.expectEqual(1, document.getElementsByTagName('i').length);
|
||||
testing.expectEqual('Italic', document.getElementsByTagName('i')[0].textContent);
|
||||
testing.expectEqual(1, document.getElementsByTagName('em').length);
|
||||
testing.expectEqual('Emphasized', document.getElementsByTagName('em')[0].textContent);
|
||||
testing.expectEqual(1, document.getElementsByTagName('strong').length);
|
||||
testing.expectEqual('Strong', document.getElementsByTagName('strong')[0].textContent);
|
||||
|
||||
// Test structural elements
|
||||
testing.expectEqual(1, document.getElementsByTagName('header').length);
|
||||
testing.expectEqual('Header', document.getElementsByTagName('header')[0].textContent);
|
||||
testing.expectEqual(1, document.getElementsByTagName('nav').length);
|
||||
testing.expectEqual('Nav', document.getElementsByTagName('nav')[0].textContent);
|
||||
testing.expectEqual(1, document.getElementsByTagName('main').length);
|
||||
testing.expectEqual('Main', document.getElementsByTagName('main')[0].textContent);
|
||||
</script>
|
||||
|
||||
<script id=multipleIterators>
|
||||
{
|
||||
const list = document.getElementsByTagName('p');
|
||||
|
||||
const iter1 = list[Symbol.iterator]();
|
||||
const iter2 = list[Symbol.iterator]();
|
||||
|
||||
const val1_iter1 = iter1.next();
|
||||
testing.expectEqual(false, val1_iter1.done);
|
||||
testing.expectEqual('p1', val1_iter1.value.id);
|
||||
|
||||
const val1_iter2 = iter2.next();
|
||||
testing.expectEqual(false, val1_iter2.done);
|
||||
testing.expectEqual('p1', val1_iter2.value.id);
|
||||
|
||||
const val2_iter1 = iter1.next();
|
||||
testing.expectEqual(false, val2_iter1.done);
|
||||
testing.expectEqual('p2', val2_iter1.value.id);
|
||||
|
||||
const val2_iter2 = iter2.next();
|
||||
testing.expectEqual(false, val2_iter2.done);
|
||||
testing.expectEqual('p2', val2_iter2.value.id);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=iteratorLifetime>
|
||||
{
|
||||
let iter;
|
||||
{
|
||||
const list = document.getElementsByTagName('p');
|
||||
iter = list[Symbol.iterator]();
|
||||
}
|
||||
|
||||
const val1 = iter.next();
|
||||
testing.expectEqual(false, val1.done);
|
||||
testing.expectEqual('p1', val1.value.id);
|
||||
|
||||
const val2 = iter.next();
|
||||
testing.expectEqual(false, val2.done);
|
||||
testing.expectEqual('p2', val2.value.id);
|
||||
|
||||
const val3 = iter.next();
|
||||
testing.expectEqual(false, val3.done);
|
||||
testing.expectEqual('p3', val3.value.id);
|
||||
|
||||
const val4 = iter.next();
|
||||
testing.expectEqual(true, val4.done);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=list_caching>
|
||||
{
|
||||
// this ordering used to crash
|
||||
const list = document.getElementsByTagName('div');
|
||||
testing.expectEqual('0', list[0].textContent);
|
||||
testing.expectEqual(3, list.length);
|
||||
}
|
||||
</script>
|
||||
54
src/browser/tests/document/insert_adjacent_element.html
Normal file
54
src/browser/tests/document/insert_adjacent_element.html
Normal file
@@ -0,0 +1,54 @@
|
||||
<!DOCTYPE html>
|
||||
<head id="the_head">
|
||||
<title>Test Document Title</title>
|
||||
<script src="../testing.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- This structure will get mutated by insertAdjacentElement test -->
|
||||
<div id="insert-adjacent-element-outer-wrapper">
|
||||
<div id="insert-adjacent-element-inner-wrapper">
|
||||
<span></span>
|
||||
<p>content</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
<script id=insertAdjacentElement>
|
||||
// Insert "beforeend".
|
||||
const wrapper = $("#insert-adjacent-element-inner-wrapper");
|
||||
const h1 = document.createElement("h1");
|
||||
h1.innerHTML = "title";
|
||||
wrapper.insertAdjacentElement("beforeend", h1);
|
||||
let newElement = wrapper.lastElementChild;
|
||||
testing.expectEqual("H1", newElement.tagName);
|
||||
testing.expectEqual("title", newElement.innerText);
|
||||
|
||||
// Insert "beforebegin".
|
||||
const h2 = document.createElement("h2");
|
||||
h2.innerHTML = "small title";
|
||||
wrapper.insertAdjacentElement("beforebegin", h2);
|
||||
newElement = wrapper.previousElementSibling;
|
||||
testing.expectEqual("H2", newElement.tagName);
|
||||
testing.expectEqual("small title", newElement.innerText);
|
||||
|
||||
// Insert "afterend".
|
||||
const divAfterEnd = document.createElement("div");
|
||||
divAfterEnd.id = "afterend";
|
||||
divAfterEnd.innerHTML = "after end";
|
||||
wrapper.insertAdjacentElement("afterend", divAfterEnd);
|
||||
newElement = wrapper.nextElementSibling;
|
||||
testing.expectEqual("DIV", newElement.tagName);
|
||||
testing.expectEqual("after end", newElement.innerText);
|
||||
testing.expectEqual("afterend", newElement.id);
|
||||
|
||||
// Insert "afterbegin".
|
||||
const divAfterBegin = document.createElement("div");
|
||||
divAfterBegin.className = "afterbegin";
|
||||
divAfterBegin.innerHTML = "after begin";
|
||||
wrapper.insertAdjacentElement("afterbegin", divAfterBegin);
|
||||
newElement = wrapper.firstElementChild;
|
||||
testing.expectEqual("DIV", newElement.tagName);
|
||||
testing.expectEqual("after begin", newElement.innerText);
|
||||
testing.expectEqual("afterbegin", newElement.className);
|
||||
</script>
|
||||
44
src/browser/tests/document/insert_adjacent_html.html
Normal file
44
src/browser/tests/document/insert_adjacent_html.html
Normal file
@@ -0,0 +1,44 @@
|
||||
<!DOCTYPE html>
|
||||
<head id="the_head">
|
||||
<title>Test Document Title</title>
|
||||
<script src="../testing.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<!-- This structure will get mutated by insertAdjacentHTML test -->
|
||||
<div id="insert-adjacent-html-outer-wrapper">
|
||||
<div id="insert-adjacent-html-inner-wrapper">
|
||||
<span></span>
|
||||
<p>content</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
<script id=insertAdjacentHTML>
|
||||
// Insert "beforeend".
|
||||
const wrapper = $("#insert-adjacent-html-inner-wrapper");
|
||||
wrapper.insertAdjacentHTML("beforeend", "<h1>title</h1>");
|
||||
let newElement = wrapper.lastElementChild;
|
||||
testing.expectEqual("H1", newElement.tagName);
|
||||
testing.expectEqual("title", newElement.innerText);
|
||||
|
||||
// Insert "beforebegin".
|
||||
wrapper.insertAdjacentHTML("beforebegin", "<h2>small title</h2>");
|
||||
newElement = wrapper.previousElementSibling;
|
||||
testing.expectEqual("H2", newElement.tagName);
|
||||
testing.expectEqual("small title", newElement.innerText);
|
||||
|
||||
// Insert "afterend".
|
||||
wrapper.insertAdjacentHTML("afterend", "<div id=\"afterend\">after end</div>");
|
||||
newElement = wrapper.nextElementSibling;
|
||||
testing.expectEqual("DIV", newElement.tagName);
|
||||
testing.expectEqual("after end", newElement.innerText);
|
||||
testing.expectEqual("afterend", newElement.id);
|
||||
|
||||
// Insert "afterbegin".
|
||||
wrapper.insertAdjacentHTML("afterbegin", "<div class=\"afterbegin\">after begin</div><yy></yy>");
|
||||
newElement = wrapper.firstElementChild;
|
||||
testing.expectEqual("DIV", newElement.tagName);
|
||||
testing.expectEqual("after begin", newElement.innerText);
|
||||
testing.expectEqual("afterbegin", newElement.className);
|
||||
</script>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user