mirror of
https://github.com/lightpanda-io/browser.git
synced 2026-03-28 15:40:04 +00:00
Compare commits
805 Commits
v0.2.2
...
wp/mrdimid
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98124e97aa | ||
|
|
dd1c758c0e | ||
|
|
0d87c352b2 | ||
|
|
918f6ce0e6 | ||
|
|
6c5efe6ce0 | ||
|
|
f0be6675e7 | ||
|
|
6a8174a15c | ||
|
|
40c3f1b618 | ||
|
|
6dd2dac049 | ||
|
|
b39bbb557f | ||
|
|
f7682cba67 | ||
|
|
f94c07160a | ||
|
|
bbe6692580 | ||
|
|
9266a1c4d9 | ||
|
|
220d80f05f | ||
|
|
9144c909dd | ||
|
|
7981fcec84 | ||
|
|
71264c56fc | ||
|
|
ca0f77bdee | ||
|
|
fc8b1b8549 | ||
|
|
bc8c44f62f | ||
|
|
01fab5c92a | ||
|
|
1c07d786a0 | ||
|
|
6f0cd87d1c | ||
|
|
e44308cba2 | ||
|
|
50245c5157 | ||
|
|
9ca5188e12 | ||
|
|
e25c33eaa6 | ||
|
|
56cc881ac0 | ||
|
|
7bddc0a89c | ||
|
|
50896bdc9d | ||
|
|
8dd4567828 | ||
|
|
06ef6d3e6a | ||
|
|
14b58e8062 | ||
|
|
eee232c12c | ||
|
|
febe321aef | ||
|
|
28777ac717 | ||
|
|
13b008b56c | ||
|
|
403f42bf38 | ||
|
|
523efbd85a | ||
|
|
fcacc8bfc6 | ||
|
|
b2e301418f | ||
|
|
334a2e44a1 | ||
|
|
252b3c3bf6 | ||
|
|
c9121a03d2 | ||
|
|
cc93180d57 | ||
|
|
24221748e1 | ||
|
|
4062a425cb | ||
|
|
cce533ebb6 | ||
|
|
48df38cbfe | ||
|
|
f982f073df | ||
|
|
34999f12ca | ||
|
|
c8d5665653 | ||
|
|
ddebaf87d0 | ||
|
|
6b80cd6109 | ||
|
|
7635d8d2a5 | ||
|
|
141ae053db | ||
|
|
10ec4ff814 | ||
|
|
d2da0b7c0e | ||
|
|
7d0548406e | ||
|
|
634e3e35a0 | ||
|
|
da3dc58199 | ||
|
|
4f99df694b | ||
|
|
c121dbbd67 | ||
|
|
c1c0a7d494 | ||
|
|
0749f60702 | ||
|
|
982b8e2d72 | ||
|
|
6e7c8d7ae2 | ||
|
|
3c858f522b | ||
|
|
f2a30f8cdd | ||
|
|
43785bfab4 | ||
|
|
78edf6d324 | ||
|
|
73565c4493 | ||
|
|
ca0ef18bdf | ||
|
|
6ed011e2f8 | ||
|
|
23d322452a | ||
|
|
5d3b965d28 | ||
|
|
d9794d72c7 | ||
|
|
524b5be937 | ||
|
|
ac2e276a6a | ||
|
|
4f4dbc0c22 | ||
|
|
8c37cac957 | ||
|
|
eceab76b6f | ||
|
|
1f81b6ddc4 | ||
|
|
52c3aadd24 | ||
|
|
ad87573d09 | ||
|
|
20fbfc8544 | ||
|
|
7695c8403f | ||
|
|
421983d06e | ||
|
|
328c681a8f | ||
|
|
48d94d0f68 | ||
|
|
10ad5d763e | ||
|
|
2a78c946e4 | ||
|
|
a7872aa054 | ||
|
|
5c228ae0a1 | ||
|
|
ce73f7ac5a | ||
|
|
64107f5957 | ||
|
|
8a1795d56f | ||
|
|
b104c3bfe8 | ||
|
|
82e3f126ff | ||
|
|
175488563e | ||
|
|
da51cdd11d | ||
|
|
a8a47b138f | ||
|
|
b63d4cf675 | ||
|
|
03b999c592 | ||
|
|
a91afab038 | ||
|
|
d4747b5386 | ||
|
|
41b81c8b05 | ||
|
|
552831364d | ||
|
|
42b5e32473 | ||
|
|
e9c36fd6f8 | ||
|
|
952dfbef36 | ||
|
|
254984b600 | ||
|
|
8cbc58d257 | ||
|
|
e6cc3e8c34 | ||
|
|
516335e0ed | ||
|
|
01798ed7f8 | ||
|
|
fcad67a854 | ||
|
|
e359ffead0 | ||
|
|
eb09041859 | ||
|
|
b3d52c966d | ||
|
|
3fb8a14348 | ||
|
|
84a949e7c7 | ||
|
|
eaf1cb26b2 | ||
|
|
f37962d3de | ||
|
|
511e957d4b | ||
|
|
71df03b729 | ||
|
|
839052f4b8 | ||
|
|
7c18d857f0 | ||
|
|
947e672d18 | ||
|
|
96942960a9 | ||
|
|
8b0118e2c8 | ||
|
|
5f9a7a5381 | ||
|
|
6897d72c3e | ||
|
|
aae9a505e0 | ||
|
|
45196e022b | ||
|
|
b9e4c44d63 | ||
|
|
0a9e5b66ee | ||
|
|
8b99e82743 | ||
|
|
059fb85e22 | ||
|
|
8997df861a | ||
|
|
e65667963f | ||
|
|
3d51667fc8 | ||
|
|
7fc6e97cd8 | ||
|
|
1473e58a41 | ||
|
|
2394b2f44f | ||
|
|
516bd98198 | ||
|
|
7d8688a130 | ||
|
|
631ec70058 | ||
|
|
6fd51cfdc0 | ||
|
|
6857b74623 | ||
|
|
5ec4305a9f | ||
|
|
88baff96d0 | ||
|
|
e871f0002b | ||
|
|
7358d48e35 | ||
|
|
178fbf0fca | ||
|
|
a50597ff27 | ||
|
|
e4cb78abee | ||
|
|
732884a3b2 | ||
|
|
80f2c42c69 | ||
|
|
49a5a39659 | ||
|
|
a4a7040b98 | ||
|
|
de5a7d5b99 | ||
|
|
3f92e388be | ||
|
|
25c941b847 | ||
|
|
24b6934d3b | ||
|
|
d286ab406c | ||
|
|
ef6a7a6904 | ||
|
|
c61eda0d24 | ||
|
|
ad226b6fb1 | ||
|
|
24491f0dfe | ||
|
|
870fd1654d | ||
|
|
38bc912e4e | ||
|
|
315c9a2d92 | ||
|
|
a14ad6f700 | ||
|
|
d56e63a91b | ||
|
|
76dcdfb98c | ||
|
|
99c09ba8a1 | ||
|
|
0f18b76813 | ||
|
|
8504e4cd22 | ||
|
|
ebe793e0e7 | ||
|
|
965c6cf4d9 | ||
|
|
2b1ab3184e | ||
|
|
e7d21c2dbe | ||
|
|
11906d9d71 | ||
|
|
ac5a64d77a | ||
|
|
c86c851c60 | ||
|
|
721cf98486 | ||
|
|
84bbb6efd4 | ||
|
|
f897cda6cd | ||
|
|
2da8b25b09 | ||
|
|
3f94fd90dd | ||
|
|
bc6be22cb4 | ||
|
|
e23604e08d | ||
|
|
be858ac9ce | ||
|
|
137ab4a557 | ||
|
|
bad0fc386d | ||
|
|
641c7b2c89 | ||
|
|
21be3db51f | ||
|
|
e978857820 | ||
|
|
3bf596c54c | ||
|
|
aedb823b4d | ||
|
|
7a417435cc | ||
|
|
497d6e80f7 | ||
|
|
ae6ab34e72 | ||
|
|
4c26161728 | ||
|
|
1731dca5dd | ||
|
|
ee2caff46e | ||
|
|
db8fb8b05d | ||
|
|
bec7e141dc | ||
|
|
ab85b4b129 | ||
|
|
b030049b40 | ||
|
|
1338a3d89d | ||
|
|
181178296f | ||
|
|
df7888d6fb | ||
|
|
dd15f5e052 | ||
|
|
f348d85b11 | ||
|
|
8c8a05b8c1 | ||
|
|
34d2fc1503 | ||
|
|
9b3fa809bf | ||
|
|
59535c112e | ||
|
|
04e5a6425a | ||
|
|
424dddf67b | ||
|
|
f0d6ae2a00 | ||
|
|
25298a32fa | ||
|
|
ba28bf01b7 | ||
|
|
d15c29b1a3 | ||
|
|
b083910a51 | ||
|
|
235aad32a6 | ||
|
|
a818560344 | ||
|
|
8f179becf7 | ||
|
|
e1695a0874 | ||
|
|
af7498d283 | ||
|
|
3e2a4d8053 | ||
|
|
29982e2caf | ||
|
|
5fea1df42b | ||
|
|
a041162b32 | ||
|
|
32cd3981d8 | ||
|
|
ca5af87196 | ||
|
|
a8164f612f | ||
|
|
d3bb0b6ff0 | ||
|
|
0ef10c1e13 | ||
|
|
4017911373 | ||
|
|
048034d4b1 | ||
|
|
fcb3f08bcb | ||
|
|
d2a05bb622 | ||
|
|
f7254ee169 | ||
|
|
a0e5c9d570 | ||
|
|
8291e4ba73 | ||
|
|
b324be3b0b | ||
|
|
6ba0ba7126 | ||
|
|
1d8e0629af | ||
|
|
42df54869f | ||
|
|
7b758b85ec | ||
|
|
82987ec401 | ||
|
|
71707b5aa7 | ||
|
|
ca2df83928 | ||
|
|
085771c2f0 | ||
|
|
607a638858 | ||
|
|
5f6d06d05d | ||
|
|
19ecb87b07 | ||
|
|
2a332c0883 | ||
|
|
bb773c6c13 | ||
|
|
238de489c1 | ||
|
|
6b4db330d8 | ||
|
|
ea5d7c0dee | ||
|
|
0f189f1af3 | ||
|
|
0f1b8dd51a | ||
|
|
d7e6946a78 | ||
|
|
255b7b1a54 | ||
|
|
79e1c751a1 | ||
|
|
fc745b9614 | ||
|
|
95b1baebd2 | ||
|
|
56fe1ceb97 | ||
|
|
863a51e556 | ||
|
|
69b3064b45 | ||
|
|
fb3eab1aa8 | ||
|
|
32c7399f26 | ||
|
|
955351b5bd | ||
|
|
75f6c67b6e | ||
|
|
700a3e6ed9 | ||
|
|
00702448c7 | ||
|
|
5074827d51 | ||
|
|
ceb0711e42 | ||
|
|
ddb5824b58 | ||
|
|
39f9209374 | ||
|
|
5fea4cf760 | ||
|
|
0e5ec86ca9 | ||
|
|
8b95211055 | ||
|
|
a27339b954 | ||
|
|
028b728760 | ||
|
|
18e63df01e | ||
|
|
5f459c0901 | ||
|
|
a90bcde38c | ||
|
|
603e7d922e | ||
|
|
861126f810 | ||
|
|
eb9b706ebc | ||
|
|
de9cbae0b2 | ||
|
|
25e890986f | ||
|
|
f66627dd04 | ||
|
|
924eb33b3f | ||
|
|
1b288c541a | ||
|
|
2612b8c86f | ||
|
|
3e2796d456 | ||
|
|
7092913863 | ||
|
|
67625fc347 | ||
|
|
eb55030b06 | ||
|
|
6e1b2d50f2 | ||
|
|
c6f72c44b8 | ||
|
|
d38ded0f26 | ||
|
|
ec20b7bd3a | ||
|
|
0766cf464a | ||
|
|
867f00e091 | ||
|
|
c823b8d7ae | ||
|
|
393d4d336c | ||
|
|
2cb3f2d03d | ||
|
|
279f2dd633 | ||
|
|
dec051a6e0 | ||
|
|
790fdd320c | ||
|
|
feb4a364a7 | ||
|
|
1140149e1e | ||
|
|
2ee9599b6e | ||
|
|
188d45e002 | ||
|
|
7c4c2f7860 | ||
|
|
90b7f2ff3b | ||
|
|
d3f0041e93 | ||
|
|
9d60142828 | ||
|
|
68d5edca60 | ||
|
|
1b369489df | ||
|
|
600ddfbf2d | ||
|
|
415d4dde2a | ||
|
|
1867245ed3 | ||
|
|
71d34592d9 | ||
|
|
db2927eea7 | ||
|
|
bb01a5cb31 | ||
|
|
815319140f | ||
|
|
6e6082119f | ||
|
|
da48ffe05c | ||
|
|
081979be3b | ||
|
|
3673956c1c | ||
|
|
bdd3c274ed | ||
|
|
423034d5c4 | ||
|
|
19fd2b12c0 | ||
|
|
21cd17873f | ||
|
|
9870fa9e34 | ||
|
|
938cd5e136 | ||
|
|
e8025ad4b3 | ||
|
|
07fa141aaa | ||
|
|
18bdf1e8b3 | ||
|
|
5be977005e | ||
|
|
282b64278e | ||
|
|
7263d484de | ||
|
|
bdb059b6c9 | ||
|
|
de3f5011bc | ||
|
|
de9faffa33 | ||
|
|
f67ca69e05 | ||
|
|
dd19e880c5 | ||
|
|
b5e8fa007c | ||
|
|
c3555bfcab | ||
|
|
0383db8788 | ||
|
|
d7af122c18 | ||
|
|
e15b8145b1 | ||
|
|
d75f5f9231 | ||
|
|
9939797792 | ||
|
|
5248b9fc6f | ||
|
|
e15295bdac | ||
|
|
4e1f96e09c | ||
|
|
96cfdebced | ||
|
|
944f34b833 | ||
|
|
1023b2ca9c | ||
|
|
16318bb9f6 | ||
|
|
350586335d | ||
|
|
9d809499a5 | ||
|
|
fdd52c17d7 | ||
|
|
1461d029db | ||
|
|
07cefd71df | ||
|
|
abab10b2cc | ||
|
|
e37d4a6756 | ||
|
|
e2a1ce623c | ||
|
|
0ff243266c | ||
|
|
645da2e307 | ||
|
|
5fd95788f9 | ||
|
|
bd29f168e0 | ||
|
|
dc97e33cd6 | ||
|
|
caf7cb07cd | ||
|
|
ad5df53ee7 | ||
|
|
95920bf207 | ||
|
|
6700166841 | ||
|
|
b8196cd06e | ||
|
|
c28afbf193 | ||
|
|
84ffffb3f3 | ||
|
|
b2c030140c | ||
|
|
90138ed574 | ||
|
|
92f131bbe4 | ||
|
|
338580087e | ||
|
|
deda53a842 | ||
|
|
5391854c82 | ||
|
|
e288bfbec4 | ||
|
|
377fe5bc40 | ||
|
|
d264ff2801 | ||
|
|
a21bb6b02d | ||
|
|
37ecd5cdef | ||
|
|
07a87dfba7 | ||
|
|
9e4db89521 | ||
|
|
536d394e41 | ||
|
|
c0580c7ad0 | ||
|
|
488e72ef4e | ||
|
|
01c224d301 | ||
|
|
eaf95a85a8 | ||
|
|
ba1d084660 | ||
|
|
2e64c461c3 | ||
|
|
ce5dad722f | ||
|
|
7675feca91 | ||
|
|
c66d74e135 | ||
|
|
54d6eed740 | ||
|
|
dc4b75070d | ||
|
|
830eb74725 | ||
|
|
4f21d8d7a8 | ||
|
|
424deb8faf | ||
|
|
b4a40f1257 | ||
|
|
9296c10ca4 | ||
|
|
fbe65cd542 | ||
|
|
ccbb6e4789 | ||
|
|
d70f436304 | ||
|
|
16aaa8201c | ||
|
|
acc1f2f3d7 | ||
|
|
433d254c70 | ||
|
|
ea4eebd2d6 | ||
|
|
3c00a527dd | ||
|
|
f72a354066 | ||
|
|
7c92e0e9ce | ||
|
|
4f6868728d | ||
|
|
0ec4522f9e | ||
|
|
c6e0c6d096 | ||
|
|
dc0fb9ed8a | ||
|
|
66d9eaee78 | ||
|
|
3797272faf | ||
|
|
682b302d04 | ||
|
|
1de10f9b05 | ||
|
|
c4391ff058 | ||
|
|
3822e3f8d9 | ||
|
|
f8f99f3878 | ||
|
|
e77e4acea9 | ||
|
|
c6de444d0b | ||
|
|
89e38c34b8 | ||
|
|
246d17972c | ||
|
|
55a8b37ef8 | ||
|
|
445183001b | ||
|
|
ca9e2200da | ||
|
|
eba3f84c04 | ||
|
|
867e6a8f4b | ||
|
|
df9779ec59 | ||
|
|
1b71d1e46d | ||
|
|
0a58918f47 | ||
|
|
afbd927fc0 | ||
|
|
2aa09ae18d | ||
|
|
09789b0b72 | ||
|
|
2426abd17a | ||
|
|
db4a97743f | ||
|
|
7ca98ed344 | ||
|
|
c9d3d17999 | ||
|
|
628049cfd7 | ||
|
|
ae9a11da53 | ||
|
|
7e097482bc | ||
|
|
df1b151587 | ||
|
|
45eb59a5aa | ||
|
|
687c17bbe2 | ||
|
|
7505aec706 | ||
|
|
c7b414492d | ||
|
|
14b0095822 | ||
|
|
a1256b46c8 | ||
|
|
094270dff7 | ||
|
|
d4e24dabc2 | ||
|
|
842df0d112 | ||
|
|
cfa9427d7c | ||
|
|
3c01e24f02 | ||
|
|
22dbf63ff9 | ||
|
|
814f7394a0 | ||
|
|
9a4cebaa1b | ||
|
|
c30207ac63 | ||
|
|
77afbddb91 | ||
|
|
18feeabe15 | ||
|
|
c3811d3a14 | ||
|
|
f20d6b551d | ||
|
|
311bcadacb | ||
|
|
2189c8cd82 | ||
|
|
6553bb8147 | ||
|
|
dea492fd64 | ||
|
|
00ab7f04fa | ||
|
|
d3ba714aba | ||
|
|
748b37f1d6 | ||
|
|
b83b188aff | ||
|
|
cfefa32603 | ||
|
|
85d8db3ef9 | ||
|
|
3c14dbe382 | ||
|
|
b49b2af11f | ||
|
|
425a36aa51 | ||
|
|
ec0b9de713 | ||
|
|
9f13b14f6d | ||
|
|
01e83b45b5 | ||
|
|
f80566e0cb | ||
|
|
42afacf0af | ||
|
|
2e61e7e682 | ||
|
|
3de9267ea7 | ||
|
|
8c99d4fcd2 | ||
|
|
be4e6e5ba5 | ||
|
|
1b5efea6eb | ||
|
|
6554f80fad | ||
|
|
2e8a9f809e | ||
|
|
dc66032720 | ||
|
|
c9433782d8 | ||
|
|
fef5586ff5 | ||
|
|
1f4a2fd654 | ||
|
|
8243385af6 | ||
|
|
26ce9b2d4a | ||
|
|
119f3169e2 | ||
|
|
16bd22ee01 | ||
|
|
f4a5f73ab2 | ||
|
|
e61a4564ea | ||
|
|
e72edee1f2 | ||
|
|
e8c150fcac | ||
|
|
52418932b1 | ||
|
|
4f81cb9333 | ||
|
|
db46f47b96 | ||
|
|
edfe5594ba | ||
|
|
f25e972594 | ||
|
|
d5488bdd42 | ||
|
|
bbff64bc96 | ||
|
|
635afefdeb | ||
|
|
fd3e67a0b4 | ||
|
|
729a6021ee | ||
|
|
309f254c2c | ||
|
|
5c37f04d64 | ||
|
|
7c3dd8e852 | ||
|
|
66ddedbaf3 | ||
|
|
7981b17897 | ||
|
|
62137d47c8 | ||
|
|
e3b5437f61 | ||
|
|
934693924e | ||
|
|
308fd92a46 | ||
|
|
da1eb71ad0 | ||
|
|
576dbb7ce6 | ||
|
|
d0c381b3df | ||
|
|
55178a81c6 | ||
|
|
249308380b | ||
|
|
d91bec08c3 | ||
|
|
e23ef4b0be | ||
|
|
6037521c49 | ||
|
|
a27fac3677 | ||
|
|
21f2eb664e | ||
|
|
81546ef4b0 | ||
|
|
4b90c8fd45 | ||
|
|
c643fb8aac | ||
|
|
0cae6ceca3 | ||
|
|
5cde59b53c | ||
|
|
7df67630af | ||
|
|
0c89dca261 | ||
|
|
6b953b8793 | ||
|
|
0d1defcf27 | ||
|
|
c1db9c19b3 | ||
|
|
95487755ed | ||
|
|
4813469659 | ||
|
|
4dfd357c0b | ||
|
|
4ca0486518 | ||
|
|
b139c05960 | ||
|
|
3d32759030 | ||
|
|
badfe39a3d | ||
|
|
060e2db351 | ||
|
|
ed802c0404 | ||
|
|
5d8739bfb2 | ||
|
|
086faf44fc | ||
|
|
e5eaa90c61 | ||
|
|
b24807ea29 | ||
|
|
d68bae9bc2 | ||
|
|
b891fb4502 | ||
|
|
ea69b3b4e3 | ||
|
|
23c8616ba5 | ||
|
|
b25c91affd | ||
|
|
151cefe0ec | ||
|
|
3412ff94bc | ||
|
|
77aa2241dc | ||
|
|
0766d08479 | ||
|
|
14112ed294 | ||
|
|
f6ed0d43a2 | ||
|
|
c8413cb029 | ||
|
|
97d53b81a7 | ||
|
|
ab888f5cd0 | ||
|
|
f54246eac1 | ||
|
|
7de9422b75 | ||
|
|
f02a37d3f0 | ||
|
|
28815a0ae6 | ||
|
|
70c7dfd0f4 | ||
|
|
9c2ebd308b | ||
|
|
11d8412591 | ||
|
|
32ca170c4d | ||
|
|
388ed08b0e | ||
|
|
3e1909b645 | ||
|
|
b408f88b8c | ||
|
|
09087401b4 | ||
|
|
c68692d78e | ||
|
|
ee2a4d0a5d | ||
|
|
a15885fe80 | ||
|
|
24111570cf | ||
|
|
ded203b1c1 | ||
|
|
e43fc98c0d | ||
|
|
1efd13545e | ||
|
|
1193ee1ab9 | ||
|
|
a6ba801738 | ||
|
|
e7958f2910 | ||
|
|
cbac9a7703 | ||
|
|
60d8f2323e | ||
|
|
70ae6b8d72 | ||
|
|
a4b1fbd6ee | ||
|
|
e1850440b0 | ||
|
|
d5c2aaeea3 | ||
|
|
a06b7acc85 | ||
|
|
615168423a | ||
|
|
73abf7d20e | ||
|
|
fcea42e91e | ||
|
|
14f7574c41 | ||
|
|
8f15ded650 | ||
|
|
4aec4ef80a | ||
|
|
ecb8f1de30 | ||
|
|
4c28180125 | ||
|
|
4138180f43 | ||
|
|
0d508a88f6 | ||
|
|
7c8fcf73f6 | ||
|
|
5904d72776 | ||
|
|
5e32ccbf12 | ||
|
|
6ce136bede | ||
|
|
b9f8ce5729 | ||
|
|
115530a104 | ||
|
|
65c9b2a5f7 | ||
|
|
46c73a05a9 | ||
|
|
c5f7e72ca8 | ||
|
|
e6fb63ddba | ||
|
|
e2645e4126 | ||
|
|
36d267ca40 | ||
|
|
2e5d04389b | ||
|
|
6130ed17a6 | ||
|
|
c4e82407ec | ||
|
|
2e28e68c48 | ||
|
|
a7882fa32b | ||
|
|
82f9e70406 | ||
|
|
3fa27c7ffa | ||
|
|
1aa50dee20 | ||
|
|
f58f7257be | ||
|
|
e17f1269a2 | ||
|
|
82f48b84b3 | ||
|
|
926bd20281 | ||
|
|
a6cd019118 | ||
|
|
bbfc476d7e | ||
|
|
8d49515a3c | ||
|
|
0a410a5544 | ||
|
|
eef203633b | ||
|
|
122255058e | ||
|
|
b1681b2213 | ||
|
|
73d79f55d8 | ||
|
|
a02fcd97d6 | ||
|
|
016708b338 | ||
|
|
9f26fc28c4 | ||
|
|
7c1b354fc3 | ||
|
|
abeda1935d | ||
|
|
403ee9ff9e | ||
|
|
cccb45fe13 | ||
|
|
8d43becb27 | ||
|
|
ee22e07fff | ||
|
|
37464e2d95 | ||
|
|
5abcecbc9b | ||
|
|
cecdf0d511 | ||
|
|
a451fe4248 | ||
|
|
d6f801f764 | ||
|
|
a35e772a6b | ||
|
|
aca3fae6b1 | ||
|
|
17891f0209 | ||
|
|
aea2b3c8e5 | ||
|
|
6d2ef9be5d | ||
|
|
57fb167a9c | ||
|
|
0406bba384 | ||
|
|
7c4c80fe4a | ||
|
|
bfb267e164 | ||
|
|
a0720948a1 | ||
|
|
9f00159a84 | ||
|
|
34067a1d70 | ||
|
|
3f6917fdcb | ||
|
|
c04a6e501e | ||
|
|
661b564399 | ||
|
|
761c103373 | ||
|
|
f4bd9e3d24 | ||
|
|
b9ddac878c | ||
|
|
f304ce5ccf | ||
|
|
828401f057 | ||
|
|
445d77a220 | ||
|
|
4d768bb5eb | ||
|
|
4e3b87d338 | ||
|
|
00740b6117 | ||
|
|
7775f203fc | ||
|
|
945af879ec | ||
|
|
b2506f0afe | ||
|
|
2eab4b84c9 | ||
|
|
7746d9968d | ||
|
|
da49d918d6 | ||
|
|
804ed758c9 | ||
|
|
17aac58e08 | ||
|
|
a7095d7dec | ||
|
|
3afbb6fcc2 | ||
|
|
8ecbd8e71c | ||
|
|
988f499723 | ||
|
|
50aeb9ff21 | ||
|
|
e620c28a1c | ||
|
|
29ee7d41f5 | ||
|
|
f9104c71f6 | ||
|
|
b6af5884b1 | ||
|
|
e4f250435d | ||
|
|
1a246f2e38 | ||
|
|
48ebc46c5f | ||
|
|
e27803038c | ||
|
|
babf8ba3e7 | ||
|
|
6ccd3f277b | ||
|
|
9d6f9aae9a | ||
|
|
95a000c279 | ||
|
|
b19debff14 | ||
|
|
39c9024747 | ||
|
|
3c660f2cb0 | ||
|
|
13dbdc7dc7 | ||
|
|
f903e4b2de | ||
|
|
b96cb2142b | ||
|
|
cc51cd4476 | ||
|
|
8a995fc515 | ||
|
|
078eccea2d | ||
|
|
190119bcd4 | ||
|
|
7672b42fbc | ||
|
|
c590658f16 | ||
|
|
017d4e792b | ||
|
|
0671be870d | ||
|
|
2f9ed37db2 | ||
|
|
2cf2db3eef | ||
|
|
11ad025e5d | ||
|
|
630cf05b2f | ||
|
|
a72782f91e | ||
|
|
fbd554a15f | ||
|
|
f71aa1cad2 | ||
|
|
6d9517f6ea | ||
|
|
fd8c488dbd | ||
|
|
dbf18b90a7 | ||
|
|
d318fe24b8 | ||
|
|
1352315441 | ||
|
|
3c635532c4 | ||
|
|
f8703bf884 | ||
|
|
eea3aa7a27 | ||
|
|
6eff448508 | ||
|
|
eb8cac5980 | ||
|
|
1a4086c98c | ||
|
|
5c91076660 | ||
|
|
5467b8dd0d | ||
|
|
d46a9d6286 | ||
|
|
2fa7810128 | ||
|
|
8249725ae7 | ||
|
|
c07b83335b | ||
|
|
7e575c501a | ||
|
|
933e2fb0ef | ||
|
|
8d51383fb2 | ||
|
|
80f4c83b83 | ||
|
|
0d739e4af7 | ||
|
|
58f9027002 | ||
|
|
990f2e2892 | ||
|
|
ce7989c171 | ||
|
|
4efb0229d4 | ||
|
|
5dd6dc2d69 | ||
|
|
20931eb9d6 | ||
|
|
c11fa122af | ||
|
|
e9141c8300 | ||
|
|
1d03b688d9 | ||
|
|
176d42f625 | ||
|
|
7c98a27c53 | ||
|
|
020b30783e | ||
|
|
fafbdb0714 | ||
|
|
466cdb4ee7 | ||
|
|
fa66f0b509 | ||
|
|
12a566c07e | ||
|
|
bf7a1c6b1f | ||
|
|
55891aa5f8 | ||
|
|
7c0acd9fcb | ||
|
|
333f1e2c47 | ||
|
|
9d30cdfefc | ||
|
|
324f6fe16e | ||
|
|
5d96304332 | ||
|
|
e6e32b5fd2 | ||
|
|
181f265de5 | ||
|
|
e5fc8bb27c | ||
|
|
34dda780d9 | ||
|
|
c7cf4eeb7a | ||
|
|
a6e5d9f6dc | ||
|
|
ea1017584e | ||
|
|
6aef32d7a8 | ||
|
|
4a1d71b6b8 | ||
|
|
a18b61cb1d | ||
|
|
e31e19aeba | ||
|
|
ef6d8a6554 | ||
|
|
100764d79e | ||
|
|
75abe7da1b | ||
|
|
a19a125aec | ||
|
|
c84106570f | ||
|
|
1a05da9e55 | ||
|
|
8e8ffd21d5 |
12
.github/actions/install/action.yml
vendored
12
.github/actions/install/action.yml
vendored
@@ -13,7 +13,7 @@ inputs:
|
||||
zig-v8:
|
||||
description: 'zig v8 version to install'
|
||||
required: false
|
||||
default: 'v0.2.6'
|
||||
default: 'v0.3.1'
|
||||
v8:
|
||||
description: 'v8 version to install'
|
||||
required: false
|
||||
@@ -22,6 +22,10 @@ inputs:
|
||||
description: 'cache dir to use'
|
||||
required: false
|
||||
default: '~/.cache'
|
||||
debug:
|
||||
description: 'enable v8 pre-built debug version, only available for linux x86_64'
|
||||
required: false
|
||||
default: 'false'
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
@@ -47,17 +51,17 @@ runs:
|
||||
cache-name: cache-v8
|
||||
with:
|
||||
path: ${{ inputs.cache-dir }}/v8
|
||||
key: libc_v8_${{ inputs.v8 }}_${{ inputs.os }}_${{ inputs.arch }}_${{ inputs.zig-v8 }}.a
|
||||
key: libc_v8_${{ inputs.v8 }}_${{ inputs.os }}_${{ inputs.arch }}_${{ inputs.zig-v8 }}${{inputs.debug == 'true' && '_debug' || '' }}.a
|
||||
|
||||
- if: ${{ steps.cache-v8.outputs.cache-hit != 'true' }}
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p ${{ inputs.cache-dir }}/v8
|
||||
|
||||
wget -O ${{ inputs.cache-dir }}/v8/libc_v8.a https://github.com/lightpanda-io/zig-v8-fork/releases/download/${{ inputs.zig-v8 }}/libc_v8_${{ inputs.v8 }}_${{ inputs.os }}_${{ inputs.arch }}.a
|
||||
wget -O ${{ inputs.cache-dir }}/v8/libc_v8.a https://github.com/lightpanda-io/zig-v8-fork/releases/download/${{ inputs.zig-v8 }}/libc_v8_${{ inputs.v8 }}_${{ inputs.os }}_${{ inputs.arch }}${{inputs.debug == 'true' && '_debug' || '' }}.a
|
||||
|
||||
- name: install v8
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p v8
|
||||
ln -s ${{ inputs.cache-dir }}/v8/libc_v8.a v8/libc_v8.a
|
||||
ln -s ${{ inputs.cache-dir }}/v8/libc_v8.a v8/libc_v8${{inputs.debug == 'true' && '_debug' || '' }}.a
|
||||
|
||||
4
.github/workflows/build.yml
vendored
4
.github/workflows/build.yml
vendored
@@ -40,7 +40,6 @@ 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
|
||||
@@ -83,7 +82,6 @@ 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
|
||||
@@ -128,7 +126,6 @@ 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
|
||||
@@ -171,7 +168,6 @@ 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
|
||||
|
||||
2
.github/workflows/e2e-integration-test.yml
vendored
2
.github/workflows/e2e-integration-test.yml
vendored
@@ -63,6 +63,6 @@ jobs:
|
||||
|
||||
- name: run end to end integration tests
|
||||
run: |
|
||||
./lightpanda serve & echo $! > LPD.pid
|
||||
./lightpanda serve --log_level error & echo $! > LPD.pid
|
||||
go run integration/main.go
|
||||
kill `cat LPD.pid`
|
||||
|
||||
55
.github/workflows/e2e-test.yml
vendored
55
.github/workflows/e2e-test.yml
vendored
@@ -56,8 +56,6 @@ jobs:
|
||||
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 }})
|
||||
@@ -124,10 +122,19 @@ jobs:
|
||||
needs: zig-build-release
|
||||
|
||||
env:
|
||||
MAX_MEMORY: 26000
|
||||
MAX_VmHWM: 28000 # 28MB (KB)
|
||||
MAX_CG_PEAK: 8000 # 8MB (KB)
|
||||
MAX_AVG_DURATION: 17
|
||||
LIGHTPANDA_DISABLE_TELEMETRY: true
|
||||
|
||||
# How to give cgroups access to the user actions-runner on the host:
|
||||
# $ sudo apt install cgroup-tools
|
||||
# $ sudo chmod o+w /sys/fs/cgroup/cgroup.procs
|
||||
# $ sudo mkdir -p /sys/fs/cgroup/actions-runner
|
||||
# $ sudo chown -R actions-runner:actions-runner /sys/fs/cgroup/actions-runner
|
||||
CG_ROOT: /sys/fs/cgroup
|
||||
CG: actions-runner/lpd_${{ github.run_id }}_${{ github.run_attempt }}
|
||||
|
||||
# use a self host runner.
|
||||
runs-on: lpd-bench-hetzner
|
||||
timeout-minutes: 15
|
||||
@@ -152,22 +159,53 @@ jobs:
|
||||
go run ws/main.go & echo $! > WS.pid
|
||||
sleep 2
|
||||
|
||||
- name: run lightpanda in cgroup
|
||||
run: |
|
||||
if [ ! -f /sys/fs/cgroup/cgroup.controllers ]; then
|
||||
echo "cgroup v2 not available: /sys/fs/cgroup/cgroup.controllers missing"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p $CG_ROOT/$CG
|
||||
cgexec -g memory:$CG ./lightpanda serve & echo $! > LPD.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`
|
||||
|
||||
PID=$(cat LPD.pid)
|
||||
while kill -0 $PID 2>/dev/null; do
|
||||
sleep 1
|
||||
done
|
||||
if [ ! -f $CG_ROOT/$CG/memory.peak ]; then
|
||||
echo "memory.peak not available in $CG"
|
||||
exit 1
|
||||
fi
|
||||
cat $CG_ROOT/$CG/memory.peak > LPD.cg_mem_peak
|
||||
|
||||
- name: puppeteer result
|
||||
run: cat puppeteer.out
|
||||
|
||||
- name: memory regression
|
||||
- name: cgroup memory regression
|
||||
run: |
|
||||
PEAK_BYTES=$(cat LPD.cg_mem_peak)
|
||||
PEAK_KB=$((PEAK_BYTES / 1024))
|
||||
echo "memory.peak_bytes=$PEAK_BYTES"
|
||||
echo "memory.peak_kb=$PEAK_KB"
|
||||
test "$PEAK_KB" -le "$MAX_CG_PEAK"
|
||||
|
||||
- name: virtual memory regression
|
||||
run: |
|
||||
export LPD_VmHWM=`cat LPD.VmHWM`
|
||||
echo "Peak resident set size: $LPD_VmHWM"
|
||||
test "$LPD_VmHWM" -le "$MAX_MEMORY"
|
||||
test "$LPD_VmHWM" -le "$MAX_VmHWM"
|
||||
|
||||
- name: cleanup cgroup
|
||||
run: rmdir $CG_ROOT/$CG
|
||||
|
||||
- name: duration regression
|
||||
run: |
|
||||
@@ -180,7 +218,8 @@ jobs:
|
||||
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
|
||||
export LPD_CG_PEAK_KB=$(( $(cat LPD.cg_mem_peak) / 1024 ))
|
||||
echo "{\"duration_total\":${TOTAL_DURATION},\"duration_avg\":${AVG_DURATION},\"mem_peak\":${LPD_VmHWM},\"cg_mem_peak\":${LPD_CG_PEAK_KB}}" > bench.json
|
||||
cat bench.json
|
||||
|
||||
- name: run hyperfine
|
||||
|
||||
88
.github/workflows/wpt.yml
vendored
88
.github/workflows/wpt.yml
vendored
@@ -15,11 +15,11 @@ on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
wpt:
|
||||
name: web platform tests json output
|
||||
wpt-build-release:
|
||||
name: zig build release
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
@@ -30,11 +30,85 @@ jobs:
|
||||
|
||||
- uses: ./.github/actions/install
|
||||
|
||||
- name: build wpt
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -- version
|
||||
- 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
|
||||
|
||||
wpt-build-runner:
|
||||
name: build wpt runner
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
repository: 'lightpanda-io/demo'
|
||||
fetch-depth: 0
|
||||
|
||||
- run: |
|
||||
cd ./wptrunner
|
||||
CGO_ENABLED=0 go build
|
||||
|
||||
- name: upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: wptrunner
|
||||
path: |
|
||||
wptrunner/wptrunner
|
||||
retention-days: 1
|
||||
|
||||
run-wpt:
|
||||
name: web platform tests json output
|
||||
needs:
|
||||
- wpt-build-release
|
||||
- wpt-build-runner
|
||||
|
||||
# use a self host runner.
|
||||
runs-on: lpd-bench-hetzner
|
||||
timeout-minutes: 120
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: fork
|
||||
repository: 'lightpanda-io/wpt'
|
||||
fetch-depth: 0
|
||||
|
||||
# The hosts are configured manually on the self host runner.
|
||||
# - name: create custom hosts
|
||||
# run: ./wpt make-hosts-file | sudo tee -a /etc/hosts
|
||||
|
||||
- name: generate manifest
|
||||
run: ./wpt manifest
|
||||
|
||||
- name: download lightpanda release
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: lightpanda-build-release
|
||||
|
||||
- run: chmod a+x ./lightpanda
|
||||
|
||||
- name: download wptrunner
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: wptrunner
|
||||
|
||||
- run: chmod a+x ./wptrunner
|
||||
|
||||
- name: run test with json output
|
||||
run: zig-out/bin/lightpanda-wpt --json > wpt.json
|
||||
run: |
|
||||
./wpt serve 2> /dev/null & echo $! > WPT.pid
|
||||
sleep 10s
|
||||
./wptrunner -lpd-path ./lightpanda -json -concurrency 3 > wpt.json
|
||||
kill `cat WPT.pid`
|
||||
|
||||
- name: write commit
|
||||
run: |
|
||||
@@ -51,7 +125,7 @@ jobs:
|
||||
|
||||
perf-fmt:
|
||||
name: perf-fmt
|
||||
needs: wpt
|
||||
needs: run-wpt
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
23
.github/workflows/zig-test.yml
vendored
23
.github/workflows/zig-test.yml
vendored
@@ -12,8 +12,7 @@ on:
|
||||
- main
|
||||
paths:
|
||||
- "build.zig"
|
||||
- "src/**/*.zig"
|
||||
- "src/*.zig"
|
||||
- "src/**"
|
||||
- "vendor/zig-js-runtime"
|
||||
- ".github/**"
|
||||
- "vendor/**"
|
||||
@@ -38,6 +37,26 @@ on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
zig-test-debug:
|
||||
name: zig test using v8 in debug mode
|
||||
timeout-minutes: 15
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
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:
|
||||
debug: true
|
||||
|
||||
- name: zig build test
|
||||
run: zig build -Dprebuilt_v8_path=v8/libc_v8_debug.a -Dtsan=true test
|
||||
|
||||
zig-test:
|
||||
name: zig test
|
||||
timeout-minutes: 15
|
||||
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -1,11 +1,6 @@
|
||||
zig-cache
|
||||
/.zig-cache/
|
||||
/.lp-cache/
|
||||
zig-out
|
||||
/vendor/netsurf/out
|
||||
/vendor/libiconv/
|
||||
lightpanda.id
|
||||
/v8/
|
||||
/build/
|
||||
/src/html5ever/target/
|
||||
src/snapshot.bin
|
||||
|
||||
15
.gitmodules
vendored
15
.gitmodules
vendored
@@ -1,15 +0,0 @@
|
||||
[submodule "tests/wpt"]
|
||||
path = tests/wpt
|
||||
url = https://github.com/lightpanda-io/wpt
|
||||
[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
|
||||
@@ -3,7 +3,7 @@ FROM debian:stable-slim
|
||||
ARG MINISIG=0.12
|
||||
ARG ZIG_MINISIG=RWSGOq2NVecA2UPNdBUZykf1CCb147pkmdtYxgb3Ti+JO/wCYvhbAb/U
|
||||
ARG V8=14.0.365.4
|
||||
ARG ZIG_V8=v0.2.6
|
||||
ARG ZIG_V8=v0.3.1
|
||||
ARG TARGETPLATFORM
|
||||
|
||||
RUN apt-get update -yq && \
|
||||
|
||||
20
Makefile
20
Makefile
@@ -47,7 +47,7 @@ help:
|
||||
|
||||
# $(ZIG) commands
|
||||
# ------------
|
||||
.PHONY: build build-v8-snapshot build-dev run run-release shell test bench wpt data end2end
|
||||
.PHONY: build build-v8-snapshot build-dev run run-release shell test bench data end2end
|
||||
|
||||
## Build v8 snapshot
|
||||
build-v8-snapshot:
|
||||
@@ -57,7 +57,7 @@ build-v8-snapshot:
|
||||
|
||||
## Build in release-fast mode
|
||||
build: build-v8-snapshot
|
||||
@printf "\033[36mBuilding (release safe)...\033[0m\n"
|
||||
@printf "\033[36mBuilding (release fast)...\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"
|
||||
|
||||
@@ -82,15 +82,6 @@ shell:
|
||||
@printf "\033[36mBuilding shell...\033[0m\n"
|
||||
@$(ZIG) build shell || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
|
||||
## Run WPT tests
|
||||
wpt:
|
||||
@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 "\033[36mBuilding wpt...\033[0m\n"
|
||||
@$(ZIG) build wpt -- --summary $(filter-out $@,$(MAKECMDGOALS)) || (printf "\033[33mBuild ERROR\033[0m\n"; exit 1;)
|
||||
|
||||
## Test - `grep` is used to filter out the huge compile command on build
|
||||
ifeq ($(OS), macos)
|
||||
test:
|
||||
@@ -111,13 +102,8 @@ end2end:
|
||||
# ------------
|
||||
.PHONY: install
|
||||
|
||||
## Install and build dependencies for release
|
||||
install: install-submodule
|
||||
install: build
|
||||
|
||||
data:
|
||||
cd src/data && go run public_suffix_list_gen.go > public_suffix_list.zig
|
||||
|
||||
## Init and update git submodule
|
||||
install-submodule:
|
||||
@git submodule init && \
|
||||
git submodule update
|
||||
|
||||
119
README.md
119
README.md
@@ -78,23 +78,49 @@ docker run -d --name lightpanda -p 9222:9222 lightpanda/browser:nightly
|
||||
### Dump a URL
|
||||
|
||||
```console
|
||||
./lightpanda fetch --dump https://lightpanda.io
|
||||
./lightpanda fetch --obey_robots --log_format pretty --log_level info https://demo-browser.lightpanda.io/campfire-commerce/
|
||||
```
|
||||
```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')
|
||||
INFO telemetry : telemetry status . . . . . . . . . . . . . [+0ms]
|
||||
disabled = false
|
||||
|
||||
INFO page : navigate . . . . . . . . . . . . . . . . . . . . [+6ms]
|
||||
url = https://demo-browser.lightpanda.io/campfire-commerce/
|
||||
method = GET
|
||||
reason = address_bar
|
||||
body = false
|
||||
req_id = 1
|
||||
|
||||
INFO browser : executing script . . . . . . . . . . . . . . [+118ms]
|
||||
src = https://demo-browser.lightpanda.io/campfire-commerce/script.js
|
||||
kind = javascript
|
||||
cacheable = true
|
||||
|
||||
INFO http : request complete . . . . . . . . . . . . . . . . [+140ms]
|
||||
source = xhr
|
||||
url = https://demo-browser.lightpanda.io/campfire-commerce/json/product.json
|
||||
status = 200
|
||||
len = 4770
|
||||
|
||||
INFO http : request complete . . . . . . . . . . . . . . . . [+141ms]
|
||||
source = fetch
|
||||
url = https://demo-browser.lightpanda.io/campfire-commerce/json/reviews.json
|
||||
status = 200
|
||||
len = 1615
|
||||
<!DOCTYPE html>
|
||||
```
|
||||
|
||||
### Start a CDP server
|
||||
|
||||
```console
|
||||
./lightpanda serve --host 127.0.0.1 --port 9222
|
||||
./lightpanda serve --obey_robots --log_format pretty --log_level info --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...
|
||||
INFO telemetry : telemetry status . . . . . . . . . . . . . [+0ms]
|
||||
disabled = false
|
||||
|
||||
INFO app : server running . . . . . . . . . . . . . . . . . [+0ms]
|
||||
address = 127.0.0.1:9222
|
||||
```
|
||||
|
||||
Once the CDP server started, you can run a Puppeteer script by configuring the
|
||||
@@ -115,7 +141,7 @@ const context = await browser.createBrowserContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
// Dump all the links from the page.
|
||||
await page.goto('https://wikipedia.com/');
|
||||
await page.goto('https://demo-browser.lightpanda.io/amiibo/', {waitUntil: "networkidle0"});
|
||||
|
||||
const links = await page.evaluate(() => {
|
||||
return Array.from(document.querySelectorAll('a')).map(row => {
|
||||
@@ -156,6 +182,7 @@ Here are the key features we have implemented:
|
||||
- [x] Custom HTTP headers
|
||||
- [x] Proxy support
|
||||
- [x] Network interception
|
||||
- [x] Respect `robots.txt` with option `--obey_robots`
|
||||
|
||||
NOTE: There are hundreds of Web APIs. Developing a browser (even just for headless mode) is a huge task. Coverage will increase over time.
|
||||
|
||||
@@ -193,18 +220,6 @@ For **MacOS**, you need cmake and [Rust](https://rust-lang.org/tools/install/).
|
||||
brew install cmake
|
||||
```
|
||||
|
||||
### Install Git submodules
|
||||
|
||||
The project uses git submodules for dependencies.
|
||||
|
||||
To init or update the submodules in the `vendor/` directory:
|
||||
|
||||
```
|
||||
make install-submodule
|
||||
```
|
||||
|
||||
This is an alias for `git submodule init && git submodule update`.
|
||||
|
||||
### Build and run
|
||||
|
||||
You an build the entire browser with `make build` or `make build-dev` for debug
|
||||
@@ -254,35 +269,75 @@ make end2end
|
||||
Lightpanda is tested against the standardized [Web Platform
|
||||
Tests](https://web-platform-tests.org/).
|
||||
|
||||
The relevant tests cases are committed in a [dedicated repository](https://github.com/lightpanda-io/wpt) which is fetched by the `make install-submodule` command.
|
||||
|
||||
All the tests cases executed are located in the `tests/wpt` sub-directory.
|
||||
We use [a fork](https://github.com/lightpanda-io/wpt/tree/fork) including a custom
|
||||
[`testharnessreport.js`](https://github.com/lightpanda-io/wpt/commit/01a3115c076a3ad0c84849dbbf77a6e3d199c56f).
|
||||
|
||||
For reference, you can easily execute a WPT test case with your browser via
|
||||
[wpt.live](https://wpt.live).
|
||||
|
||||
#### Configure WPT HTTP server
|
||||
|
||||
To run the test, you must clone the repository, configure the custom hosts and generate the
|
||||
`MANIFEST.json` file.
|
||||
|
||||
Clone the repository with the `fork` branch.
|
||||
```
|
||||
git clone -b fork --depth=1 git@github.com:lightpanda-io/wpt.git
|
||||
```
|
||||
|
||||
Enter into the `wpt/` dir.
|
||||
|
||||
Install custom domains in your `/etc/hosts`
|
||||
```
|
||||
./wpt make-hosts-file | sudo tee -a /etc/hosts
|
||||
```
|
||||
|
||||
Generate `MANIFEST.json`
|
||||
```
|
||||
./wpt manifest
|
||||
```
|
||||
Use the [WPT's setup
|
||||
guide](https://web-platform-tests.org/running-tests/from-local-system.html) for
|
||||
details.
|
||||
|
||||
#### Run WPT test suite
|
||||
|
||||
To run all the tests:
|
||||
An external [Go](https://go.dev) runner is provided by
|
||||
[github.com/lightpanda-io/demo/](https://github.com/lightpanda-io/demo/)
|
||||
repository, located into `wptrunner/` dir.
|
||||
You need to clone the project first.
|
||||
|
||||
First start the WPT's HTTP server from your `wpt/` clone dir.
|
||||
```
|
||||
./wpt serve
|
||||
```
|
||||
|
||||
Run a Lightpanda browser
|
||||
|
||||
```
|
||||
make wpt
|
||||
zig build run -- --insecure_disable_tls_host_verification
|
||||
```
|
||||
|
||||
Then you can start the wptrunner from the Demo's clone dir:
|
||||
```
|
||||
cd wptrunner && go run .
|
||||
```
|
||||
|
||||
Or one specific test:
|
||||
|
||||
```
|
||||
make wpt Node-childNodes.html
|
||||
cd wptrunner && go run . Node-childNodes.html
|
||||
```
|
||||
|
||||
#### Add a new WPT test case
|
||||
`wptrunner` command accepts `--summary` and `--json` options modifying output.
|
||||
Also `--concurrency` define the concurrency limit.
|
||||
|
||||
We add new relevant tests cases files when we implemented changes in Lightpanda.
|
||||
:warning: Running the whole test suite will take a long time. In this case,
|
||||
it's useful to build in `releaseFast` mode to make tests faster.
|
||||
|
||||
To add a new test, copy the file you want from the [WPT
|
||||
repo](https://github.com/web-platform-tests/wpt) into the `tests/wpt` directory.
|
||||
|
||||
:warning: Please keep the original directory tree structure of `tests/wpt`.
|
||||
```
|
||||
zig build -Doptimize=ReleaseFast run
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
|
||||
@@ -1,18 +1,36 @@
|
||||
.{
|
||||
.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/v0.2.6.tar.gz",
|
||||
.hash = "v8-0.0.0-xddH60NRBAAWmpZq9nWdfFAEqVJ9zqJnvr1Nl9m2AbcY",
|
||||
.url = "https://github.com/lightpanda-io/zig-v8-fork/archive/refs/tags/v0.3.1.tar.gz",
|
||||
.hash = "v8-0.0.0-xddH64J7BAC81mkf6G9RbEJxS-W3TIRl5iFnShwbqCqy",
|
||||
|
||||
},
|
||||
//.v8 = .{ .path = "../zig-v8-fork" },
|
||||
.brotli = .{
|
||||
// v1.2.0
|
||||
.url = "https://github.com/google/brotli/archive/028fb5a23661f123017c060daa546b55cf4bde29.tar.gz",
|
||||
.hash = "N-V-__8AAJudKgCQCuIiH6MJjAiIJHfg_tT_Ew-0vZwVkCo_",
|
||||
},
|
||||
.zlib = .{
|
||||
.url = "https://github.com/madler/zlib/releases/download/v1.3.2/zlib-1.3.2.tar.gz",
|
||||
.hash = "N-V-__8AAJ2cNgAgfBtAw33Bxfu1IWISDeKKSr3DAqoAysIJ",
|
||||
},
|
||||
.nghttp2 = .{
|
||||
.url = "https://github.com/nghttp2/nghttp2/releases/download/v1.68.0/nghttp2-1.68.0.tar.gz",
|
||||
.hash = "N-V-__8AAL15vQCI63ZL6Zaz5hJg6JTEgYXGbLnMFSnf7FT3",
|
||||
},
|
||||
.@"boringssl-zig" = .{
|
||||
.url = "git+https://github.com/Syndica/boringssl-zig.git#c53df00d06b02b755ad88bbf4d1202ed9687b096",
|
||||
.hash = "boringssl-0.1.0-VtJeWehMAAA4RNnwRnzEvKcS9rjsR1QVRw1uJrwXxmVK",
|
||||
},
|
||||
.curl = .{
|
||||
.url = "https://github.com/curl/curl/releases/download/curl-8_18_0/curl-8.18.0.tar.gz",
|
||||
.hash = "N-V-__8AALp9QAGn6CCHZ6fK_FfMyGtG824LSHYHHasM3w-y",
|
||||
},
|
||||
},
|
||||
.paths = .{""},
|
||||
}
|
||||
|
||||
24
flake.lock
generated
24
flake.lock
generated
@@ -8,11 +8,11 @@
|
||||
"rust-analyzer-src": "rust-analyzer-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1763016383,
|
||||
"narHash": "sha256-eYmo7FNvm3q08iROzwIi8i9dWuUbJJl3uLR3OLnSmdI=",
|
||||
"lastModified": 1770708269,
|
||||
"narHash": "sha256-OnZW86app7hHJJoB5lC9GNXY5QBBIESJB+sIdwEyld0=",
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"rev": "0fad5c0e5c531358e7174cd666af4608f08bc3ba",
|
||||
"rev": "6b5325a017a9a9fe7e6252ccac3680cc7181cd63",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -96,11 +96,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1763043403,
|
||||
"narHash": "sha256-DgCTbHdIpzbXSlQlOZEWj8oPt2lrRMlSk03oIstvkVQ=",
|
||||
"lastModified": 1768649915,
|
||||
"narHash": "sha256-jc21hKogFnxU7KXSVTRmxC7u5D4RHwm9BAvDf5/Z1Uo=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "75e04ecd084f93d4105ce68c07dac7656291fe2e",
|
||||
"rev": "3e3f3c7f9977dc123c23ee21e8085ed63daf8c37",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -122,11 +122,11 @@
|
||||
"rust-analyzer-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1762860488,
|
||||
"narHash": "sha256-rMfWMCOo/pPefM2We0iMBLi2kLBAnYoB9thi4qS7uk4=",
|
||||
"lastModified": 1770668050,
|
||||
"narHash": "sha256-Q05yaIZtQrBKHpyWaPmyJmDRj0lojnVf8nUFE0vydcY=",
|
||||
"owner": "rust-lang",
|
||||
"repo": "rust-analyzer",
|
||||
"rev": "2efc80078029894eec0699f62ec8d5c1a56af763",
|
||||
"rev": "9efc1f709f3c8134c3acac5d3592a8e4c184a0c6",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -175,11 +175,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1762907712,
|
||||
"narHash": "sha256-VNW/+VYIg6N4b9Iq+F0YZmm22n74IdFS7hsPLblWuOY=",
|
||||
"lastModified": 1770598090,
|
||||
"narHash": "sha256-k+82IDgTd9o5sxHIqGlvfwseKln3Ejx1edGtDltuPXo=",
|
||||
"owner": "mitchellh",
|
||||
"repo": "zig-overlay",
|
||||
"rev": "d16453ee78765e49527c56d23386cead799b6b53",
|
||||
"rev": "142495696982c88edddc8e17e4da90d8164acadf",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
54
src/App.zig
54
src/App.zig
@@ -1,4 +1,4 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
@@ -21,68 +21,38 @@ const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const log = @import("log.zig");
|
||||
const Config = @import("Config.zig");
|
||||
const Snapshot = @import("browser/js/Snapshot.zig");
|
||||
const Platform = @import("browser/js/Platform.zig");
|
||||
const Telemetry = @import("telemetry/telemetry.zig").Telemetry;
|
||||
const RobotStore = @import("browser/Robots.zig").RobotStore;
|
||||
|
||||
pub const Http = @import("http/Http.zig");
|
||||
pub const ArenaPool = @import("ArenaPool.zig");
|
||||
pub const Notification = @import("Notification.zig");
|
||||
|
||||
// Container for global state / objects that various parts of the system
|
||||
// might need.
|
||||
const App = @This();
|
||||
|
||||
http: Http,
|
||||
config: Config,
|
||||
config: *const Config,
|
||||
platform: Platform,
|
||||
snapshot: Snapshot,
|
||||
telemetry: Telemetry,
|
||||
allocator: Allocator,
|
||||
arena_pool: ArenaPool,
|
||||
robots: RobotStore,
|
||||
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 {
|
||||
pub fn init(allocator: Allocator, config: *const 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.robots = RobotStore.init(allocator);
|
||||
|
||||
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,
|
||||
});
|
||||
app.http = try Http.init(allocator, &app.robots, config);
|
||||
errdefer app.http.deinit();
|
||||
|
||||
app.platform = try Platform.init();
|
||||
@@ -93,12 +63,10 @@ pub fn init(allocator: Allocator, config: Config) !*App {
|
||||
|
||||
app.app_dir_path = getAndMakeAppDir(allocator);
|
||||
|
||||
app.telemetry = try Telemetry.init(app, config.run_mode);
|
||||
app.telemetry = try Telemetry.init(app, config.mode);
|
||||
errdefer app.telemetry.deinit();
|
||||
|
||||
try app.telemetry.register(app.notification);
|
||||
|
||||
app.arena_pool = ArenaPool.init(allocator);
|
||||
app.arena_pool = ArenaPool.init(allocator, 512, 1024 * 16);
|
||||
errdefer app.arena_pool.deinit();
|
||||
|
||||
return app;
|
||||
@@ -115,7 +83,7 @@ pub fn deinit(self: *App) void {
|
||||
self.app_dir_path = null;
|
||||
}
|
||||
self.telemetry.deinit();
|
||||
self.notification.deinit();
|
||||
self.robots.deinit();
|
||||
self.http.deinit();
|
||||
self.snapshot.deinit();
|
||||
self.platform.deinit();
|
||||
|
||||
@@ -29,18 +29,19 @@ free_list_len: u16 = 0,
|
||||
free_list: ?*Entry = null,
|
||||
free_list_max: u16,
|
||||
entry_pool: std.heap.MemoryPool(Entry),
|
||||
mutex: std.Thread.Mutex = .{},
|
||||
|
||||
const Entry = struct {
|
||||
next: ?*Entry,
|
||||
arena: ArenaAllocator,
|
||||
};
|
||||
|
||||
pub fn init(allocator: Allocator) ArenaPool {
|
||||
pub fn init(allocator: Allocator, free_list_max: u16, retain_bytes: usize) ArenaPool {
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.free_list_max = 512, // TODO make configurable
|
||||
.retain_bytes = 1024 * 16, // TODO make configurable
|
||||
.entry_pool = std.heap.MemoryPool(Entry).init(allocator),
|
||||
.free_list_max = free_list_max,
|
||||
.retain_bytes = retain_bytes,
|
||||
.entry_pool = .init(allocator),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -54,8 +55,12 @@ pub fn deinit(self: *ArenaPool) void {
|
||||
}
|
||||
|
||||
pub fn acquire(self: *ArenaPool) !Allocator {
|
||||
self.mutex.lock();
|
||||
defer self.mutex.unlock();
|
||||
|
||||
if (self.free_list) |entry| {
|
||||
self.free_list = entry.next;
|
||||
self.free_list_len -= 1;
|
||||
return entry.arena.allocator();
|
||||
}
|
||||
|
||||
@@ -72,13 +77,136 @@ pub fn release(self: *ArenaPool, allocator: Allocator) void {
|
||||
const arena: *std.heap.ArenaAllocator = @ptrCast(@alignCast(allocator.ptr));
|
||||
const entry: *Entry = @fieldParentPtr("arena", arena);
|
||||
|
||||
if (self.free_list_len == self.free_list_max) {
|
||||
// Reset the arena before acquiring the lock to minimize lock hold time
|
||||
_ = arena.reset(.{ .retain_with_limit = self.retain_bytes });
|
||||
|
||||
self.mutex.lock();
|
||||
defer self.mutex.unlock();
|
||||
|
||||
const free_list_len = self.free_list_len;
|
||||
if (free_list_len == self.free_list_max) {
|
||||
arena.deinit();
|
||||
self.entry_pool.destroy(entry);
|
||||
return;
|
||||
}
|
||||
|
||||
_ = arena.reset(.{ .retain_with_limit = self.retain_bytes });
|
||||
entry.next = self.free_list;
|
||||
self.free_list_len = free_list_len + 1;
|
||||
self.free_list = entry;
|
||||
}
|
||||
|
||||
pub fn reset(_: *const ArenaPool, allocator: Allocator, retain: usize) void {
|
||||
const arena: *std.heap.ArenaAllocator = @ptrCast(@alignCast(allocator.ptr));
|
||||
_ = arena.reset(.{ .retain_with_limit = retain });
|
||||
}
|
||||
|
||||
const testing = std.testing;
|
||||
|
||||
test "arena pool - basic acquire and use" {
|
||||
var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
|
||||
defer pool.deinit();
|
||||
|
||||
const alloc = try pool.acquire();
|
||||
const buf = try alloc.alloc(u8, 64);
|
||||
@memset(buf, 0xAB);
|
||||
try testing.expectEqual(@as(u8, 0xAB), buf[0]);
|
||||
|
||||
pool.release(alloc);
|
||||
}
|
||||
|
||||
test "arena pool - reuse entry after release" {
|
||||
var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
|
||||
defer pool.deinit();
|
||||
|
||||
const alloc1 = try pool.acquire();
|
||||
try testing.expectEqual(@as(u16, 0), pool.free_list_len);
|
||||
|
||||
pool.release(alloc1);
|
||||
try testing.expectEqual(@as(u16, 1), pool.free_list_len);
|
||||
|
||||
// The same entry should be returned from the free list.
|
||||
const alloc2 = try pool.acquire();
|
||||
try testing.expectEqual(@as(u16, 0), pool.free_list_len);
|
||||
try testing.expectEqual(alloc1.ptr, alloc2.ptr);
|
||||
|
||||
pool.release(alloc2);
|
||||
}
|
||||
|
||||
test "arena pool - multiple concurrent arenas" {
|
||||
var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
|
||||
defer pool.deinit();
|
||||
|
||||
const a1 = try pool.acquire();
|
||||
const a2 = try pool.acquire();
|
||||
const a3 = try pool.acquire();
|
||||
|
||||
// All three must be distinct arenas.
|
||||
try testing.expect(a1.ptr != a2.ptr);
|
||||
try testing.expect(a2.ptr != a3.ptr);
|
||||
try testing.expect(a1.ptr != a3.ptr);
|
||||
|
||||
_ = try a1.alloc(u8, 16);
|
||||
_ = try a2.alloc(u8, 32);
|
||||
_ = try a3.alloc(u8, 48);
|
||||
|
||||
pool.release(a1);
|
||||
pool.release(a2);
|
||||
pool.release(a3);
|
||||
|
||||
try testing.expectEqual(@as(u16, 3), pool.free_list_len);
|
||||
}
|
||||
|
||||
test "arena pool - free list respects max limit" {
|
||||
// Cap the free list at 1 so the second release discards its arena.
|
||||
var pool = ArenaPool.init(testing.allocator, 1, 1024 * 16);
|
||||
defer pool.deinit();
|
||||
|
||||
const a1 = try pool.acquire();
|
||||
const a2 = try pool.acquire();
|
||||
|
||||
pool.release(a1);
|
||||
try testing.expectEqual(@as(u16, 1), pool.free_list_len);
|
||||
|
||||
// The free list is full; a2's arena should be destroyed, not queued.
|
||||
pool.release(a2);
|
||||
try testing.expectEqual(@as(u16, 1), pool.free_list_len);
|
||||
}
|
||||
|
||||
test "arena pool - reset clears memory without releasing" {
|
||||
var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
|
||||
defer pool.deinit();
|
||||
|
||||
const alloc = try pool.acquire();
|
||||
|
||||
const buf = try alloc.alloc(u8, 128);
|
||||
@memset(buf, 0xFF);
|
||||
|
||||
// reset() frees arena memory but keeps the allocator in-flight.
|
||||
pool.reset(alloc, 0);
|
||||
|
||||
// The free list must stay empty; the allocator was not released.
|
||||
try testing.expectEqual(@as(u16, 0), pool.free_list_len);
|
||||
|
||||
// Allocating again through the same arena must still work.
|
||||
const buf2 = try alloc.alloc(u8, 64);
|
||||
@memset(buf2, 0x00);
|
||||
try testing.expectEqual(@as(u8, 0x00), buf2[0]);
|
||||
|
||||
pool.release(alloc);
|
||||
}
|
||||
|
||||
test "arena pool - deinit with entries in free list" {
|
||||
// Verifies that deinit properly cleans up free-listed arenas (no leaks
|
||||
// detected by the test allocator).
|
||||
var pool = ArenaPool.init(testing.allocator, 512, 1024 * 16);
|
||||
|
||||
const a1 = try pool.acquire();
|
||||
const a2 = try pool.acquire();
|
||||
_ = try a1.alloc(u8, 256);
|
||||
_ = try a2.alloc(u8, 512);
|
||||
pool.release(a1);
|
||||
pool.release(a2);
|
||||
try testing.expectEqual(@as(u16, 2), pool.free_list_len);
|
||||
|
||||
pool.deinit();
|
||||
}
|
||||
|
||||
849
src/Config.zig
Normal file
849
src/Config.zig
Normal file
@@ -0,0 +1,849 @@
|
||||
// Copyright (C) 2023-2026 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 Allocator = std.mem.Allocator;
|
||||
|
||||
const log = @import("log.zig");
|
||||
const dump = @import("browser/dump.zig");
|
||||
|
||||
pub const RunMode = enum {
|
||||
help,
|
||||
fetch,
|
||||
serve,
|
||||
version,
|
||||
mcp,
|
||||
};
|
||||
|
||||
pub const CDP_MAX_HTTP_REQUEST_SIZE = 4096;
|
||||
|
||||
// max message size
|
||||
// +14 for max websocket payload overhead
|
||||
// +140 for the max control packet that might be interleaved in a message
|
||||
pub const CDP_MAX_MESSAGE_SIZE = 512 * 1024 + 14 + 140;
|
||||
|
||||
mode: Mode,
|
||||
exec_name: []const u8,
|
||||
http_headers: HttpHeaders,
|
||||
|
||||
const Config = @This();
|
||||
|
||||
pub fn init(allocator: Allocator, exec_name: []const u8, mode: Mode) !Config {
|
||||
var config = Config{
|
||||
.mode = mode,
|
||||
.exec_name = exec_name,
|
||||
.http_headers = undefined,
|
||||
};
|
||||
config.http_headers = try HttpHeaders.init(allocator, &config);
|
||||
return config;
|
||||
}
|
||||
|
||||
pub fn deinit(self: *const Config, allocator: Allocator) void {
|
||||
self.http_headers.deinit(allocator);
|
||||
}
|
||||
|
||||
pub fn tlsVerifyHost(self: *const Config) bool {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.tls_verify_host,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn obeyRobots(self: *const Config) bool {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.obey_robots,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpProxy(self: *const Config) ?[:0]const u8 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_proxy,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn proxyBearerToken(self: *const Config) ?[:0]const u8 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.proxy_bearer_token,
|
||||
.help, .version => null,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpMaxConcurrent(self: *const Config) u8 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_max_concurrent orelse 10,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpMaxHostOpen(self: *const Config) u8 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_max_host_open orelse 4,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpConnectTimeout(self: *const Config) u31 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_connect_timeout orelse 0,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpTimeout(self: *const Config) u31 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_timeout orelse 5000,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn httpMaxRedirects(_: *const Config) u8 {
|
||||
return 10;
|
||||
}
|
||||
|
||||
pub fn httpMaxResponseSize(self: *const Config) ?usize {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.http_max_response_size,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn logLevel(self: *const Config) ?log.Level {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.log_level,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn logFormat(self: *const Config) ?log.Format {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.log_format,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn logFilterScopes(self: *const Config) ?[]const log.Scope {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.log_filter_scopes,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn userAgentSuffix(self: *const Config) ?[]const u8 {
|
||||
return switch (self.mode) {
|
||||
inline .serve, .fetch, .mcp => |opts| opts.common.user_agent_suffix,
|
||||
.help, .version => null,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn maxConnections(self: *const Config) u16 {
|
||||
return switch (self.mode) {
|
||||
.serve => |opts| opts.cdp_max_connections,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn maxPendingConnections(self: *const Config) u31 {
|
||||
return switch (self.mode) {
|
||||
.serve => |opts| opts.cdp_max_pending_connections,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
pub const Mode = union(RunMode) {
|
||||
help: bool, // false when being printed because of an error
|
||||
fetch: Fetch,
|
||||
serve: Serve,
|
||||
version: void,
|
||||
mcp: Mcp,
|
||||
};
|
||||
|
||||
pub const Serve = struct {
|
||||
host: []const u8 = "127.0.0.1",
|
||||
port: u16 = 9222,
|
||||
timeout: u31 = 10,
|
||||
cdp_max_connections: u16 = 16,
|
||||
cdp_max_pending_connections: u16 = 128,
|
||||
common: Common = .{},
|
||||
};
|
||||
|
||||
pub const Mcp = struct {
|
||||
common: Common = .{},
|
||||
};
|
||||
|
||||
pub const DumpFormat = enum {
|
||||
html,
|
||||
markdown,
|
||||
wpt,
|
||||
};
|
||||
|
||||
pub const Fetch = struct {
|
||||
url: [:0]const u8,
|
||||
dump_mode: ?DumpFormat = null,
|
||||
common: Common = .{},
|
||||
with_base: bool = false,
|
||||
with_frames: bool = false,
|
||||
strip: dump.Opts.Strip = .{},
|
||||
};
|
||||
|
||||
pub const Common = struct {
|
||||
obey_robots: bool = false,
|
||||
proxy_bearer_token: ?[:0]const u8 = null,
|
||||
http_proxy: ?[:0]const u8 = null,
|
||||
http_max_concurrent: ?u8 = null,
|
||||
http_max_host_open: ?u8 = null,
|
||||
http_timeout: ?u31 = null,
|
||||
http_connect_timeout: ?u31 = null,
|
||||
http_max_response_size: ?usize = null,
|
||||
tls_verify_host: bool = true,
|
||||
log_level: ?log.Level = null,
|
||||
log_format: ?log.Format = null,
|
||||
log_filter_scopes: ?[]log.Scope = null,
|
||||
user_agent_suffix: ?[]const u8 = null,
|
||||
};
|
||||
|
||||
/// Pre-formatted HTTP headers for reuse across Http and Client.
|
||||
/// Must be initialized with an allocator that outlives all HTTP connections.
|
||||
pub const HttpHeaders = struct {
|
||||
const user_agent_base: [:0]const u8 = "Lightpanda/1.0";
|
||||
|
||||
user_agent: [:0]const u8, // User agent value (e.g. "Lightpanda/1.0")
|
||||
user_agent_header: [:0]const u8,
|
||||
|
||||
proxy_bearer_header: ?[:0]const u8,
|
||||
|
||||
pub fn init(allocator: Allocator, config: *const Config) !HttpHeaders {
|
||||
const user_agent: [:0]const u8 = if (config.userAgentSuffix()) |suffix|
|
||||
try std.fmt.allocPrintSentinel(allocator, "{s} {s}", .{ user_agent_base, suffix }, 0)
|
||||
else
|
||||
user_agent_base;
|
||||
errdefer if (config.userAgentSuffix() != null) allocator.free(user_agent);
|
||||
|
||||
const user_agent_header = try std.fmt.allocPrintSentinel(allocator, "User-Agent: {s}", .{user_agent}, 0);
|
||||
errdefer allocator.free(user_agent_header);
|
||||
|
||||
const proxy_bearer_header: ?[:0]const u8 = if (config.proxyBearerToken()) |token|
|
||||
try std.fmt.allocPrintSentinel(allocator, "Proxy-Authorization: Bearer {s}", .{token}, 0)
|
||||
else
|
||||
null;
|
||||
|
||||
return .{
|
||||
.user_agent = user_agent,
|
||||
.user_agent_header = user_agent_header,
|
||||
.proxy_bearer_header = proxy_bearer_header,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *const HttpHeaders, allocator: Allocator) void {
|
||||
if (self.proxy_bearer_header) |hdr| {
|
||||
allocator.free(hdr);
|
||||
}
|
||||
allocator.free(self.user_agent_header);
|
||||
if (self.user_agent.ptr != user_agent_base.ptr) {
|
||||
allocator.free(self.user_agent);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
pub fn printUsageAndExit(self: *const Config, success: bool) void {
|
||||
// MAX_HELP_LEN|
|
||||
const common_options =
|
||||
\\
|
||||
\\--insecure_disable_tls_host_verification
|
||||
\\ Disables host verification on all HTTP requests. This is an
|
||||
\\ advanced option which should only be set if you understand
|
||||
\\ and accept the risk of disabling host verification.
|
||||
\\
|
||||
\\--obey_robots
|
||||
\\ Fetches and obeys the robots.txt (if available) of the web pages
|
||||
\\ we make requests towards.
|
||||
\\ Defaults to false.
|
||||
\\
|
||||
\\--http_proxy The HTTP proxy to use for all HTTP requests.
|
||||
\\ A username:password can be included for basic authentication.
|
||||
\\ Defaults to none.
|
||||
\\
|
||||
\\--proxy_bearer_token
|
||||
\\ The <token> to send for bearer authentication with the proxy
|
||||
\\ Proxy-Authorization: Bearer <token>
|
||||
\\
|
||||
\\--http_max_concurrent
|
||||
\\ The maximum number of concurrent HTTP requests.
|
||||
\\ Defaults to 10.
|
||||
\\
|
||||
\\--http_max_host_open
|
||||
\\ The maximum number of open connection to a given host:port.
|
||||
\\ Defaults to 4.
|
||||
\\
|
||||
\\--http_connect_timeout
|
||||
\\ The time, in milliseconds, for establishing an HTTP connection
|
||||
\\ before timing out. 0 means it never times out.
|
||||
\\ Defaults to 0.
|
||||
\\
|
||||
\\--http_timeout
|
||||
\\ The maximum time, in milliseconds, the transfer is allowed
|
||||
\\ to complete. 0 means it never times out.
|
||||
\\ Defaults to 10000.
|
||||
\\
|
||||
\\--http_max_response_size
|
||||
\\ Limits the acceptable response size for any request
|
||||
\\ (e.g. XHR, fetch, script loading, ...).
|
||||
\\ Defaults to no limit.
|
||||
\\
|
||||
\\--log_level The log level: debug, info, warn, error or fatal.
|
||||
\\ Defaults to
|
||||
++ (if (builtin.mode == .Debug) " info." else "warn.") ++
|
||||
\\
|
||||
\\
|
||||
\\--log_format The log format: pretty or logfmt.
|
||||
\\ Defaults to
|
||||
++ (if (builtin.mode == .Debug) " pretty." else " logfmt.") ++
|
||||
\\
|
||||
\\
|
||||
\\--log_filter_scopes
|
||||
\\ Filter out too verbose logs per scope:
|
||||
\\ http, unknown_prop, event, ...
|
||||
\\
|
||||
\\--user_agent_suffix
|
||||
\\ Suffix to append to the Lightpanda/X.Y User-Agent
|
||||
\\
|
||||
;
|
||||
|
||||
// MAX_HELP_LEN|
|
||||
const usage =
|
||||
\\usage: {s} command [options] [URL]
|
||||
\\
|
||||
\\Command can be either 'fetch', 'serve', 'mcp' or 'help'
|
||||
\\
|
||||
\\fetch command
|
||||
\\Fetches the specified URL
|
||||
\\Example: {s} fetch --dump html https://lightpanda.io/
|
||||
\\
|
||||
\\Options:
|
||||
\\--dump Dumps document to stdout.
|
||||
\\ Argument must be 'html' or 'markdown'.
|
||||
\\ Defaults to no dump.
|
||||
\\
|
||||
\\--strip_mode Comma separated list of tag groups to remove from dump
|
||||
\\ the dump. e.g. --strip_mode js,css
|
||||
\\ - "js" script and link[as=script, rel=preload]
|
||||
\\ - "ui" includes img, picture, video, css and svg
|
||||
\\ - "css" includes style and link[rel=stylesheet]
|
||||
\\ - "full" includes js, ui and css
|
||||
\\
|
||||
\\--with_base Add a <base> tag in dump. Defaults to false.
|
||||
\\
|
||||
\\--with_frames Includes the contents of iframes. Defaults to false.
|
||||
\\
|
||||
++ common_options ++
|
||||
\\
|
||||
\\serve command
|
||||
\\Starts a websocket CDP server
|
||||
\\Example: {s} serve --host 127.0.0.1 --port 9222
|
||||
\\
|
||||
\\Options:
|
||||
\\--host Host of the CDP server
|
||||
\\ Defaults to "127.0.0.1"
|
||||
\\
|
||||
\\--port Port of the CDP server
|
||||
\\ Defaults to 9222
|
||||
\\
|
||||
\\--timeout Inactivity timeout in seconds before disconnecting clients
|
||||
\\ Defaults to 10 (seconds). Limited to 604800 (1 week).
|
||||
\\
|
||||
\\--cdp_max_connections
|
||||
\\ Maximum number of simultaneous CDP connections.
|
||||
\\ Defaults to 16.
|
||||
\\
|
||||
\\--cdp_max_pending_connections
|
||||
\\ Maximum pending connections in the accept queue.
|
||||
\\ Defaults to 128.
|
||||
\\
|
||||
++ common_options ++
|
||||
\\
|
||||
\\mcp command
|
||||
\\Starts an MCP (Model Context Protocol) server over stdio
|
||||
\\Example: {s} mcp
|
||||
\\
|
||||
++ common_options ++
|
||||
\\
|
||||
\\version command
|
||||
\\Displays the version of {s}
|
||||
\\
|
||||
\\help command
|
||||
\\Displays this message
|
||||
\\
|
||||
;
|
||||
std.debug.print(usage, .{ self.exec_name, self.exec_name, self.exec_name, self.exec_name, self.exec_name });
|
||||
if (success) {
|
||||
return std.process.cleanExit();
|
||||
}
|
||||
std.process.exit(1);
|
||||
}
|
||||
|
||||
pub fn parseArgs(allocator: Allocator) !Config {
|
||||
var args = try std.process.argsWithAllocator(allocator);
|
||||
defer args.deinit();
|
||||
|
||||
const exec_name = try allocator.dupe(u8, std.fs.path.basename(args.next().?));
|
||||
|
||||
const mode_string = args.next() orelse "";
|
||||
const run_mode = std.meta.stringToEnum(RunMode, mode_string) orelse blk: {
|
||||
const inferred_mode = inferMode(mode_string) orelse
|
||||
return init(allocator, exec_name, .{ .help = false });
|
||||
// "command" wasn't a command but an option. We can't reset args, but
|
||||
// we can create a new one. Not great, but this fallback is temporary
|
||||
// as we transition to this command mode approach.
|
||||
args.deinit();
|
||||
|
||||
args = try std.process.argsWithAllocator(allocator);
|
||||
// skip the exec_name
|
||||
_ = args.skip();
|
||||
|
||||
break :blk inferred_mode;
|
||||
};
|
||||
|
||||
const mode: Mode = switch (run_mode) {
|
||||
.help => .{ .help = true },
|
||||
.serve => .{ .serve = parseServeArgs(allocator, &args) catch
|
||||
return init(allocator, exec_name, .{ .help = false }) },
|
||||
.fetch => .{ .fetch = parseFetchArgs(allocator, &args) catch
|
||||
return init(allocator, exec_name, .{ .help = false }) },
|
||||
.mcp => .{ .mcp = parseMcpArgs(allocator, &args) catch
|
||||
return init(allocator, exec_name, .{ .help = false }) },
|
||||
.version => .{ .version = {} },
|
||||
};
|
||||
return init(allocator, exec_name, mode);
|
||||
}
|
||||
|
||||
fn inferMode(opt: []const u8) ?RunMode {
|
||||
if (opt.len == 0) {
|
||||
return .serve;
|
||||
}
|
||||
|
||||
if (std.mem.startsWith(u8, opt, "--") == false) {
|
||||
return .fetch;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, opt, "--dump")) {
|
||||
return .fetch;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, opt, "--noscript")) {
|
||||
return .fetch;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, opt, "--strip_mode")) {
|
||||
return .fetch;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, opt, "--with_base")) {
|
||||
return .fetch;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, opt, "--with_frames")) {
|
||||
return .fetch;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, opt, "--host")) {
|
||||
return .serve;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, opt, "--port")) {
|
||||
return .serve;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, opt, "--timeout")) {
|
||||
return .serve;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
fn parseServeArgs(
|
||||
allocator: Allocator,
|
||||
args: *std.process.ArgIterator,
|
||||
) !Serve {
|
||||
var serve: Serve = .{};
|
||||
|
||||
while (args.next()) |opt| {
|
||||
if (std.mem.eql(u8, "--host", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--host" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
serve.host = try allocator.dupe(u8, str);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--port", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--port" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
serve.port = std.fmt.parseInt(u16, str, 10) catch |err| {
|
||||
log.fatal(.app, "invalid argument value", .{ .arg = "--port", .err = err });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--timeout", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--timeout" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
serve.timeout = std.fmt.parseInt(u31, str, 10) catch |err| {
|
||||
log.fatal(.app, "invalid argument value", .{ .arg = "--timeout", .err = err });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--cdp_max_connections", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--cdp_max_connections" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
serve.cdp_max_connections = std.fmt.parseInt(u16, str, 10) catch |err| {
|
||||
log.fatal(.app, "invalid argument value", .{ .arg = "--cdp_max_connections", .err = err });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--cdp_max_pending_connections", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--cdp_max_pending_connections" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
serve.cdp_max_pending_connections = std.fmt.parseInt(u16, str, 10) catch |err| {
|
||||
log.fatal(.app, "invalid argument value", .{ .arg = "--cdp_max_pending_connections", .err = err });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if (try parseCommonArg(allocator, opt, args, &serve.common)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
log.fatal(.app, "unknown argument", .{ .mode = "serve", .arg = opt });
|
||||
return error.UnkownOption;
|
||||
}
|
||||
|
||||
return serve;
|
||||
}
|
||||
|
||||
fn parseMcpArgs(
|
||||
allocator: Allocator,
|
||||
args: *std.process.ArgIterator,
|
||||
) !Mcp {
|
||||
var mcp: Mcp = .{};
|
||||
|
||||
while (args.next()) |opt| {
|
||||
if (try parseCommonArg(allocator, opt, args, &mcp.common)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
log.fatal(.mcp, "unknown argument", .{ .mode = "mcp", .arg = opt });
|
||||
return error.UnkownOption;
|
||||
}
|
||||
|
||||
return mcp;
|
||||
}
|
||||
|
||||
fn parseFetchArgs(
|
||||
allocator: Allocator,
|
||||
args: *std.process.ArgIterator,
|
||||
) !Fetch {
|
||||
var dump_mode: ?DumpFormat = null;
|
||||
var with_base: bool = false;
|
||||
var with_frames: bool = false;
|
||||
var url: ?[:0]const u8 = null;
|
||||
var common: Common = .{};
|
||||
var strip: dump.Opts.Strip = .{};
|
||||
|
||||
while (args.next()) |opt| {
|
||||
if (std.mem.eql(u8, "--dump", opt)) {
|
||||
var peek_args = args.*;
|
||||
if (peek_args.next()) |next_arg| {
|
||||
if (std.meta.stringToEnum(DumpFormat, next_arg)) |mode| {
|
||||
dump_mode = mode;
|
||||
_ = args.next();
|
||||
} else {
|
||||
dump_mode = .html;
|
||||
}
|
||||
} else {
|
||||
dump_mode = .html;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--noscript", opt)) {
|
||||
log.warn(.app, "deprecation warning", .{
|
||||
.feature = "--noscript argument",
|
||||
.hint = "use '--strip_mode js' instead",
|
||||
});
|
||||
strip.js = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--with_base", opt)) {
|
||||
with_base = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--with_frames", opt)) {
|
||||
with_frames = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--strip_mode", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--strip_mode" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
var it = std.mem.splitScalar(u8, str, ',');
|
||||
while (it.next()) |part| {
|
||||
const trimmed = std.mem.trim(u8, part, &std.ascii.whitespace);
|
||||
if (std.mem.eql(u8, trimmed, "js")) {
|
||||
strip.js = true;
|
||||
} else if (std.mem.eql(u8, trimmed, "ui")) {
|
||||
strip.ui = true;
|
||||
} else if (std.mem.eql(u8, trimmed, "css")) {
|
||||
strip.css = true;
|
||||
} else if (std.mem.eql(u8, trimmed, "full")) {
|
||||
strip.js = true;
|
||||
strip.ui = true;
|
||||
strip.css = true;
|
||||
} else {
|
||||
log.fatal(.app, "invalid option choice", .{ .arg = "--strip_mode", .value = trimmed });
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (try parseCommonArg(allocator, opt, args, &common)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std.mem.startsWith(u8, opt, "--")) {
|
||||
log.fatal(.app, "unknown argument", .{ .mode = "fetch", .arg = opt });
|
||||
return error.UnkownOption;
|
||||
}
|
||||
|
||||
if (url != null) {
|
||||
log.fatal(.app, "duplicate fetch url", .{ .help = "only 1 URL can be specified" });
|
||||
return error.TooManyURLs;
|
||||
}
|
||||
url = try allocator.dupeZ(u8, opt);
|
||||
}
|
||||
|
||||
if (url == null) {
|
||||
log.fatal(.app, "missing fetch url", .{ .help = "URL to fetch must be provided" });
|
||||
return error.MissingURL;
|
||||
}
|
||||
|
||||
return .{
|
||||
.url = url.?,
|
||||
.dump_mode = dump_mode,
|
||||
.strip = strip,
|
||||
.common = common,
|
||||
.with_base = with_base,
|
||||
.with_frames = with_frames,
|
||||
};
|
||||
}
|
||||
|
||||
fn parseCommonArg(
|
||||
allocator: Allocator,
|
||||
opt: []const u8,
|
||||
args: *std.process.ArgIterator,
|
||||
common: *Common,
|
||||
) !bool {
|
||||
if (std.mem.eql(u8, "--insecure_disable_tls_host_verification", opt)) {
|
||||
common.tls_verify_host = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--obey_robots", opt)) {
|
||||
common.obey_robots = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--http_proxy", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--http_proxy" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
common.http_proxy = try allocator.dupeZ(u8, str);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--proxy_bearer_token", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--proxy_bearer_token" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
common.proxy_bearer_token = try allocator.dupeZ(u8, str);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--http_max_concurrent", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--http_max_concurrent" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
common.http_max_concurrent = std.fmt.parseInt(u8, str, 10) catch |err| {
|
||||
log.fatal(.app, "invalid argument value", .{ .arg = "--http_max_concurrent", .err = err });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--http_max_host_open", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--http_max_host_open" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
common.http_max_host_open = std.fmt.parseInt(u8, str, 10) catch |err| {
|
||||
log.fatal(.app, "invalid argument value", .{ .arg = "--http_max_host_open", .err = err });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--http_connect_timeout", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--http_connect_timeout" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
common.http_connect_timeout = std.fmt.parseInt(u31, str, 10) catch |err| {
|
||||
log.fatal(.app, "invalid argument value", .{ .arg = "--http_connect_timeout", .err = err });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--http_timeout", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--http_timeout" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
common.http_timeout = std.fmt.parseInt(u31, str, 10) catch |err| {
|
||||
log.fatal(.app, "invalid argument value", .{ .arg = "--http_timeout", .err = err });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--http_max_response_size", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--http_max_response_size" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
common.http_max_response_size = std.fmt.parseInt(usize, str, 10) catch |err| {
|
||||
log.fatal(.app, "invalid argument value", .{ .arg = "--http_max_response_size", .err = err });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--log_level", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--log_level" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
common.log_level = std.meta.stringToEnum(log.Level, str) orelse blk: {
|
||||
if (std.mem.eql(u8, str, "error")) {
|
||||
break :blk .err;
|
||||
}
|
||||
log.fatal(.app, "invalid option choice", .{ .arg = "--log_level", .value = str });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--log_format", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--log_format" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
|
||||
common.log_format = std.meta.stringToEnum(log.Format, str) orelse {
|
||||
log.fatal(.app, "invalid option choice", .{ .arg = "--log_format", .value = str });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--log_filter_scopes", opt)) {
|
||||
if (builtin.mode != .Debug) {
|
||||
log.fatal(.app, "experimental", .{ .help = "log scope filtering is only available in debug builds" });
|
||||
return false;
|
||||
}
|
||||
|
||||
const str = args.next() orelse {
|
||||
// disables the default filters
|
||||
common.log_filter_scopes = &.{};
|
||||
return true;
|
||||
};
|
||||
|
||||
var arr: std.ArrayList(log.Scope) = .empty;
|
||||
|
||||
var it = std.mem.splitScalar(u8, str, ',');
|
||||
while (it.next()) |part| {
|
||||
try arr.append(allocator, std.meta.stringToEnum(log.Scope, part) orelse {
|
||||
log.fatal(.app, "invalid option choice", .{ .arg = "--log_filter_scopes", .value = part });
|
||||
return false;
|
||||
});
|
||||
}
|
||||
common.log_filter_scopes = arr.items;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (std.mem.eql(u8, "--user_agent_suffix", opt)) {
|
||||
const str = args.next() orelse {
|
||||
log.fatal(.app, "missing argument value", .{ .arg = "--user_agent_suffix" });
|
||||
return error.InvalidArgument;
|
||||
};
|
||||
for (str) |c| {
|
||||
if (!std.ascii.isPrint(c)) {
|
||||
log.fatal(.app, "not printable character", .{ .arg = "--user_agent_suffix" });
|
||||
return error.InvalidArgument;
|
||||
}
|
||||
}
|
||||
common.user_agent_suffix = try allocator.dupe(u8, str);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
1707
src/Net.zig
Normal file
1707
src/Net.zig
Normal file
File diff suppressed because it is too large
Load Diff
@@ -39,10 +39,9 @@ const List = std.DoublyLinkedList;
|
||||
// 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.
|
||||
// That is, it would work until multiple CDP clients connect, and because
|
||||
// everything's just one big global, events from one CDP session would be sent
|
||||
// to all CDP clients.
|
||||
//
|
||||
// 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
|
||||
@@ -50,14 +49,10 @@ const List = std.DoublyLinkedList;
|
||||
// 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.
|
||||
// CDP connection (BrowserContext). Each CDP connection has its own notification
|
||||
// that is shared across all Sessions (tabs) within that connection. This ensures
|
||||
// proper isolation between different CDP clients while allowing a single client
|
||||
// to receive events from all its tabs.
|
||||
const Notification = @This();
|
||||
// Every event type (which are hard-coded), has a list of Listeners.
|
||||
// When the event happens, we dispatch to those listener.
|
||||
@@ -66,7 +61,7 @@ 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)),
|
||||
listeners: std.AutoHashMapUnmanaged(usize, std.ArrayList(*Listener)),
|
||||
|
||||
allocator: Allocator,
|
||||
mem_pool: std.heap.MemoryPool(Listener),
|
||||
@@ -78,6 +73,7 @@ const EventListeners = struct {
|
||||
page_navigated: List = .{},
|
||||
page_network_idle: List = .{},
|
||||
page_network_almost_idle: List = .{},
|
||||
page_frame_created: List = .{},
|
||||
http_request_fail: List = .{},
|
||||
http_request_start: List = .{},
|
||||
http_request_intercept: List = .{},
|
||||
@@ -85,7 +81,6 @@ const EventListeners = struct {
|
||||
http_request_auth_required: List = .{},
|
||||
http_response_data: List = .{},
|
||||
http_response_header_done: List = .{},
|
||||
notification_created: List = .{},
|
||||
};
|
||||
|
||||
const Events = union(enum) {
|
||||
@@ -95,6 +90,7 @@ const Events = union(enum) {
|
||||
page_navigated: *const PageNavigated,
|
||||
page_network_idle: *const PageNetworkIdle,
|
||||
page_network_almost_idle: *const PageNetworkAlmostIdle,
|
||||
page_frame_created: *const PageFrameCreated,
|
||||
http_request_fail: *const RequestFail,
|
||||
http_request_start: *const RequestStart,
|
||||
http_request_intercept: *const RequestIntercept,
|
||||
@@ -102,31 +98,42 @@ const Events = union(enum) {
|
||||
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,
|
||||
req_id: u32,
|
||||
frame_id: u32,
|
||||
timestamp: u64,
|
||||
url: [:0]const u8,
|
||||
opts: Page.NavigateOpts,
|
||||
};
|
||||
|
||||
pub const PageNavigated = struct {
|
||||
req_id: usize,
|
||||
req_id: u32,
|
||||
frame_id: u32,
|
||||
timestamp: u64,
|
||||
url: [:0]const u8,
|
||||
opts: Page.NavigatedOpts,
|
||||
};
|
||||
|
||||
pub const PageNetworkIdle = struct {
|
||||
req_id: u32,
|
||||
frame_id: u32,
|
||||
timestamp: u64,
|
||||
};
|
||||
|
||||
pub const PageNetworkAlmostIdle = struct {
|
||||
req_id: u32,
|
||||
frame_id: u32,
|
||||
timestamp: u64,
|
||||
};
|
||||
|
||||
pub const PageFrameCreated = struct {
|
||||
frame_id: u32,
|
||||
parent_id: u32,
|
||||
timestamp: u64,
|
||||
};
|
||||
|
||||
@@ -162,12 +169,7 @@ pub const RequestFail = struct {
|
||||
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.
|
||||
pub fn init(allocator: Allocator) !*Notification {
|
||||
const notification = try allocator.create(Notification);
|
||||
errdefer allocator.destroy(notification);
|
||||
|
||||
@@ -178,10 +180,6 @@ pub fn init(allocator: Allocator, parent: ?*Notification) !*Notification {
|
||||
.mem_pool = std.heap.MemoryPool(Listener).init(allocator),
|
||||
};
|
||||
|
||||
if (parent) |pn| {
|
||||
pn.dispatch(.notification_created, notification);
|
||||
}
|
||||
|
||||
return notification;
|
||||
}
|
||||
|
||||
@@ -256,6 +254,9 @@ pub fn unregisterAll(self: *Notification, receiver: *anyopaque) void {
|
||||
}
|
||||
|
||||
pub fn dispatch(self: *Notification, comptime event: EventType, data: ArgType(event)) void {
|
||||
if (self.listeners.count() == 0) {
|
||||
return;
|
||||
}
|
||||
const list = &@field(self.event_listeners, @tagName(event));
|
||||
|
||||
var node = list.first;
|
||||
@@ -313,11 +314,12 @@ const Listener = struct {
|
||||
|
||||
const testing = std.testing;
|
||||
test "Notification" {
|
||||
var notifier = try Notification.init(testing.allocator, null);
|
||||
var notifier = try Notification.init(testing.allocator);
|
||||
defer notifier.deinit();
|
||||
|
||||
// noop
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.frame_id = 0,
|
||||
.req_id = 1,
|
||||
.timestamp = 4,
|
||||
.url = undefined,
|
||||
@@ -328,6 +330,7 @@ test "Notification" {
|
||||
|
||||
try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.frame_id = 0,
|
||||
.req_id = 1,
|
||||
.timestamp = 4,
|
||||
.url = undefined,
|
||||
@@ -337,6 +340,7 @@ test "Notification" {
|
||||
|
||||
notifier.unregisterAll(&tc);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.frame_id = 0,
|
||||
.req_id = 1,
|
||||
.timestamp = 10,
|
||||
.url = undefined,
|
||||
@@ -347,23 +351,25 @@ test "Notification" {
|
||||
try notifier.register(.page_navigate, &tc, TestClient.pageNavigate);
|
||||
try notifier.register(.page_navigated, &tc, TestClient.pageNavigated);
|
||||
notifier.dispatch(.page_navigate, &.{
|
||||
.frame_id = 0,
|
||||
.req_id = 1,
|
||||
.timestamp = 10,
|
||||
.url = undefined,
|
||||
.opts = .{},
|
||||
});
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 6, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .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, &.{
|
||||
.frame_id = 0,
|
||||
.req_id = 1,
|
||||
.timestamp = 100,
|
||||
.url = undefined,
|
||||
.opts = .{},
|
||||
});
|
||||
notifier.dispatch(.page_navigated, &.{ .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(14, tc.page_navigate);
|
||||
try testing.expectEqual(6, tc.page_navigated);
|
||||
|
||||
@@ -371,27 +377,27 @@ test "Notification" {
|
||||
// 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 = .{} });
|
||||
notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .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 = .{} });
|
||||
notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .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 = .{} });
|
||||
notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .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 = .{} });
|
||||
notifier.dispatch(.page_navigate, &.{ .frame_id = 0, .req_id = 1, .timestamp = 100, .url = undefined, .opts = .{} });
|
||||
notifier.dispatch(.page_navigated, &.{ .frame_id = 0, .req_id = 1, .timestamp = 1000, .url = undefined, .opts = .{} });
|
||||
try testing.expectEqual(114, tc.page_navigate);
|
||||
try testing.expectEqual(2006, tc.page_navigated);
|
||||
}
|
||||
|
||||
1081
src/Server.zig
1081
src/Server.zig
File diff suppressed because it is too large
Load Diff
@@ -17,10 +17,11 @@
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const URL = @import("browser/URL.zig");
|
||||
|
||||
const TestHTTPServer = @This();
|
||||
|
||||
shutdown: bool,
|
||||
shutdown: std.atomic.Value(bool),
|
||||
listener: ?std.net.Server,
|
||||
handler: Handler,
|
||||
|
||||
@@ -28,16 +29,23 @@ const Handler = *const fn (req: *std.http.Server.Request) anyerror!void;
|
||||
|
||||
pub fn init(handler: Handler) TestHTTPServer {
|
||||
return .{
|
||||
.shutdown = true,
|
||||
.shutdown = .init(true),
|
||||
.listener = null,
|
||||
.handler = handler,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *TestHTTPServer) void {
|
||||
self.shutdown = true;
|
||||
self.listener = null;
|
||||
}
|
||||
|
||||
pub fn stop(self: *TestHTTPServer) void {
|
||||
self.shutdown.store(true, .release);
|
||||
if (self.listener) |*listener| {
|
||||
listener.deinit();
|
||||
switch (@import("builtin").target.os.tag) {
|
||||
.linux => std.posix.shutdown(listener.stream.handle, .recv) catch {},
|
||||
else => std.posix.close(listener.stream.handle),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,12 +54,13 @@ pub fn run(self: *TestHTTPServer, wg: *std.Thread.WaitGroup) !void {
|
||||
|
||||
self.listener = try address.listen(.{ .reuse_address = true });
|
||||
var listener = &self.listener.?;
|
||||
self.shutdown.store(false, .release);
|
||||
|
||||
wg.finish();
|
||||
|
||||
while (true) {
|
||||
const conn = listener.accept() catch |err| {
|
||||
if (self.shutdown) {
|
||||
if (self.shutdown.load(.acquire) or err == error.SocketNotListening) {
|
||||
return;
|
||||
}
|
||||
return err;
|
||||
@@ -89,7 +98,10 @@ fn handleConnection(self: *TestHTTPServer, conn: std.net.Server.Connection) !voi
|
||||
}
|
||||
|
||||
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) {
|
||||
var url_buf: [1024]u8 = undefined;
|
||||
var fba = std.heap.FixedBufferAllocator.init(&url_buf);
|
||||
const unescaped_file_path = try URL.unescape(fba.allocator(), file_path);
|
||||
var file = std.fs.cwd().openFile(unescaped_file_path, .{}) catch |err| switch (err) {
|
||||
error.FileNotFound => return req.respond("server error", .{ .status = .not_found }),
|
||||
else => return err,
|
||||
};
|
||||
|
||||
@@ -24,14 +24,14 @@ 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 ArenaPool = App.ArenaPool;
|
||||
const HttpClient = App.Http.Client;
|
||||
const Notification = App.Notification;
|
||||
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
const Session = @import("Session.zig");
|
||||
const Notification = @import("../Notification.zig");
|
||||
|
||||
// Browser is an instance of the browser.
|
||||
// You can create multiple browser instances.
|
||||
@@ -44,54 +44,38 @@ session: ?Session,
|
||||
allocator: Allocator,
|
||||
arena_pool: *ArenaPool,
|
||||
http_client: *HttpClient,
|
||||
call_arena: ArenaAllocator,
|
||||
page_arena: ArenaAllocator,
|
||||
session_arena: ArenaAllocator,
|
||||
transfer_arena: ArenaAllocator,
|
||||
notification: *Notification,
|
||||
|
||||
pub fn init(app: *App) !Browser {
|
||||
const InitOpts = struct {
|
||||
env: js.Env.InitOpts = .{},
|
||||
http_client: *HttpClient,
|
||||
};
|
||||
|
||||
pub fn init(app: *App, opts: InitOpts) !Browser {
|
||||
const allocator = app.allocator;
|
||||
|
||||
var env = try js.Env.init(allocator, &app.platform, &app.snapshot);
|
||||
var env = try js.Env.init(app, opts.env);
|
||||
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,
|
||||
.arena_pool = &app.arena_pool,
|
||||
.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),
|
||||
.http_client = opts.http_client,
|
||||
};
|
||||
}
|
||||
|
||||
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 {
|
||||
pub fn newSession(self: *Browser, notification: *Notification) !*Session {
|
||||
self.closeSession();
|
||||
self.session = @as(Session, undefined);
|
||||
const session = &self.session.?;
|
||||
try Session.init(session, self);
|
||||
try Session.init(session, self, notification);
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -99,20 +83,33 @@ 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.memoryPressureNotification(.critical);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn runMicrotasks(self: *const Browser) void {
|
||||
pub fn runMicrotasks(self: *Browser) void {
|
||||
self.env.runMicrotasks();
|
||||
}
|
||||
|
||||
pub fn runMessageLoop(self: *const Browser) void {
|
||||
while (self.env.pumpMessageLoop()) {
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.browser, "pumpMessageLoop", .{});
|
||||
}
|
||||
}
|
||||
pub fn runMacrotasks(self: *Browser) !?u64 {
|
||||
const env = &self.env;
|
||||
|
||||
const time_to_next = try self.env.runMacrotasks();
|
||||
env.pumpMessageLoop();
|
||||
|
||||
// either of the above could have queued more microtasks
|
||||
env.runMicrotasks();
|
||||
|
||||
return time_to_next;
|
||||
}
|
||||
|
||||
pub fn hasBackgroundTasks(self: *Browser) bool {
|
||||
return self.env.hasBackgroundTasks();
|
||||
}
|
||||
pub fn waitForBackgroundTasks(self: *Browser) void {
|
||||
self.env.waitForBackgroundTasks();
|
||||
}
|
||||
|
||||
pub fn runIdleTasks(self: *const Browser) void {
|
||||
self.env.runIdleTasks();
|
||||
}
|
||||
|
||||
@@ -28,30 +28,61 @@ const Page = @import("Page.zig");
|
||||
const Node = @import("webapi/Node.zig");
|
||||
const Event = @import("webapi/Event.zig");
|
||||
const EventTarget = @import("webapi/EventTarget.zig");
|
||||
const Element = @import("webapi/Element.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const IS_DEBUG = builtin.mode == .Debug;
|
||||
|
||||
const EventKey = struct {
|
||||
event_target: usize,
|
||||
type_string: String,
|
||||
};
|
||||
|
||||
const EventKeyContext = struct {
|
||||
pub fn hash(_: @This(), key: EventKey) u64 {
|
||||
var hasher = std.hash.Wyhash.init(0);
|
||||
hasher.update(std.mem.asBytes(&key.event_target));
|
||||
hasher.update(key.type_string.str());
|
||||
return hasher.final();
|
||||
}
|
||||
|
||||
pub fn eql(_: @This(), a: EventKey, b: EventKey) bool {
|
||||
return a.event_target == b.event_target and a.type_string.eql(b.type_string);
|
||||
}
|
||||
};
|
||||
|
||||
pub const EventManager = @This();
|
||||
|
||||
page: *Page,
|
||||
arena: Allocator,
|
||||
// Used as an optimization in Page._documentIsComplete. If we know there are no
|
||||
// 'load' listeners in the document, we can skip dispatching the per-resource
|
||||
// 'load' event (e.g. amazon product page has no listener and ~350 resources)
|
||||
has_dom_load_listener: bool,
|
||||
listener_pool: std.heap.MemoryPool(Listener),
|
||||
ignore_list: std.ArrayList(*Listener),
|
||||
list_pool: std.heap.MemoryPool(std.DoublyLinkedList),
|
||||
lookup: std.AutoHashMapUnmanaged(usize, *std.DoublyLinkedList),
|
||||
lookup: std.HashMapUnmanaged(
|
||||
EventKey,
|
||||
*std.DoublyLinkedList,
|
||||
EventKeyContext,
|
||||
std.hash_map.default_max_load_percentage,
|
||||
),
|
||||
dispatch_depth: usize,
|
||||
deferred_removals: std.ArrayList(struct { list: *std.DoublyLinkedList, listener: *Listener }),
|
||||
|
||||
pub fn init(page: *Page) EventManager {
|
||||
pub fn init(arena: Allocator, 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),
|
||||
.arena = arena,
|
||||
.ignore_list = .{},
|
||||
.list_pool = .init(arena),
|
||||
.listener_pool = .init(arena),
|
||||
.dispatch_depth = 0,
|
||||
.deferred_removals = .{},
|
||||
.has_dom_load_listener = false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -69,7 +100,7 @@ pub const Callback = union(enum) {
|
||||
|
||||
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 });
|
||||
log.debug(.event, "eventManager.register", .{ .type = typ, .capture = opts.capture, .once = opts.once, .target = target.toString() });
|
||||
}
|
||||
|
||||
// If a signal is provided and already aborted, don't register the listener
|
||||
@@ -79,20 +110,28 @@ pub fn register(self: *EventManager, target: *EventTarget, typ: []const u8, call
|
||||
}
|
||||
}
|
||||
|
||||
const gop = try self.lookup.getOrPut(self.arena, @intFromPtr(target));
|
||||
// Allocate the type string we'll use in both listener and key
|
||||
const type_string = try String.init(self.arena, typ, .{});
|
||||
|
||||
if (type_string.eql(comptime .wrap("load")) and target._type == .node) {
|
||||
self.has_dom_load_listener = true;
|
||||
}
|
||||
|
||||
const gop = try self.lookup.getOrPut(self.arena, .{
|
||||
.type_string = type_string,
|
||||
.event_target = @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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -114,51 +153,67 @@ pub fn register(self: *EventManager, target: *EventTarget, typ: []const u8, call
|
||||
.passive = opts.passive,
|
||||
.function = func,
|
||||
.signal = opts.signal,
|
||||
.typ = try String.init(self.arena, typ, .{}),
|
||||
.typ = type_string,
|
||||
};
|
||||
// append the listener to the list of listeners for this target
|
||||
gop.value_ptr.*.append(&listener.node);
|
||||
|
||||
// Track load listeners for script execution ignore list
|
||||
if (type_string.eql(comptime .wrap("load"))) {
|
||||
try self.ignore_list.append(self.arena, listener);
|
||||
}
|
||||
}
|
||||
|
||||
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| {
|
||||
const list = self.lookup.get(.{
|
||||
.type_string = .wrap(typ),
|
||||
.event_target = @intFromPtr(target),
|
||||
}) orelse return;
|
||||
if (findListener(list, callback, use_capture)) |listener| {
|
||||
self.removeListener(list, listener);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dispatch(self: *EventManager, target: *EventTarget, event: *Event) !void {
|
||||
pub fn clearIgnoreList(self: *EventManager) void {
|
||||
self.ignore_list.clearRetainingCapacity();
|
||||
}
|
||||
|
||||
// Dispatching can be recursive from the compiler's point of view, so we need to
|
||||
// give it an explicit error set so that other parts of the code can use and
|
||||
// inferred error.
|
||||
const DispatchError = error{
|
||||
OutOfMemory,
|
||||
StringTooLarge,
|
||||
JSExecCallback,
|
||||
CompilationError,
|
||||
ExecutionError,
|
||||
JsException,
|
||||
};
|
||||
|
||||
pub const DispatchOpts = struct {
|
||||
// A "load" event triggered by a script (in ScriptManager) should not trigger
|
||||
// a "load" listener added within that script. Therefore, any "load" listener
|
||||
// that we add go into an ignore list until after the script finishes executing.
|
||||
// The ignore list is only checked when apply_ignore == true, which is only
|
||||
// set by the ScriptManager when raising the script's "load" event.
|
||||
apply_ignore: bool = false,
|
||||
};
|
||||
|
||||
pub fn dispatch(self: *EventManager, target: *EventTarget, event: *Event) DispatchError!void {
|
||||
return self.dispatchOpts(target, event, .{});
|
||||
}
|
||||
|
||||
pub fn dispatchOpts(self: *EventManager, target: *EventTarget, event: *Event, comptime opts: DispatchOpts) DispatchError!void {
|
||||
event.acquireRef();
|
||||
defer event.deinit(false, self.page);
|
||||
|
||||
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) {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
self.page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
ls.local.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);
|
||||
},
|
||||
.node => |node| try self.dispatchNode(node, event, opts),
|
||||
else => try self.dispatchDirect(target, event, null, .{ .context = "dispatch" }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,13 +222,22 @@ pub fn dispatch(self: *EventManager, target: *EventTarget, event: *Event) !void
|
||||
// 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 {
|
||||
const DispatchDirectOptions = struct {
|
||||
context: []const u8,
|
||||
inject_target: bool = true,
|
||||
};
|
||||
pub fn dispatchWithFunction(self: *EventManager, target: *EventTarget, event: *Event, function_: ?js.Function, comptime opts: DispatchWithFunctionOptions) !void {
|
||||
|
||||
// Direct dispatch for non-DOM targets (Window, XHR, AbortSignal) or DOM nodes with
|
||||
// property handlers. No propagation - just calls the handler and registered listeners.
|
||||
// Handler can be: null, ?js.Function.Global, ?js.Function.Temp, or js.Function
|
||||
pub fn dispatchDirect(self: *EventManager, target: *EventTarget, event: *Event, handler: anytype, comptime opts: DispatchDirectOptions) !void {
|
||||
const page = self.page;
|
||||
|
||||
event.acquireRef();
|
||||
defer event.deinit(false, page);
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.event, "dispatchWithFunction", .{ .type = event._type_string.str(), .context = opts.context, .has_function = function_ != null });
|
||||
log.debug(.event, "dispatchDirect", .{ .type = event._type_string, .context = opts.context });
|
||||
}
|
||||
|
||||
if (comptime opts.inject_target) {
|
||||
@@ -182,14 +246,15 @@ pub fn dispatchWithFunction(self: *EventManager, target: *EventTarget, event: *E
|
||||
}
|
||||
|
||||
var was_dispatched = false;
|
||||
defer if (was_dispatched) {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
self.page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
ls.local.runMicrotasks();
|
||||
};
|
||||
|
||||
if (function_) |func| {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
page.js.localScope(&ls);
|
||||
defer {
|
||||
ls.local.runMicrotasks();
|
||||
ls.deinit();
|
||||
}
|
||||
|
||||
if (getFunction(handler, &ls.local)) |func| {
|
||||
event._current_target = target;
|
||||
if (func.callWithThis(void, target, .{event})) {
|
||||
was_dispatched = true;
|
||||
@@ -199,110 +264,15 @@ pub fn dispatchWithFunction(self: *EventManager, target: *EventTarget, event: *E
|
||||
}
|
||||
}
|
||||
|
||||
const list = self.lookup.get(@intFromPtr(target)) orelse return;
|
||||
try self.dispatchAll(list, target, event, &was_dispatched);
|
||||
}
|
||||
// listeners reigstered via addEventListener
|
||||
const list = self.lookup.get(.{
|
||||
.event_target = @intFromPtr(target),
|
||||
.type_string = event._type_string,
|
||||
}) orelse return;
|
||||
|
||||
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;
|
||||
// This is a slightly simplified version of what you'll find in dispatchPhase
|
||||
// It is simpler because, for direct dispatching, we know there's no ancestors
|
||||
// and only the single target phase.
|
||||
|
||||
// Track dispatch depth for deferred removal
|
||||
self.dispatch_depth += 1;
|
||||
@@ -336,16 +306,6 @@ fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_targe
|
||||
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;
|
||||
@@ -364,6 +324,281 @@ fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_targe
|
||||
self.removeListener(list, listener);
|
||||
}
|
||||
|
||||
was_dispatched = true;
|
||||
event._current_target = target;
|
||||
|
||||
switch (listener.function) {
|
||||
.value => |value| try ls.toLocal(value).callWithThis(void, target, .{event}),
|
||||
.string => |string| {
|
||||
const str = try page.call_arena.dupeZ(u8, string.str());
|
||||
try ls.local.eval(str, null);
|
||||
},
|
||||
.object => |obj_global| {
|
||||
const obj = ls.toLocal(obj_global);
|
||||
if (try obj.getFunction("handleEvent")) |handleEvent| {
|
||||
try handleEvent.callWithThis(void, obj, .{event});
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
if (event._stop_immediate_propagation) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn getFunction(handler: anytype, local: *const js.Local) ?js.Function {
|
||||
const T = @TypeOf(handler);
|
||||
const ti = @typeInfo(T);
|
||||
|
||||
if (ti == .null) {
|
||||
return null;
|
||||
}
|
||||
if (ti == .optional) {
|
||||
return getFunction(handler orelse return null, local);
|
||||
}
|
||||
return switch (T) {
|
||||
js.Function => handler,
|
||||
js.Function.Temp => local.toLocal(handler),
|
||||
js.Function.Global => local.toLocal(handler),
|
||||
else => @compileError("handler must be null or \\??js.Function(\\.(Temp|Global))?"),
|
||||
};
|
||||
}
|
||||
|
||||
fn dispatchNode(self: *EventManager, target: *Node, event: *Event, comptime opts: DispatchOpts) !void {
|
||||
const ShadowRoot = @import("webapi/ShadowRoot.zig");
|
||||
|
||||
{
|
||||
const et = target.asEventTarget();
|
||||
event._target = et;
|
||||
event._dispatch_target = et; // Store original target for composedPath()
|
||||
}
|
||||
|
||||
const page = self.page;
|
||||
var was_handled = false;
|
||||
|
||||
// Create a single scope for all event handlers in this dispatch.
|
||||
// This ensures function handles passed to queueMicrotask remain valid
|
||||
// throughout the entire dispatch, preventing crashes when microtasks run.
|
||||
var ls: js.Local.Scope = undefined;
|
||||
page.js.localScope(&ls);
|
||||
defer {
|
||||
if (was_handled) {
|
||||
ls.local.runMicrotasks();
|
||||
}
|
||||
ls.deinit();
|
||||
}
|
||||
|
||||
const activation_state = ActivationState.create(event, target, page);
|
||||
|
||||
// Defer runs even on early return - ensures event phase is reset
|
||||
// and default actions execute (unless prevented)
|
||||
defer {
|
||||
event._event_phase = .none;
|
||||
event._stop_propagation = false;
|
||||
event._stop_immediate_propagation = false;
|
||||
// Handle checkbox/radio activation rollback or commit
|
||||
if (activation_state) |state| {
|
||||
state.restore(event, page);
|
||||
}
|
||||
|
||||
// Execute default action if not prevented
|
||||
if (event._prevent_default) {
|
||||
// can't return in a defer (╯°□°)╯︵ ┻━┻
|
||||
} else if (event._type_string.eql(comptime .wrap("click"))) {
|
||||
page.handleClick(target) catch |err| {
|
||||
log.warn(.event, "page.click", .{ .err = err });
|
||||
};
|
||||
} else if (event._type_string.eql(comptime .wrap("keydown"))) {
|
||||
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, most events propagate
|
||||
// through it in the capture phase (unless we stopped at a shadow boundary)
|
||||
// The only explicit exception is "load"
|
||||
if (event._type_string.eql(comptime .wrap("load")) == false) {
|
||||
if (path_len < path_buffer.len) {
|
||||
path_buffer[path_len] = 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;
|
||||
if (event._stop_propagation) return;
|
||||
const current_target = path[i];
|
||||
if (self.lookup.get(.{
|
||||
.event_target = @intFromPtr(current_target),
|
||||
.type_string = event._type_string,
|
||||
})) |list| {
|
||||
try self.dispatchPhase(list, current_target, event, &was_handled, &ls.local, comptime .init(true, opts));
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: At target
|
||||
if (event._stop_propagation) return;
|
||||
event._event_phase = .at_target;
|
||||
const target_et = target.asEventTarget();
|
||||
|
||||
blk: {
|
||||
// Get inline handler (e.g., onclick property) for this target
|
||||
if (self.getInlineHandler(target_et, event)) |inline_handler| {
|
||||
was_handled = true;
|
||||
event._current_target = target_et;
|
||||
|
||||
try ls.toLocal(inline_handler).callWithThis(void, target_et, .{event});
|
||||
|
||||
if (event._stop_propagation) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event._stop_immediate_propagation) {
|
||||
break :blk;
|
||||
}
|
||||
}
|
||||
|
||||
if (self.lookup.get(.{
|
||||
.type_string = event._type_string,
|
||||
.event_target = @intFromPtr(target_et),
|
||||
})) |list| {
|
||||
try self.dispatchPhase(list, target_et, event, &was_handled, &ls.local, comptime .init(null, opts));
|
||||
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 (event._stop_propagation) break;
|
||||
if (self.lookup.get(.{
|
||||
.type_string = event._type_string,
|
||||
.event_target = @intFromPtr(current_target),
|
||||
})) |list| {
|
||||
try self.dispatchPhase(list, current_target, event, &was_handled, &ls.local, comptime .init(false, opts));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DispatchPhaseOpts = struct {
|
||||
capture_only: ?bool = null,
|
||||
apply_ignore: bool = false,
|
||||
|
||||
fn init(capture_only: ?bool, opts: DispatchOpts) DispatchPhaseOpts {
|
||||
return .{
|
||||
.capture_only = capture_only,
|
||||
.apply_ignore = opts.apply_ignore,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_target: *EventTarget, event: *Event, was_handled: *bool, local: *const js.Local, comptime opts: DispatchPhaseOpts) !void {
|
||||
const page = self.page;
|
||||
|
||||
// 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;
|
||||
node_loop: 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 (comptime opts.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;
|
||||
}
|
||||
}
|
||||
|
||||
if (comptime opts.apply_ignore) {
|
||||
for (self.ignore_list.items) |ignored| {
|
||||
if (ignored == listener) {
|
||||
continue :node_loop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
@@ -373,18 +608,14 @@ fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_targe
|
||||
event._target = getAdjustedTarget(original_target, current_target);
|
||||
}
|
||||
|
||||
var ls: js.Local.Scope = undefined;
|
||||
page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
|
||||
switch (listener.function) {
|
||||
.value => |value| try ls.toLocal(value).callWithThis(void, current_target, .{event}),
|
||||
.value => |value| try local.toLocal(value).callWithThis(void, current_target, .{event}),
|
||||
.string => |string| {
|
||||
const str = try page.call_arena.dupeZ(u8, string.str());
|
||||
try ls.local.eval(str, null);
|
||||
try local.eval(str, null);
|
||||
},
|
||||
.object => |obj_global| {
|
||||
const obj = ls.toLocal(obj_global);
|
||||
const obj = local.toLocal(obj_global);
|
||||
if (try obj.getFunction("handleEvent")) |handleEvent| {
|
||||
try handleEvent.callWithThis(void, obj, .{event});
|
||||
}
|
||||
@@ -402,9 +633,20 @@ fn dispatchPhase(self: *EventManager, list: *std.DoublyLinkedList, current_targe
|
||||
}
|
||||
}
|
||||
|
||||
// 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 getInlineHandler(self: *EventManager, target: *EventTarget, event: *Event) ?js.Function.Global {
|
||||
const global_event_handlers = @import("webapi/global_event_handlers.zig");
|
||||
const handler_type = global_event_handlers.fromEventType(event._type_string.str()) orelse return null;
|
||||
|
||||
// Look up the inline handler for this target
|
||||
const html_element = switch (target._type) {
|
||||
.node => |n| n.is(Element.Html) orelse return null,
|
||||
else => return null,
|
||||
};
|
||||
|
||||
return html_element.getAttributeFunction(handler_type, self.page) catch |err| {
|
||||
log.warn(.event, "inline html callback", .{ .type = handler_type, .err = err });
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
fn removeListener(self: *EventManager, list: *std.DoublyLinkedList, listener: *Listener) void {
|
||||
@@ -419,7 +661,7 @@ fn removeListener(self: *EventManager, list: *std.DoublyLinkedList, listener: *L
|
||||
}
|
||||
}
|
||||
|
||||
fn findListener(list: *const std.DoublyLinkedList, typ: []const u8, callback: Callback, capture: bool) ?*Listener {
|
||||
fn findListener(list: *const std.DoublyLinkedList, callback: Callback, capture: bool) ?*Listener {
|
||||
var node = list.first;
|
||||
while (node) |n| {
|
||||
node = n.next;
|
||||
@@ -434,9 +676,6 @@ fn findListener(list: *const std.DoublyLinkedList, typ: []const u8, callback: Ca
|
||||
if (listener.capture != capture) {
|
||||
continue;
|
||||
}
|
||||
if (!listener.typ.eqlSlice(typ)) {
|
||||
continue;
|
||||
}
|
||||
return listener;
|
||||
}
|
||||
return null;
|
||||
@@ -525,3 +764,144 @@ fn isAncestorOrSelf(ancestor: *Node, node: *Node) bool {
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Handles the default action for clicking on input checked/radio. Maybe this
|
||||
// could be generalized if needed, but I'm not sure. This wasn't obvious to me
|
||||
// but when an input is clicked, it's important to think about both the intent
|
||||
// and the actual result. Imagine you have an unchecked checkbox. When clicked,
|
||||
// the checkbox immediately becomes checked, and event handlers see this "checked"
|
||||
// intent. But a listener can preventDefault() in which case the check we did at
|
||||
// the start will be undone.
|
||||
// This is a bit more complicated for radio buttons, as the checking/unchecking
|
||||
// and the rollback can impact a different radio input. So if you "check" a radio
|
||||
// the intent is that it becomes checked and whatever was checked before becomes
|
||||
// unchecked, so that if you have to rollback (because of a preventDefault())
|
||||
// then both inputs have to revert to their original values.
|
||||
const ActivationState = struct {
|
||||
old_checked: bool,
|
||||
input: *Element.Html.Input,
|
||||
previously_checked_radio: ?*Input,
|
||||
|
||||
const Input = Element.Html.Input;
|
||||
|
||||
fn create(event: *const Event, target: *Node, page: *Page) ?ActivationState {
|
||||
if (event._type_string.eql(comptime .wrap("click")) == false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const input = target.is(Element.Html.Input) orelse return null;
|
||||
if (input._input_type != .checkbox and input._input_type != .radio) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const old_checked = input._checked;
|
||||
var previously_checked_radio: ?*Element.Html.Input = null;
|
||||
|
||||
// For radio buttons, find the currently checked radio in the group
|
||||
if (input._input_type == .radio and !old_checked) {
|
||||
previously_checked_radio = try findCheckedRadioInGroup(input, page);
|
||||
}
|
||||
|
||||
// Toggle checkbox or check radio (which unchecks others in group)
|
||||
const new_checked = if (input._input_type == .checkbox) !old_checked else true;
|
||||
try input.setChecked(new_checked, page);
|
||||
|
||||
return .{
|
||||
.input = input,
|
||||
.old_checked = old_checked,
|
||||
.previously_checked_radio = previously_checked_radio,
|
||||
};
|
||||
}
|
||||
|
||||
fn restore(self: *const ActivationState, event: *const Event, page: *Page) void {
|
||||
const input = self.input;
|
||||
if (event._prevent_default) {
|
||||
// Rollback: restore previous state
|
||||
input._checked = self.old_checked;
|
||||
input._checked_dirty = true;
|
||||
if (self.previously_checked_radio) |prev_radio| {
|
||||
prev_radio._checked = true;
|
||||
prev_radio._checked_dirty = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Commit: fire input and change events only if state actually changed
|
||||
// and the element is connected to a document (detached elements don't fire).
|
||||
// For checkboxes, state always changes. For radios, only if was unchecked.
|
||||
const state_changed = (input._input_type == .checkbox) or !self.old_checked;
|
||||
if (state_changed and input.asElement().asNode().isConnected()) {
|
||||
fireEvent(page, input, "input") catch |err| {
|
||||
log.warn(.event, "input event", .{ .err = err });
|
||||
};
|
||||
fireEvent(page, input, "change") catch |err| {
|
||||
log.warn(.event, "change event", .{ .err = err });
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn findCheckedRadioInGroup(input: *Input, page: *Page) !?*Input {
|
||||
const elem = input.asElement();
|
||||
|
||||
const name = elem.getAttributeSafe(comptime .wrap("name")) orelse return null;
|
||||
if (name.len == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const form = input.getForm(page);
|
||||
|
||||
// Walk from the root of the tree containing this element
|
||||
// This handles both document-attached and orphaned elements
|
||||
const root = elem.asNode().getRootNode(null);
|
||||
|
||||
const TreeWalker = @import("webapi/TreeWalker.zig");
|
||||
var walker = TreeWalker.Full.init(root, .{});
|
||||
|
||||
while (walker.next()) |node| {
|
||||
const other_element = node.is(Element) orelse continue;
|
||||
const other_input = other_element.is(Input) orelse continue;
|
||||
|
||||
if (other_input._input_type != .radio) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip the input we're checking from
|
||||
if (other_input == input) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const other_name = other_element.getAttributeSafe(comptime .wrap("name")) orelse continue;
|
||||
if (!std.mem.eql(u8, name, other_name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if same form context
|
||||
const other_form = other_input.getForm(page);
|
||||
if (form) |f| {
|
||||
const of = other_form orelse continue;
|
||||
if (f != of) {
|
||||
continue; // Different forms
|
||||
}
|
||||
} else if (other_form != null) {
|
||||
continue; // form is null but other has a form
|
||||
}
|
||||
|
||||
if (other_input._checked) {
|
||||
return other_input;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Fire input or change event
|
||||
fn fireEvent(page: *Page, input: *Input, comptime typ: []const u8) !void {
|
||||
const event = try Event.initTrusted(comptime .wrap(typ), .{
|
||||
.bubbles = true,
|
||||
.cancelable = false,
|
||||
}, page);
|
||||
|
||||
const target = input.asElement().asEventTarget();
|
||||
try page._event_manager.dispatch(target, event);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -42,10 +42,96 @@ const Allocator = std.mem.Allocator;
|
||||
const IS_DEBUG = builtin.mode == .Debug;
|
||||
const assert = std.debug.assert;
|
||||
|
||||
// Shared across all frames of a Page.
|
||||
const Factory = @This();
|
||||
_page: *Page,
|
||||
|
||||
_arena: Allocator,
|
||||
_slab: SlabAllocator,
|
||||
|
||||
pub fn init(arena: Allocator) !*Factory {
|
||||
const self = try arena.create(Factory);
|
||||
self.* = .{
|
||||
._arena = arena,
|
||||
._slab = SlabAllocator.init(arena, 128),
|
||||
};
|
||||
return self;
|
||||
}
|
||||
|
||||
// this is a root object
|
||||
pub fn eventTarget(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
return self.eventTargetWithAllocator(self._slab.allocator(), child);
|
||||
}
|
||||
|
||||
pub fn eventTargetWithAllocator(_: *const Factory, allocator: Allocator, child: anytype) !*@TypeOf(child) {
|
||||
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);
|
||||
}
|
||||
|
||||
pub fn standaloneEventTarget(self: *Factory, child: anytype) !*EventTarget {
|
||||
const allocator = self._slab.allocator();
|
||||
const et = try allocator.create(EventTarget);
|
||||
et.* = .{ ._type = unionInit(EventTarget.Type, child) };
|
||||
return et;
|
||||
}
|
||||
|
||||
// this is a root object
|
||||
pub fn event(_: *const Factory, arena: Allocator, typ: String, child: anytype) !*@TypeOf(child) {
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, @TypeOf(child) },
|
||||
).allocate(arena);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try eventInit(arena, typ, chain.get(1));
|
||||
chain.setLeaf(1, child);
|
||||
|
||||
return chain.get(1);
|
||||
}
|
||||
|
||||
pub fn uiEvent(_: *const Factory, arena: Allocator, typ: String, child: anytype) !*@TypeOf(child) {
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, UIEvent, @TypeOf(child) },
|
||||
).allocate(arena);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try eventInit(arena, typ, chain.get(1));
|
||||
chain.setMiddle(1, UIEvent.Type);
|
||||
chain.setLeaf(2, child);
|
||||
|
||||
return chain.get(2);
|
||||
}
|
||||
|
||||
pub fn mouseEvent(_: *const Factory, arena: Allocator, typ: String, mouse: MouseEvent, child: anytype) !*@TypeOf(child) {
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, UIEvent, MouseEvent, @TypeOf(child) },
|
||||
).allocate(arena);
|
||||
|
||||
// Special case: Event has a _type_string field, so we need manual setup
|
||||
const event_ptr = chain.get(0);
|
||||
event_ptr.* = try eventInit(arena, typ, chain.get(1));
|
||||
chain.setMiddle(1, UIEvent.Type);
|
||||
|
||||
// Set MouseEvent with all its fields
|
||||
const mouse_ptr = chain.get(2);
|
||||
mouse_ptr.* = mouse;
|
||||
mouse_ptr._proto = chain.get(1);
|
||||
mouse_ptr._type = unionInit(MouseEvent.Type, chain.get(3));
|
||||
|
||||
chain.setLeaf(3, child);
|
||||
|
||||
return chain.get(3);
|
||||
}
|
||||
|
||||
fn PrototypeChain(comptime types: []const type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
@@ -149,96 +235,20 @@ fn AutoPrototypeChain(comptime types: []const type) type {
|
||||
};
|
||||
}
|
||||
|
||||
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 {
|
||||
fn eventInit(arena: Allocator, typ: String, value: anytype) !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 .{
|
||||
._rc = 0,
|
||||
._arena = arena,
|
||||
._type = unionInit(Event.Type, value),
|
||||
._type_string = try String.init(page.arena, typ, .{}),
|
||||
._type_string = 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 mouseEvent(self: *Factory, typ: []const u8, mouse: MouseEvent, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
|
||||
const chain = try PrototypeChain(
|
||||
&.{ Event, UIEvent, MouseEvent, @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);
|
||||
|
||||
// Set MouseEvent with all its fields
|
||||
const mouse_ptr = chain.get(2);
|
||||
mouse_ptr.* = mouse;
|
||||
mouse_ptr._proto = chain.get(1);
|
||||
mouse_ptr._type = unionInit(MouseEvent.Type, chain.get(3));
|
||||
|
||||
chain.setLeaf(3, child);
|
||||
|
||||
return chain.get(3);
|
||||
}
|
||||
|
||||
pub fn blob(self: *Factory, child: anytype) !*@TypeOf(child) {
|
||||
const allocator = self._slab.allocator();
|
||||
|
||||
@@ -333,7 +343,7 @@ pub fn svgElement(self: *Factory, tag_name: []const u8, child: anytype) !*@TypeO
|
||||
chain.setMiddle(2, Element.Type);
|
||||
|
||||
// will never allocate, can't fail
|
||||
const tag_name_str = String.init(self._page.arena, tag_name, .{}) catch unreachable;
|
||||
const tag_name_str = String.init(self._arena, tag_name, .{}) catch unreachable;
|
||||
|
||||
// Manually set Element.Svg with the tag_name
|
||||
chain.set(3, .{
|
||||
@@ -378,7 +388,7 @@ pub fn destroy(self: *Factory, value: anytype) void {
|
||||
}
|
||||
|
||||
if (comptime @hasField(S, "_proto")) {
|
||||
self.destroyChain(value, true, 0, std.mem.Alignment.@"1");
|
||||
self.destroyChain(value, 0, std.mem.Alignment.@"1");
|
||||
} else {
|
||||
self.destroyStandalone(value);
|
||||
}
|
||||
@@ -392,7 +402,6 @@ pub fn destroyStandalone(self: *Factory, value: anytype) void {
|
||||
fn destroyChain(
|
||||
self: *Factory,
|
||||
value: anytype,
|
||||
comptime first: bool,
|
||||
old_size: usize,
|
||||
old_align: std.mem.Alignment,
|
||||
) void {
|
||||
@@ -404,23 +413,8 @@ fn destroyChain(
|
||||
const new_size = current_size + @sizeOf(S);
|
||||
const new_align = std.mem.Alignment.max(old_align, std.mem.Alignment.of(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);
|
||||
self.destroyChain(value._proto, new_size, new_align);
|
||||
} else {
|
||||
// no proto so this is the head of the chain.
|
||||
// we use this as the ptr to the start of the chain.
|
||||
|
||||
@@ -24,10 +24,11 @@ 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,
|
||||
charset_len: usize = default_charset_len,
|
||||
|
||||
/// String "UTF-8" continued by null characters.
|
||||
pub const default_charset = .{ 'U', 'T', 'F', '-', '8' } ++ .{0} ** 36;
|
||||
const default_charset = .{ 'U', 'T', 'F', '-', '8' } ++ .{0} ** 36;
|
||||
const default_charset_len = 5;
|
||||
|
||||
/// Mime with unknown Content-Type, empty params and empty charset.
|
||||
pub const unknown = Mime{ .content_type = .{ .unknown = {} } };
|
||||
@@ -38,6 +39,10 @@ pub const ContentTypeEnum = enum {
|
||||
text_javascript,
|
||||
text_plain,
|
||||
text_css,
|
||||
image_jpeg,
|
||||
image_gif,
|
||||
image_png,
|
||||
image_webp,
|
||||
application_json,
|
||||
unknown,
|
||||
other,
|
||||
@@ -49,6 +54,10 @@ pub const ContentType = union(ContentTypeEnum) {
|
||||
text_javascript: void,
|
||||
text_plain: void,
|
||||
text_css: void,
|
||||
image_jpeg: void,
|
||||
image_gif: void,
|
||||
image_png: void,
|
||||
image_webp: void,
|
||||
application_json: void,
|
||||
unknown: void,
|
||||
other: struct { type: []const u8, sub_type: []const u8 },
|
||||
@@ -61,6 +70,10 @@ pub fn contentTypeString(mime: *const Mime) []const u8 {
|
||||
.text_javascript => "application/javascript",
|
||||
.text_plain => "text/plain",
|
||||
.text_css => "text/css",
|
||||
.image_jpeg => "image/jpeg",
|
||||
.image_png => "image/png",
|
||||
.image_gif => "image/gif",
|
||||
.image_webp => "image/webp",
|
||||
.application_json => "application/json",
|
||||
else => "",
|
||||
};
|
||||
@@ -115,17 +128,17 @@ pub fn parse(input: []u8) !Mime {
|
||||
|
||||
const params = trimLeft(normalized[type_len..]);
|
||||
|
||||
var charset: [41]u8 = undefined;
|
||||
var charset_len: usize = undefined;
|
||||
var charset: [41]u8 = default_charset;
|
||||
var charset_len: usize = default_charset_len;
|
||||
|
||||
var it = std.mem.splitScalar(u8, params, ';');
|
||||
while (it.next()) |attr| {
|
||||
const i = std.mem.indexOfScalarPos(u8, attr, 0, '=') orelse return error.Invalid;
|
||||
const i = std.mem.indexOfScalarPos(u8, attr, 0, '=') orelse continue;
|
||||
const name = trimLeft(attr[0..i]);
|
||||
|
||||
const value = trimRight(attr[i + 1 ..]);
|
||||
if (value.len == 0) {
|
||||
return error.Invalid;
|
||||
continue;
|
||||
}
|
||||
|
||||
const attribute_name = std.meta.stringToEnum(enum {
|
||||
@@ -138,7 +151,7 @@ pub fn parse(input: []u8) !Mime {
|
||||
break;
|
||||
}
|
||||
|
||||
const attribute_value = try parseCharset(value);
|
||||
const attribute_value = parseCharset(value) catch continue;
|
||||
@memcpy(charset[0..attribute_value.len], attribute_value);
|
||||
// Null-terminate right after attribute value.
|
||||
charset[attribute_value.len] = 0;
|
||||
@@ -243,6 +256,11 @@ fn parseContentType(value: []const u8) !struct { ContentType, usize } {
|
||||
@"application/javascript",
|
||||
@"application/x-javascript",
|
||||
|
||||
@"image/jpeg",
|
||||
@"image/png",
|
||||
@"image/gif",
|
||||
@"image/webp",
|
||||
|
||||
@"application/json",
|
||||
}, type_name)) |known_type| {
|
||||
const ct: ContentType = switch (known_type) {
|
||||
@@ -251,6 +269,10 @@ fn parseContentType(value: []const u8) !struct { ContentType, usize } {
|
||||
.@"text/javascript", .@"application/javascript", .@"application/x-javascript" => .{ .text_javascript = {} },
|
||||
.@"text/plain" => .{ .text_plain = {} },
|
||||
.@"text/css" => .{ .text_css = {} },
|
||||
.@"image/jpeg" => .{ .image_jpeg = {} },
|
||||
.@"image/png" => .{ .image_png = {} },
|
||||
.@"image/gif" => .{ .image_gif = {} },
|
||||
.@"image/webp" => .{ .image_webp = {} },
|
||||
.@"application/json" => .{ .application_json = {} },
|
||||
};
|
||||
return .{ ct, attribute_start };
|
||||
@@ -313,6 +335,19 @@ test "Mime: invalid" {
|
||||
"text/ html",
|
||||
"text / html",
|
||||
"text/html other",
|
||||
};
|
||||
|
||||
for (invalids) |invalid| {
|
||||
const mutable_input = try testing.arena_allocator.dupe(u8, invalid);
|
||||
try testing.expectError(error.Invalid, Mime.parse(mutable_input));
|
||||
}
|
||||
}
|
||||
|
||||
test "Mime: malformed parameters are ignored" {
|
||||
defer testing.reset();
|
||||
|
||||
// These should all parse successfully as text/html with malformed params ignored
|
||||
const valid_with_malformed_params = [_][]const u8{
|
||||
"text/html; x",
|
||||
"text/html; x=",
|
||||
"text/html; x= ",
|
||||
@@ -321,11 +356,13 @@ test "Mime: invalid" {
|
||||
"text/html; charset=\"\"",
|
||||
"text/html; charset=\"",
|
||||
"text/html; charset=\"\\",
|
||||
"text/html;\"",
|
||||
};
|
||||
|
||||
for (invalids) |invalid| {
|
||||
const mutable_input = try testing.arena_allocator.dupe(u8, invalid);
|
||||
try testing.expectError(error.Invalid, Mime.parse(mutable_input));
|
||||
for (valid_with_malformed_params) |input| {
|
||||
const mutable_input = try testing.arena_allocator.dupe(u8, input);
|
||||
const mime = try Mime.parse(mutable_input);
|
||||
try testing.expectEqual(.text_html, std.meta.activeTag(mime.content_type));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,6 +395,11 @@ test "Mime: parse common" {
|
||||
|
||||
try expect(.{ .content_type = .{ .application_json = {} } }, "application/json");
|
||||
try expect(.{ .content_type = .{ .text_css = {} } }, "text/css");
|
||||
|
||||
try expect(.{ .content_type = .{ .image_jpeg = {} } }, "image/jpeg");
|
||||
try expect(.{ .content_type = .{ .image_png = {} } }, "image/png");
|
||||
try expect(.{ .content_type = .{ .image_gif = {} } }, "image/gif");
|
||||
try expect(.{ .content_type = .{ .image_webp = {} } }, "image/webp");
|
||||
}
|
||||
|
||||
test "Mime: parse uncommon" {
|
||||
@@ -409,6 +451,12 @@ test "Mime: parse charset" {
|
||||
.charset = "custom-non-standard-charset-value",
|
||||
.params = "charset=\"custom-non-standard-charset-value\"",
|
||||
}, "text/xml;charset=\"custom-non-standard-charset-value\"");
|
||||
|
||||
try expect(.{
|
||||
.content_type = .{ .text_html = {} },
|
||||
.charset = "UTF-8",
|
||||
.params = "x=\"",
|
||||
}, "text/html;x=\"");
|
||||
}
|
||||
|
||||
test "Mime: isHTML" {
|
||||
|
||||
1536
src/browser/Page.zig
1536
src/browser/Page.zig
File diff suppressed because it is too large
Load Diff
1003
src/browser/Robots.zig
Normal file
1003
src/browser/Robots.zig
Normal file
File diff suppressed because it is too large
Load Diff
@@ -20,18 +20,19 @@ const std = @import("std");
|
||||
const lp = @import("lightpanda");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const js = @import("js/js.zig");
|
||||
const log = @import("../log.zig");
|
||||
const Http = @import("../http/Http.zig");
|
||||
const String = @import("../string.zig").String;
|
||||
|
||||
const js = @import("js/js.zig");
|
||||
const URL = @import("URL.zig");
|
||||
const Page = @import("Page.zig");
|
||||
const Browser = @import("Browser.zig");
|
||||
const Http = @import("../http/Http.zig");
|
||||
|
||||
const Element = @import("webapi/Element.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const ArrayListUnmanaged = std.ArrayListUnmanaged;
|
||||
const ArrayList = std.ArrayList;
|
||||
|
||||
const IS_DEBUG = builtin.mode == .Debug;
|
||||
|
||||
@@ -83,10 +84,11 @@ imported_modules: std.StringHashMapUnmanaged(ImportedModule),
|
||||
// importmap contains resolved urls.
|
||||
importmap: std.StringHashMapUnmanaged([:0]const u8),
|
||||
|
||||
pub fn init(page: *Page) ScriptManager {
|
||||
// page isn't fully initialized, we can setup our reference, but that's it.
|
||||
const browser = page._session.browser;
|
||||
const allocator = browser.allocator;
|
||||
// have we notified the page that all scripts are loaded (used to fire the "load"
|
||||
// event).
|
||||
page_notified_of_completion: bool,
|
||||
|
||||
pub fn init(allocator: Allocator, http_client: *Http.Client, page: *Page) ScriptManager {
|
||||
return .{
|
||||
.page = page,
|
||||
.async_scripts = .{},
|
||||
@@ -96,9 +98,10 @@ pub fn init(page: *Page) ScriptManager {
|
||||
.is_evaluating = false,
|
||||
.allocator = allocator,
|
||||
.imported_modules = .empty,
|
||||
.client = browser.http_client,
|
||||
.client = http_client,
|
||||
.static_scripts_done = false,
|
||||
.buffer_pool = BufferPool.init(allocator, 5),
|
||||
.page_notified_of_completion = false,
|
||||
.script_pool = std.heap.MemoryPool(Script).init(allocator),
|
||||
};
|
||||
}
|
||||
@@ -138,6 +141,12 @@ fn clearList(list: *std.DoublyLinkedList) void {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn getHeaders(self: *ScriptManager, url: [:0]const u8) !Http.Headers {
|
||||
var headers = try self.client.newHeaders();
|
||||
try self.page.headersForRequest(self.page.arena, url, &headers);
|
||||
return headers;
|
||||
}
|
||||
|
||||
pub fn addFromElement(self: *ScriptManager, comptime from_parser: bool, script_element: *Element.Html.Script, comptime ctx: []const u8) !void {
|
||||
if (script_element._executed) {
|
||||
// If a script tag gets dynamically created and added to the dom:
|
||||
@@ -252,17 +261,16 @@ pub fn addFromElement(self: *ScriptManager, comptime from_parser: bool, script_e
|
||||
script.deinit(true);
|
||||
}
|
||||
|
||||
var headers = try self.client.newHeaders();
|
||||
try page.requestCookie(.{}).headersForRequest(page.arena, url, &headers);
|
||||
|
||||
try self.client.request(.{
|
||||
.url = url,
|
||||
.ctx = script,
|
||||
.method = .GET,
|
||||
.headers = headers,
|
||||
.frame_id = page._frame_id,
|
||||
.headers = try self.getHeaders(url),
|
||||
.blocking = is_blocking,
|
||||
.cookie_jar = &page._session.cookie_jar,
|
||||
.resource_type = .script,
|
||||
.notification = page._session.notification,
|
||||
.start_callback = if (log.enabled(.http, .debug)) Script.startCallback else null,
|
||||
.header_callback = Script.headerCallback,
|
||||
.data_callback = Script.dataCallback,
|
||||
@@ -357,12 +365,11 @@ pub fn preloadImport(self: *ScriptManager, url: [:0]const u8, referrer: []const
|
||||
.manager = self,
|
||||
};
|
||||
|
||||
var headers = try self.client.newHeaders();
|
||||
try self.page.requestCookie(.{}).headersForRequest(self.page.arena, url, &headers);
|
||||
const page = self.page;
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
self.page.js.localScope(&ls);
|
||||
page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
|
||||
log.debug(.http, "script queue", .{
|
||||
@@ -377,9 +384,11 @@ pub fn preloadImport(self: *ScriptManager, url: [:0]const u8, referrer: []const
|
||||
.url = url,
|
||||
.ctx = script,
|
||||
.method = .GET,
|
||||
.headers = headers,
|
||||
.cookie_jar = &self.page._session.cookie_jar,
|
||||
.frame_id = page._frame_id,
|
||||
.headers = try self.getHeaders(url),
|
||||
.cookie_jar = &page._session.cookie_jar,
|
||||
.resource_type = .script,
|
||||
.notification = page._session.notification,
|
||||
.start_callback = if (log.enabled(.http, .debug)) Script.startCallback else null,
|
||||
.header_callback = Script.headerCallback,
|
||||
.data_callback = Script.dataCallback,
|
||||
@@ -452,12 +461,10 @@ pub fn getAsyncImport(self: *ScriptManager, url: [:0]const u8, cb: ImportAsync.C
|
||||
} },
|
||||
};
|
||||
|
||||
var headers = try self.client.newHeaders();
|
||||
try self.page.requestCookie(.{}).headersForRequest(self.page.arena, url, &headers);
|
||||
|
||||
const page = self.page;
|
||||
if (comptime IS_DEBUG) {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
self.page.js.localScope(&ls);
|
||||
page.js.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
|
||||
log.debug(.http, "script queue", .{
|
||||
@@ -480,10 +487,12 @@ pub fn getAsyncImport(self: *ScriptManager, url: [:0]const u8, cb: ImportAsync.C
|
||||
try self.client.request(.{
|
||||
.url = url,
|
||||
.method = .GET,
|
||||
.headers = headers,
|
||||
.frame_id = page._frame_id,
|
||||
.headers = try self.getHeaders(url),
|
||||
.ctx = script,
|
||||
.resource_type = .script,
|
||||
.cookie_jar = &self.page._session.cookie_jar,
|
||||
.cookie_jar = &page._session.cookie_jar,
|
||||
.notification = page._session.notification,
|
||||
.start_callback = if (log.enabled(.http, .debug)) Script.startCallback else null,
|
||||
.header_callback = Script.headerCallback,
|
||||
.data_callback = Script.dataCallback,
|
||||
@@ -567,19 +576,12 @@ fn evaluate(self: *ScriptManager) void {
|
||||
// Page makes this safe to call multiple times.
|
||||
page.documentIsLoaded();
|
||||
|
||||
if (self.async_scripts.first == null) {
|
||||
// Looks like all async scripts are done too!
|
||||
// Page makes this safe to call multiple times.
|
||||
page.documentIsComplete();
|
||||
if (self.async_scripts.first == null and self.page_notified_of_completion == false) {
|
||||
self.page_notified_of_completion = true;
|
||||
page.scriptsCompletedLoading();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn isDone(self: *const ScriptManager) bool {
|
||||
return self.static_scripts_done and // page is done processing initial html
|
||||
self.defer_scripts.first == null and // no deferred scripts
|
||||
self.async_scripts.first == null; // no async scripts
|
||||
}
|
||||
|
||||
fn parseImportmap(self: *ScriptManager, script: *const Script) !void {
|
||||
const content = script.source.content();
|
||||
|
||||
@@ -621,6 +623,20 @@ pub const Script = struct {
|
||||
script_element: ?*Element.Html.Script,
|
||||
manager: *ScriptManager,
|
||||
|
||||
// for debugging a rare production issue
|
||||
header_callback_called: bool = false,
|
||||
|
||||
// for debugging a rare production issue
|
||||
debug_transfer_id: u32 = 0,
|
||||
debug_transfer_tries: u8 = 0,
|
||||
debug_transfer_aborted: bool = false,
|
||||
debug_transfer_bytes_received: usize = 0,
|
||||
debug_transfer_notified_fail: bool = false,
|
||||
debug_transfer_redirecting: bool = false,
|
||||
debug_transfer_intercept_state: u8 = 0,
|
||||
debug_transfer_auth_challenge: bool = false,
|
||||
debug_transfer_easy_id: usize = 0,
|
||||
|
||||
const Kind = enum {
|
||||
module,
|
||||
javascript,
|
||||
@@ -634,7 +650,7 @@ pub const Script = struct {
|
||||
|
||||
const Source = union(enum) {
|
||||
@"inline": []const u8,
|
||||
remote: std.ArrayListUnmanaged(u8),
|
||||
remote: std.ArrayList(u8),
|
||||
|
||||
fn content(self: Source) []const u8 {
|
||||
return switch (self) {
|
||||
@@ -684,11 +700,44 @@ pub const Script = struct {
|
||||
});
|
||||
}
|
||||
|
||||
// If this isn't true, then we'll likely leak memory. If you don't
|
||||
// set `CURLOPT_SUPPRESS_CONNECT_HEADERS` and CONNECT to a proxy, this
|
||||
// will fail. This assertion exists to catch incorrect assumptions about
|
||||
// how libcurl works, or about how we've configured it.
|
||||
lp.assert(self.source.remote.capacity == 0, "ScriptManager.HeaderCallback", .{ .capacity = self.source.remote.capacity });
|
||||
{
|
||||
// temp debug, trying to figure out why the next assert sometimes
|
||||
// fails. Is the buffer just corrupt or is headerCallback really
|
||||
// being called twice?
|
||||
lp.assert(self.header_callback_called == false, "ScriptManager.Header recall", .{
|
||||
.m = @tagName(std.meta.activeTag(self.mode)),
|
||||
.a1 = self.debug_transfer_id,
|
||||
.a2 = self.debug_transfer_tries,
|
||||
.a3 = self.debug_transfer_aborted,
|
||||
.a4 = self.debug_transfer_bytes_received,
|
||||
.a5 = self.debug_transfer_notified_fail,
|
||||
.a6 = self.debug_transfer_redirecting,
|
||||
.a7 = self.debug_transfer_intercept_state,
|
||||
.a8 = self.debug_transfer_auth_challenge,
|
||||
.a9 = self.debug_transfer_easy_id,
|
||||
.b1 = transfer.id,
|
||||
.b2 = transfer._tries,
|
||||
.b3 = transfer.aborted,
|
||||
.b4 = transfer.bytes_received,
|
||||
.b5 = transfer._notified_fail,
|
||||
.b6 = transfer._redirecting,
|
||||
.b7 = @intFromEnum(transfer._intercept_state),
|
||||
.b8 = transfer._auth_challenge != null,
|
||||
.b9 = if (transfer._conn) |c| @intFromPtr(c.easy) else 0,
|
||||
});
|
||||
self.header_callback_called = true;
|
||||
self.debug_transfer_id = transfer.id;
|
||||
self.debug_transfer_tries = transfer._tries;
|
||||
self.debug_transfer_aborted = transfer.aborted;
|
||||
self.debug_transfer_bytes_received = transfer.bytes_received;
|
||||
self.debug_transfer_notified_fail = transfer._notified_fail;
|
||||
self.debug_transfer_redirecting = transfer._redirecting;
|
||||
self.debug_transfer_intercept_state = @intFromEnum(transfer._intercept_state);
|
||||
self.debug_transfer_auth_challenge = transfer._auth_challenge != null;
|
||||
self.debug_transfer_easy_id = if (transfer._conn) |c| @intFromPtr(c.easy) else 0;
|
||||
}
|
||||
|
||||
lp.assert(self.source.remote.capacity == 0, "ScriptManager.Header buffer", .{ .capacity = self.source.remote.capacity });
|
||||
var buffer = self.manager.buffer_pool.get();
|
||||
if (transfer.getContentLength()) |cl| {
|
||||
try buffer.ensureTotalCapacity(self.manager.allocator, cl);
|
||||
@@ -818,13 +867,15 @@ pub const Script = struct {
|
||||
.kind = self.kind,
|
||||
.cacheable = cacheable,
|
||||
});
|
||||
self.executeCallback("error", local.toLocal(script_element._on_error), page);
|
||||
self.executeCallback(comptime .wrap("error"), page);
|
||||
return;
|
||||
};
|
||||
self.executeCallback("load", local.toLocal(script_element._on_load), page);
|
||||
self.executeCallback(comptime .wrap("load"), page);
|
||||
return;
|
||||
}
|
||||
|
||||
defer page._event_manager.clearIgnoreList();
|
||||
|
||||
var try_catch: js.TryCatch = undefined;
|
||||
try_catch.init(local);
|
||||
defer try_catch.deinit();
|
||||
@@ -843,19 +894,18 @@ pub const Script = struct {
|
||||
};
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.browser, "executed script", .{ .src = url, .success = success, .on_load = script_element._on_load != null });
|
||||
log.debug(.browser, "executed script", .{ .src = url, .success = success });
|
||||
}
|
||||
|
||||
defer {
|
||||
// We should run microtasks even if script execution fails.
|
||||
local.runMicrotasks();
|
||||
_ = page.scheduler.run() catch |err| {
|
||||
local.runMacrotasks(); // also runs microtasks
|
||||
_ = page.js.scheduler.run() catch |err| {
|
||||
log.err(.page, "scheduler", .{ .err = err });
|
||||
};
|
||||
}
|
||||
|
||||
if (success) {
|
||||
self.executeCallback("load", local.toLocal(script_element._on_load), page);
|
||||
self.executeCallback(comptime .wrap("load"), page);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -866,12 +916,10 @@ pub const Script = struct {
|
||||
.cacheable = cacheable,
|
||||
});
|
||||
|
||||
self.executeCallback("error", local.toLocal(script_element._on_error), page);
|
||||
self.executeCallback(comptime .wrap("error"), page);
|
||||
}
|
||||
|
||||
fn executeCallback(self: *const Script, comptime typ: []const u8, cb_: ?js.Function, page: *Page) void {
|
||||
const cb = cb_ orelse return;
|
||||
|
||||
fn executeCallback(self: *const Script, typ: String, page: *Page) void {
|
||||
const Event = @import("webapi/Event.zig");
|
||||
const event = Event.initTrusted(typ, .{}, page) catch |err| {
|
||||
log.warn(.js, "script internal callback", .{
|
||||
@@ -881,13 +929,11 @@ pub const Script = struct {
|
||||
});
|
||||
return;
|
||||
};
|
||||
|
||||
var caught: js.TryCatch.Caught = undefined;
|
||||
cb.tryCall(void, .{event}, &caught) catch {
|
||||
page._event_manager.dispatchOpts(self.script_element.?.asNode().asEventTarget(), event, .{ .apply_ignore = true }) catch |err| {
|
||||
log.warn(.js, "script callback", .{
|
||||
.url = self.url,
|
||||
.type = typ,
|
||||
.caught = caught,
|
||||
.err = err,
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -900,11 +946,11 @@ const BufferPool = struct {
|
||||
max_concurrent_transfers: u8,
|
||||
mem_pool: std.heap.MemoryPool(Container),
|
||||
|
||||
const List = std.DoublyLinkedList;
|
||||
const List = std.SinglyLinkedList;
|
||||
|
||||
const Container = struct {
|
||||
node: List.Node,
|
||||
buf: std.ArrayListUnmanaged(u8),
|
||||
buf: std.ArrayList(u8),
|
||||
};
|
||||
|
||||
fn init(allocator: Allocator, max_concurrent_transfers: u8) BufferPool {
|
||||
@@ -929,7 +975,7 @@ const BufferPool = struct {
|
||||
self.mem_pool.deinit();
|
||||
}
|
||||
|
||||
fn get(self: *BufferPool) std.ArrayListUnmanaged(u8) {
|
||||
fn get(self: *BufferPool) std.ArrayList(u8) {
|
||||
const node = self.available.popFirst() orelse {
|
||||
// return a new buffer
|
||||
return .{};
|
||||
@@ -941,7 +987,7 @@ const BufferPool = struct {
|
||||
return container.buf;
|
||||
}
|
||||
|
||||
fn release(self: *BufferPool, buffer: ArrayListUnmanaged(u8)) void {
|
||||
fn release(self: *BufferPool, buffer: ArrayList(u8)) void {
|
||||
// create mutable copy
|
||||
var b = buffer;
|
||||
|
||||
@@ -959,7 +1005,7 @@ const BufferPool = struct {
|
||||
b.clearRetainingCapacity();
|
||||
container.* = .{ .buf = b, .node = .{} };
|
||||
self.count += 1;
|
||||
self.available.append(&container.node);
|
||||
self.available.prepend(&container.node);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1007,23 +1053,35 @@ fn parseDataURI(allocator: Allocator, src: []const u8) !?[]const u8 {
|
||||
|
||||
const uri = src[5..];
|
||||
const data_starts = std.mem.indexOfScalar(u8, uri, ',') orelse return null;
|
||||
const data = uri[data_starts + 1 ..];
|
||||
|
||||
var data = uri[data_starts + 1 ..];
|
||||
const unescaped = try URL.unescape(allocator, data);
|
||||
|
||||
// Extract the encoding.
|
||||
const metadata = uri[0..data_starts];
|
||||
if (std.mem.endsWith(u8, metadata, ";base64")) {
|
||||
const decoder = std.base64.standard.Decoder;
|
||||
const decoded_size = try decoder.calcSizeForSlice(data);
|
||||
|
||||
const buffer = try allocator.alloc(u8, decoded_size);
|
||||
errdefer allocator.free(buffer);
|
||||
|
||||
try decoder.decode(buffer, data);
|
||||
data = buffer;
|
||||
if (std.mem.endsWith(u8, metadata, ";base64") == false) {
|
||||
return unescaped;
|
||||
}
|
||||
|
||||
return data;
|
||||
// Forgiving base64 decode per WHATWG spec:
|
||||
// https://infra.spec.whatwg.org/#forgiving-base64-decode
|
||||
// Step 1: Remove all ASCII whitespace
|
||||
var stripped = try std.ArrayList(u8).initCapacity(allocator, unescaped.len);
|
||||
for (unescaped) |c| {
|
||||
if (!std.ascii.isWhitespace(c)) {
|
||||
stripped.appendAssumeCapacity(c);
|
||||
}
|
||||
}
|
||||
const trimmed = std.mem.trimRight(u8, stripped.items, "=");
|
||||
|
||||
// Length % 4 == 1 is invalid
|
||||
if (trimmed.len % 4 == 1) {
|
||||
return error.InvalidCharacterError;
|
||||
}
|
||||
|
||||
const decoded_size = std.base64.standard_no_pad.Decoder.calcSizeForSlice(trimmed) catch return error.InvalidCharacterError;
|
||||
const buffer = try allocator.alloc(u8, decoded_size);
|
||||
std.base64.standard_no_pad.Decoder.decode(buffer, trimmed) catch return error.InvalidCharacterError;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
const testing = @import("../testing.zig");
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
const std = @import("std");
|
||||
const lp = @import("lightpanda");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const log = @import("../log.zig");
|
||||
|
||||
@@ -28,9 +29,10 @@ const History = @import("webapi/History.zig");
|
||||
|
||||
const Page = @import("Page.zig");
|
||||
const Browser = @import("Browser.zig");
|
||||
const Notification = @import("../Notification.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
const IS_DEBUG = 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.
|
||||
@@ -39,45 +41,37 @@ const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
const Session = @This();
|
||||
|
||||
browser: *Browser,
|
||||
notification: *Notification,
|
||||
|
||||
// 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,
|
||||
page: ?Page,
|
||||
|
||||
pub fn init(self: *Session, browser: *Browser) !void {
|
||||
var executor = try browser.env.newExecutionWorld();
|
||||
errdefer executor.deinit();
|
||||
frame_id_gen: u32,
|
||||
|
||||
pub fn init(self: *Session, browser: *Browser, notification: *Notification) !void {
|
||||
const allocator = browser.app.allocator;
|
||||
const session_allocator = browser.session_arena.allocator();
|
||||
const arena = try browser.arena_pool.acquire();
|
||||
errdefer browser.arena_pool.release(arena);
|
||||
|
||||
self.* = .{
|
||||
.browser = browser,
|
||||
.executor = executor,
|
||||
.storage_shed = .{},
|
||||
.arena = session_allocator,
|
||||
.cookie_jar = storage.Cookie.Jar.init(allocator),
|
||||
.navigation = .{},
|
||||
.page = null,
|
||||
.arena = arena,
|
||||
.history = .{},
|
||||
.transfer_arena = browser.transfer_arena.allocator(),
|
||||
.frame_id_gen = 0,
|
||||
// The prototype (EventTarget) for Navigation is created when a Page is created.
|
||||
.navigation = .{ ._proto = undefined },
|
||||
.storage_shed = .{},
|
||||
.browser = browser,
|
||||
.notification = notification,
|
||||
.cookie_jar = storage.Cookie.Jar.init(allocator),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -85,9 +79,11 @@ pub fn deinit(self: *Session) void {
|
||||
if (self.page != null) {
|
||||
self.removePage();
|
||||
}
|
||||
const browser = self.browser;
|
||||
|
||||
self.cookie_jar.deinit();
|
||||
self.storage_shed.deinit(self.browser.app.allocator);
|
||||
self.executor.deinit();
|
||||
self.storage_shed.deinit(browser.app.allocator);
|
||||
browser.arena_pool.release(self.arena);
|
||||
}
|
||||
|
||||
// NOTE: the caller is not the owner of the returned value,
|
||||
@@ -95,11 +91,9 @@ pub fn deinit(self: *Session) void {
|
||||
pub fn createPage(self: *Session) !*Page {
|
||||
lp.assert(self.page == null, "Session.createPage - page not 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.?;
|
||||
self.page = @as(Page, undefined);
|
||||
const page = &self.page.?;
|
||||
try Page.init(page, self.nextFrameId(), self, null);
|
||||
|
||||
// Creates a new NavigationEventTarget for this page.
|
||||
try self.navigation.onNewPage(page);
|
||||
@@ -109,14 +103,14 @@ pub fn createPage(self: *Session) !*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);
|
||||
self.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, .{});
|
||||
self.notification.dispatch(.page_remove, .{});
|
||||
lp.assert(self.page != null, "Session.removePage - page is null", .{});
|
||||
|
||||
self.page.?.deinit();
|
||||
@@ -129,48 +123,262 @@ pub fn removePage(self: *Session) void {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn replacePage(self: *Session) !*Page {
|
||||
if (comptime IS_DEBUG) {
|
||||
log.debug(.browser, "replace page", .{});
|
||||
}
|
||||
|
||||
lp.assert(self.page != null, "Session.replacePage null page", .{});
|
||||
|
||||
var current = self.page.?;
|
||||
const frame_id = current._frame_id;
|
||||
const parent = current.parent;
|
||||
current.deinit();
|
||||
|
||||
self.browser.env.memoryPressureNotification(.moderate);
|
||||
|
||||
self.page = @as(Page, undefined);
|
||||
const page = &self.page.?;
|
||||
try Page.init(page, frame_id, self, parent);
|
||||
return page;
|
||||
}
|
||||
|
||||
pub fn currentPage(self: *Session) ?*Page {
|
||||
return self.page orelse return null;
|
||||
return &(self.page orelse return null);
|
||||
}
|
||||
|
||||
pub const WaitResult = enum {
|
||||
done,
|
||||
no_page,
|
||||
cdp_socket,
|
||||
navigate,
|
||||
};
|
||||
|
||||
pub fn findPage(self: *Session, frame_id: u32) ?*Page {
|
||||
const page = self.currentPage() orelse return null;
|
||||
return if (page._frame_id == frame_id) page else null;
|
||||
}
|
||||
|
||||
pub fn wait(self: *Session, wait_ms: u32) WaitResult {
|
||||
var page = &(self.page orelse return .no_page);
|
||||
while (true) {
|
||||
const page = self.page orelse return .no_page;
|
||||
switch (page.wait(wait_ms)) {
|
||||
.navigate => self.processScheduledNavigation() catch return .done,
|
||||
const wait_result = self._wait(page, wait_ms) catch |err| {
|
||||
switch (err) {
|
||||
error.JsError => {}, // already logged (with hopefully more context)
|
||||
else => log.err(.browser, "session wait", .{
|
||||
.err = err,
|
||||
.url = page.url,
|
||||
}),
|
||||
}
|
||||
return .done;
|
||||
};
|
||||
|
||||
switch (wait_result) {
|
||||
.done => {
|
||||
if (page._queued_navigation == null) {
|
||||
return .done;
|
||||
}
|
||||
page = self.processScheduledNavigation(page) 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 });
|
||||
fn _wait(self: *Session, page: *Page, wait_ms: u32) !WaitResult {
|
||||
var timer = try std.time.Timer.start();
|
||||
var ms_remaining = wait_ms;
|
||||
|
||||
// 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 browser = self.browser;
|
||||
var http_client = browser.http_client;
|
||||
|
||||
const page = self.createPage() catch |err| {
|
||||
log.err(.browser, "queued navigation page error", .{
|
||||
.err = err,
|
||||
.url = qn.url,
|
||||
});
|
||||
return err;
|
||||
// I'd like the page to know NOTHING about cdp_socket / CDP, but the
|
||||
// fact is that the behavior of wait changes depending on whether or
|
||||
// not we're using CDP.
|
||||
// If we aren't using CDP, as soon as we think there's nothing left
|
||||
// to do, we can exit - we'de done.
|
||||
// But if we are using CDP, we should wait for the whole `wait_ms`
|
||||
// because the http_click.tick() also monitors the CDP socket. And while
|
||||
// we could let CDP poll http (like it does for HTTP requests), the fact
|
||||
// is that we know more about the timing of stuff (e.g. how long to
|
||||
// poll/sleep) in the page.
|
||||
const exit_when_done = http_client.cdp_client == null;
|
||||
|
||||
while (true) {
|
||||
switch (page._parse_state) {
|
||||
.pre, .raw, .text, .image => {
|
||||
// The main page hasn't started/finished navigating.
|
||||
// There's no JS to run, and no reason to run the scheduler.
|
||||
if (http_client.active == 0 and exit_when_done) {
|
||||
// haven't started navigating, I guess.
|
||||
return .done;
|
||||
}
|
||||
// Either we have active http connections, or we're in CDP
|
||||
// mode with an extra socket. Either way, we're waiting
|
||||
// for http traffic
|
||||
if (try http_client.tick(@intCast(ms_remaining)) == .cdp_socket) {
|
||||
// exit_when_done is explicitly set when there isn't
|
||||
// an extra socket, so it should not be possibl to
|
||||
// get an cdp_socket message when exit_when_done
|
||||
// is true.
|
||||
if (IS_DEBUG) {
|
||||
std.debug.assert(exit_when_done == false);
|
||||
}
|
||||
|
||||
// data on a socket we aren't handling, return to caller
|
||||
return .cdp_socket;
|
||||
}
|
||||
},
|
||||
.html, .complete => {
|
||||
if (page._queued_navigation != null) {
|
||||
return .done;
|
||||
}
|
||||
|
||||
// The HTML page was parsed. We now either have JS scripts to
|
||||
// download, or scheduled tasks to execute, or both.
|
||||
|
||||
// scheduler.run could trigger new http transfers, so do not
|
||||
// store http_client.active BEFORE this call and then use
|
||||
// it AFTER.
|
||||
const ms_to_next_task = try browser.runMacrotasks();
|
||||
|
||||
// Each call to this runs scheduled load events.
|
||||
try page.dispatchLoad();
|
||||
|
||||
const http_active = http_client.active;
|
||||
const total_network_activity = http_active + http_client.intercepted;
|
||||
if (page._notified_network_almost_idle.check(total_network_activity <= 2)) {
|
||||
page.notifyNetworkAlmostIdle();
|
||||
}
|
||||
if (page._notified_network_idle.check(total_network_activity == 0)) {
|
||||
page.notifyNetworkIdle();
|
||||
}
|
||||
|
||||
if (http_active == 0 and exit_when_done) {
|
||||
// we don't need to consider http_client.intercepted here
|
||||
// because exit_when_done is true, and that can only be
|
||||
// the case when interception isn't possible.
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(http_client.intercepted == 0);
|
||||
}
|
||||
|
||||
const ms: u64 = ms_to_next_task orelse blk: {
|
||||
if (wait_ms - ms_remaining < 100) {
|
||||
if (comptime builtin.is_test) {
|
||||
return .done;
|
||||
}
|
||||
// Look, we want to exit ASAP, but we don't want
|
||||
// to exit so fast that we've run none of the
|
||||
// background jobs.
|
||||
break :blk 50;
|
||||
}
|
||||
|
||||
if (browser.hasBackgroundTasks()) {
|
||||
// _we_ have nothing to run, but v8 is working on
|
||||
// background tasks. We'll wait for them.
|
||||
browser.waitForBackgroundTasks();
|
||||
break :blk 20;
|
||||
}
|
||||
|
||||
// No http transfers, no cdp extra socket, no
|
||||
// scheduled tasks, we're done.
|
||||
return .done;
|
||||
};
|
||||
|
||||
if (ms > ms_remaining) {
|
||||
// Same as above, except we have a scheduled task,
|
||||
// it just happens to be too far into the future
|
||||
// compared to how long we were told to wait.
|
||||
return .done;
|
||||
}
|
||||
|
||||
// We have a task to run in the not-so-distant future.
|
||||
// You might think we can just sleep until that task is
|
||||
// ready, but we should continue to run lowPriority tasks
|
||||
// in the meantime, and that could unblock things. So
|
||||
// we'll just sleep for a bit, and then restart our wait
|
||||
// loop to see if anything new can be processed.
|
||||
std.Thread.sleep(std.time.ns_per_ms * @as(u64, @intCast(@min(ms, 20))));
|
||||
} else {
|
||||
// We're here because we either have active HTTP
|
||||
// connections, or exit_when_done == false (aka, there's
|
||||
// an cdp_socket registered with the http client).
|
||||
// We should continue to run lowPriority tasks, so we
|
||||
// minimize how long we'll poll for network I/O.
|
||||
var ms_to_wait = @min(200, ms_to_next_task orelse 200);
|
||||
if (ms_to_wait > 10 and browser.hasBackgroundTasks()) {
|
||||
// if we have background tasks, we don't want to wait too
|
||||
// long for a message from the client. We want to go back
|
||||
// to the top of the loop and run macrotasks.
|
||||
ms_to_wait = 10;
|
||||
}
|
||||
if (try http_client.tick(@min(ms_remaining, ms_to_wait)) == .cdp_socket) {
|
||||
// data on a socket we aren't handling, return to caller
|
||||
return .cdp_socket;
|
||||
}
|
||||
}
|
||||
},
|
||||
.err => |err| {
|
||||
page._parse_state = .{ .raw_done = @errorName(err) };
|
||||
return err;
|
||||
},
|
||||
.raw_done => {
|
||||
if (exit_when_done) {
|
||||
return .done;
|
||||
}
|
||||
// we _could_ http_client.tick(ms_to_wait), but this has
|
||||
// the same result, and I feel is more correct.
|
||||
return .no_page;
|
||||
},
|
||||
}
|
||||
|
||||
const ms_elapsed = timer.lap() / 1_000_000;
|
||||
if (ms_elapsed >= ms_remaining) {
|
||||
return .done;
|
||||
}
|
||||
ms_remaining -= @intCast(ms_elapsed);
|
||||
}
|
||||
}
|
||||
|
||||
fn processScheduledNavigation(self: *Session, current_page: *Page) !*Page {
|
||||
const browser = self.browser;
|
||||
|
||||
const qn = current_page._queued_navigation.?;
|
||||
// take ownership of the page's queued navigation
|
||||
current_page._queued_navigation = null;
|
||||
defer browser.arena_pool.release(qn.arena);
|
||||
|
||||
const frame_id, const parent = blk: {
|
||||
const page = &self.page.?;
|
||||
const frame_id = page._frame_id;
|
||||
const parent = page.parent;
|
||||
|
||||
browser.http_client.abort();
|
||||
self.removePage();
|
||||
|
||||
break :blk .{ frame_id, parent };
|
||||
};
|
||||
|
||||
self.page = @as(Page, undefined);
|
||||
const page = &self.page.?;
|
||||
try Page.init(page, frame_id, self, parent);
|
||||
|
||||
// Creates a new NavigationEventTarget for this page.
|
||||
try self.navigation.onNewPage(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.notification.dispatch(.page_created, page);
|
||||
|
||||
page.navigate(qn.url, qn.opts) catch |err| {
|
||||
log.err(.browser, "queued navigation error", .{ .err = err, .url = qn.url });
|
||||
return err;
|
||||
};
|
||||
|
||||
return page;
|
||||
}
|
||||
|
||||
pub fn nextFrameId(self: *Session) u32 {
|
||||
const id = self.frame_id_gen +% 1;
|
||||
self.frame_id_gen = id;
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
@@ -17,48 +17,64 @@
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const lp = @import("lightpanda");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const ResolveOpts = struct {
|
||||
encode: bool = false,
|
||||
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);
|
||||
const duped = try allocator.dupeZ(u8, path);
|
||||
return processResolved(allocator, duped, opts);
|
||||
}
|
||||
if (comptime opts.encode) {
|
||||
return processResolved(allocator, path, opts);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
if (path.len == 0) {
|
||||
if (comptime opts.always_dupe) {
|
||||
return allocator.dupeZ(u8, base);
|
||||
const duped = try allocator.dupeZ(u8, base);
|
||||
return processResolved(allocator, duped, opts);
|
||||
}
|
||||
if (comptime opts.encode) {
|
||||
return processResolved(allocator, base, opts);
|
||||
}
|
||||
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 });
|
||||
const result = try std.mem.joinZ(allocator, "", &.{ base[0..base_path_end], path });
|
||||
return processResolved(allocator, result, opts);
|
||||
}
|
||||
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 });
|
||||
const result = try std.mem.joinZ(allocator, "", &.{ base[0..base_fragment_start], path });
|
||||
return processResolved(allocator, result, opts);
|
||||
}
|
||||
|
||||
if (std.mem.startsWith(u8, path, "//")) {
|
||||
// network-path reference
|
||||
const index = std.mem.indexOfScalar(u8, base, ':') orelse {
|
||||
if (comptime isNullTerminated(PT)) {
|
||||
if (comptime opts.encode) {
|
||||
return processResolved(allocator, path, opts);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
return allocator.dupeZ(u8, path);
|
||||
const duped = try allocator.dupeZ(u8, path);
|
||||
return processResolved(allocator, duped, opts);
|
||||
};
|
||||
const protocol = base[0 .. index + 1];
|
||||
return std.mem.joinZ(allocator, "", &.{ protocol, path });
|
||||
const result = try std.mem.joinZ(allocator, "", &.{ protocol, path });
|
||||
return processResolved(allocator, result, opts);
|
||||
}
|
||||
|
||||
const scheme_end = std.mem.indexOf(u8, base, "://");
|
||||
@@ -66,7 +82,8 @@ pub fn resolve(allocator: Allocator, base: [:0]const u8, path: anytype, comptime
|
||||
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 });
|
||||
const result = try std.mem.joinZ(allocator, "", &.{ base[0..path_start], path });
|
||||
return processResolved(allocator, result, opts);
|
||||
}
|
||||
|
||||
var normalized_base: []const u8 = base[0..path_start];
|
||||
@@ -128,7 +145,119 @@ pub fn resolve(allocator: Allocator, base: [:0]const u8, path: anytype, comptime
|
||||
|
||||
// we always have an extra space
|
||||
out[out_i] = 0;
|
||||
return out[0..out_i :0];
|
||||
return processResolved(allocator, out[0..out_i :0], opts);
|
||||
}
|
||||
|
||||
fn processResolved(allocator: Allocator, url: [:0]const u8, comptime opts: ResolveOpts) ![:0]const u8 {
|
||||
if (!comptime opts.encode) {
|
||||
return url;
|
||||
}
|
||||
return ensureEncoded(allocator, url);
|
||||
}
|
||||
|
||||
pub fn ensureEncoded(allocator: Allocator, url: [:0]const u8) ![:0]const u8 {
|
||||
const scheme_end = std.mem.indexOf(u8, url, "://");
|
||||
const authority_start = if (scheme_end) |end| end + 3 else 0;
|
||||
const path_start = std.mem.indexOfScalarPos(u8, url, authority_start, '/') orelse return url;
|
||||
|
||||
const query_start = std.mem.indexOfScalarPos(u8, url, path_start, '?');
|
||||
const fragment_start = std.mem.indexOfScalarPos(u8, url, query_start orelse path_start, '#');
|
||||
|
||||
const path_end = query_start orelse fragment_start orelse url.len;
|
||||
const query_end = if (query_start) |_| (fragment_start orelse url.len) else path_end;
|
||||
|
||||
const path_to_encode = url[path_start..path_end];
|
||||
const encoded_path = try percentEncodeSegment(allocator, path_to_encode, true);
|
||||
|
||||
const encoded_query = if (query_start) |qs| blk: {
|
||||
const query_to_encode = url[qs + 1 .. query_end];
|
||||
const encoded = try percentEncodeSegment(allocator, query_to_encode, false);
|
||||
break :blk encoded;
|
||||
} else null;
|
||||
|
||||
const encoded_fragment = if (fragment_start) |fs| blk: {
|
||||
const fragment_to_encode = url[fs + 1 ..];
|
||||
const encoded = try percentEncodeSegment(allocator, fragment_to_encode, false);
|
||||
break :blk encoded;
|
||||
} else null;
|
||||
|
||||
if (encoded_path.ptr == path_to_encode.ptr and
|
||||
(encoded_query == null or encoded_query.?.ptr == url[query_start.? + 1 .. query_end].ptr) and
|
||||
(encoded_fragment == null or encoded_fragment.?.ptr == url[fragment_start.? + 1 ..].ptr))
|
||||
{
|
||||
// nothing has changed
|
||||
return url;
|
||||
}
|
||||
|
||||
var buf = try std.ArrayList(u8).initCapacity(allocator, url.len + 20);
|
||||
try buf.appendSlice(allocator, url[0..path_start]);
|
||||
try buf.appendSlice(allocator, encoded_path);
|
||||
if (encoded_query) |eq| {
|
||||
try buf.append(allocator, '?');
|
||||
try buf.appendSlice(allocator, eq);
|
||||
}
|
||||
if (encoded_fragment) |ef| {
|
||||
try buf.append(allocator, '#');
|
||||
try buf.appendSlice(allocator, ef);
|
||||
}
|
||||
try buf.append(allocator, 0);
|
||||
return buf.items[0 .. buf.items.len - 1 :0];
|
||||
}
|
||||
|
||||
fn percentEncodeSegment(allocator: Allocator, segment: []const u8, comptime is_path: bool) ![]const u8 {
|
||||
// Check if encoding is needed
|
||||
var needs_encoding = false;
|
||||
for (segment) |c| {
|
||||
if (shouldPercentEncode(c, is_path)) {
|
||||
needs_encoding = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!needs_encoding) {
|
||||
return segment;
|
||||
}
|
||||
|
||||
var buf = try std.ArrayList(u8).initCapacity(allocator, segment.len + 10);
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < segment.len) : (i += 1) {
|
||||
const c = segment[i];
|
||||
|
||||
// Check if this is an already-encoded sequence (%XX)
|
||||
if (c == '%' and i + 2 < segment.len) {
|
||||
const end = i + 2;
|
||||
const h1 = segment[i + 1];
|
||||
const h2 = segment[end];
|
||||
if (std.ascii.isHex(h1) and std.ascii.isHex(h2)) {
|
||||
try buf.appendSlice(allocator, segment[i .. end + 1]);
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldPercentEncode(c, is_path)) {
|
||||
try buf.writer(allocator).print("%{X:0>2}", .{c});
|
||||
} else {
|
||||
try buf.append(allocator, c);
|
||||
}
|
||||
}
|
||||
|
||||
return buf.items;
|
||||
}
|
||||
|
||||
fn shouldPercentEncode(c: u8, comptime is_path: bool) bool {
|
||||
return switch (c) {
|
||||
// Unreserved characters (RFC 3986)
|
||||
'A'...'Z', 'a'...'z', '0'...'9', '-', '.', '_', '~' => false,
|
||||
// sub-delims allowed in both path and query
|
||||
'!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=' => false,
|
||||
// Separators allowed in both path and query
|
||||
'/', ':', '@' => false,
|
||||
// Query-specific: '?' is allowed in queries but not in paths
|
||||
'?' => comptime is_path,
|
||||
// Everything else needs encoding (including space)
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
|
||||
fn isNullTerminated(comptime value: type) bool {
|
||||
@@ -503,6 +632,43 @@ pub fn concatQueryString(arena: Allocator, url: []const u8, query_string: []cons
|
||||
return buf.items[0 .. buf.items.len - 1 :0];
|
||||
}
|
||||
|
||||
pub fn getRobotsUrl(arena: Allocator, url: [:0]const u8) ![:0]const u8 {
|
||||
const origin = try getOrigin(arena, url) orelse return error.NoOrigin;
|
||||
return try std.fmt.allocPrintSentinel(
|
||||
arena,
|
||||
"{s}/robots.txt",
|
||||
.{origin},
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn unescape(arena: Allocator, input: []const u8) ![]const u8 {
|
||||
if (std.mem.indexOfScalar(u8, input, '%') == null) {
|
||||
return input;
|
||||
}
|
||||
|
||||
var result = try std.ArrayList(u8).initCapacity(arena, input.len);
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < input.len) {
|
||||
if (input[i] == '%' and i + 2 < input.len) {
|
||||
const hex = input[i + 1 .. i + 3];
|
||||
const byte = std.fmt.parseInt(u8, hex, 16) catch {
|
||||
result.appendAssumeCapacity(input[i]);
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
result.appendAssumeCapacity(byte);
|
||||
i += 3;
|
||||
} else {
|
||||
result.appendAssumeCapacity(input[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return result.items;
|
||||
}
|
||||
|
||||
const testing = @import("../testing.zig");
|
||||
test "URL: isCompleteHTTPUrl" {
|
||||
try testing.expectEqual(true, isCompleteHTTPUrl("http://example.com/about"));
|
||||
@@ -682,6 +848,297 @@ test "URL: resolve" {
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: ensureEncoded" {
|
||||
defer testing.reset();
|
||||
|
||||
const Case = struct {
|
||||
url: [:0]const u8,
|
||||
expected: [:0]const u8,
|
||||
};
|
||||
|
||||
const cases = [_]Case{
|
||||
.{
|
||||
.url = "https://example.com/over 9000!",
|
||||
.expected = "https://example.com/over%209000!",
|
||||
},
|
||||
.{
|
||||
.url = "http://example.com/hello world.html",
|
||||
.expected = "http://example.com/hello%20world.html",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/file[1].html",
|
||||
.expected = "https://example.com/file%5B1%5D.html",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/file{name}.html",
|
||||
.expected = "https://example.com/file%7Bname%7D.html",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page?query=hello world",
|
||||
.expected = "https://example.com/page?query=hello%20world",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page?a=1&b=value with spaces",
|
||||
.expected = "https://example.com/page?a=1&b=value%20with%20spaces",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page#section one",
|
||||
.expected = "https://example.com/page#section%20one",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/my path?query=my value#my anchor",
|
||||
.expected = "https://example.com/my%20path?query=my%20value#my%20anchor",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/already%20encoded",
|
||||
.expected = "https://example.com/already%20encoded",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/file%5B1%5D.html",
|
||||
.expected = "https://example.com/file%5B1%5D.html",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/caf%C3%A9",
|
||||
.expected = "https://example.com/caf%C3%A9",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page?query=already%20encoded",
|
||||
.expected = "https://example.com/page?query=already%20encoded",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page?a=1&b=value%20here",
|
||||
.expected = "https://example.com/page?a=1&b=value%20here",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page#section%20one",
|
||||
.expected = "https://example.com/page#section%20one",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/part%20encoded and not",
|
||||
.expected = "https://example.com/part%20encoded%20and%20not",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/page?a=encoded%20value&b=not encoded",
|
||||
.expected = "https://example.com/page?a=encoded%20value&b=not%20encoded",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/my%20path?query=not encoded#encoded%20anchor",
|
||||
.expected = "https://example.com/my%20path?query=not%20encoded#encoded%20anchor",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/fully%20encoded?query=also%20encoded#and%20this",
|
||||
.expected = "https://example.com/fully%20encoded?query=also%20encoded#and%20this",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/path-with_under~tilde",
|
||||
.expected = "https://example.com/path-with_under~tilde",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/sub-delims!$&'()*+,;=",
|
||||
.expected = "https://example.com/sub-delims!$&'()*+,;=",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com",
|
||||
.expected = "https://example.com",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com?query=value",
|
||||
.expected = "https://example.com?query=value",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/clean/path",
|
||||
.expected = "https://example.com/clean/path",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/path?clean=query#clean-fragment",
|
||||
.expected = "https://example.com/path?clean=query#clean-fragment",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/100% complete",
|
||||
.expected = "https://example.com/100%25%20complete",
|
||||
},
|
||||
.{
|
||||
.url = "https://example.com/path?value=100% done",
|
||||
.expected = "https://example.com/path?value=100%25%20done",
|
||||
},
|
||||
.{
|
||||
.url = "about:blank",
|
||||
.expected = "about:blank",
|
||||
},
|
||||
};
|
||||
|
||||
for (cases) |case| {
|
||||
const result = try ensureEncoded(testing.arena_allocator, case.url);
|
||||
try testing.expectString(case.expected, result);
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: resolve with encoding" {
|
||||
defer testing.reset();
|
||||
|
||||
const Case = struct {
|
||||
base: [:0]const u8,
|
||||
path: [:0]const u8,
|
||||
expected: [:0]const u8,
|
||||
};
|
||||
|
||||
const cases = [_]Case{
|
||||
// Spaces should be encoded as %20, but ! is allowed
|
||||
.{
|
||||
.base = "https://example.com/dir/",
|
||||
.path = "over 9000!",
|
||||
.expected = "https://example.com/dir/over%209000!",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "hello world.html",
|
||||
.expected = "https://example.com/hello%20world.html",
|
||||
},
|
||||
// Multiple spaces
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "path with multiple spaces",
|
||||
.expected = "https://example.com/path%20with%20%20multiple%20%20%20spaces",
|
||||
},
|
||||
// Special characters that need encoding
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file[1].html",
|
||||
.expected = "https://example.com/file%5B1%5D.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file{name}.html",
|
||||
.expected = "https://example.com/file%7Bname%7D.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file<test>.html",
|
||||
.expected = "https://example.com/file%3Ctest%3E.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file\"quote\".html",
|
||||
.expected = "https://example.com/file%22quote%22.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file|pipe.html",
|
||||
.expected = "https://example.com/file%7Cpipe.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file\\backslash.html",
|
||||
.expected = "https://example.com/file%5Cbackslash.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file^caret.html",
|
||||
.expected = "https://example.com/file%5Ecaret.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file`backtick`.html",
|
||||
.expected = "https://example.com/file%60backtick%60.html",
|
||||
},
|
||||
// Characters that should NOT be encoded
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "path-with_under~tilde.html",
|
||||
.expected = "https://example.com/path-with_under~tilde.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "path/with/slashes",
|
||||
.expected = "https://example.com/path/with/slashes",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "sub-delims!$&'()*+,;=.html",
|
||||
.expected = "https://example.com/sub-delims!$&'()*+,;=.html",
|
||||
},
|
||||
// Already encoded characters should not be double-encoded
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "already%20encoded",
|
||||
.expected = "https://example.com/already%20encoded",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file%5B1%5D.html",
|
||||
.expected = "https://example.com/file%5B1%5D.html",
|
||||
},
|
||||
// Mix of encoded and unencoded
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "part%20encoded and not",
|
||||
.expected = "https://example.com/part%20encoded%20and%20not",
|
||||
},
|
||||
// Query strings and fragments ARE encoded
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file name.html?query=value with spaces",
|
||||
.expected = "https://example.com/file%20name.html?query=value%20with%20spaces",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file name.html#anchor with spaces",
|
||||
.expected = "https://example.com/file%20name.html#anchor%20with%20spaces",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file.html?hello=world !",
|
||||
.expected = "https://example.com/file.html?hello=world%20!",
|
||||
},
|
||||
// Query structural characters should NOT be encoded
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "file.html?a=1&b=2",
|
||||
.expected = "https://example.com/file.html?a=1&b=2",
|
||||
},
|
||||
// Relative paths with encoding
|
||||
.{
|
||||
.base = "https://example.com/dir/page.html",
|
||||
.path = "../other dir/file.html",
|
||||
.expected = "https://example.com/other%20dir/file.html",
|
||||
},
|
||||
.{
|
||||
.base = "https://example.com/dir/",
|
||||
.path = "./sub dir/file.html",
|
||||
.expected = "https://example.com/dir/sub%20dir/file.html",
|
||||
},
|
||||
// Absolute paths with encoding
|
||||
.{
|
||||
.base = "https://example.com/some/path",
|
||||
.path = "/absolute path/file.html",
|
||||
.expected = "https://example.com/absolute%20path/file.html",
|
||||
},
|
||||
// Unicode/high bytes (though ideally these should be UTF-8 encoded first)
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "café",
|
||||
.expected = "https://example.com/caf%C3%A9",
|
||||
},
|
||||
// Empty path
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "",
|
||||
.expected = "https://example.com/",
|
||||
},
|
||||
// Complete URL as path (should not be encoded)
|
||||
.{
|
||||
.base = "https://example.com/",
|
||||
.path = "https://other.com/path with spaces",
|
||||
.expected = "https://other.com/path%20with%20spaces",
|
||||
},
|
||||
};
|
||||
|
||||
for (cases) |case| {
|
||||
const result = try resolve(testing.arena_allocator, case.base, case.path, .{ .encode = true });
|
||||
try testing.expectString(case.expected, result);
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: eqlDocument" {
|
||||
defer testing.reset();
|
||||
{
|
||||
@@ -779,3 +1236,96 @@ test "URL: concatQueryString" {
|
||||
try testing.expectEqual("https://www.lightpanda.io/index?1=2&a=b", url);
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: getRobotsUrl" {
|
||||
defer testing.reset();
|
||||
const arena = testing.arena_allocator;
|
||||
|
||||
{
|
||||
const url = try getRobotsUrl(arena, "https://www.lightpanda.io");
|
||||
try testing.expectEqual("https://www.lightpanda.io/robots.txt", url);
|
||||
}
|
||||
|
||||
{
|
||||
const url = try getRobotsUrl(arena, "https://www.lightpanda.io/some/path");
|
||||
try testing.expectString("https://www.lightpanda.io/robots.txt", url);
|
||||
}
|
||||
|
||||
{
|
||||
const url = try getRobotsUrl(arena, "https://www.lightpanda.io:8080/page");
|
||||
try testing.expectString("https://www.lightpanda.io:8080/robots.txt", url);
|
||||
}
|
||||
{
|
||||
const url = try getRobotsUrl(arena, "http://example.com/deep/nested/path?query=value#fragment");
|
||||
try testing.expectString("http://example.com/robots.txt", url);
|
||||
}
|
||||
{
|
||||
const url = try getRobotsUrl(arena, "https://user:pass@example.com/page");
|
||||
try testing.expectString("https://example.com/robots.txt", url);
|
||||
}
|
||||
}
|
||||
|
||||
test "URL: unescape" {
|
||||
defer testing.reset();
|
||||
const arena = testing.arena_allocator;
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello world");
|
||||
try testing.expectEqual("hello world", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello%20world");
|
||||
try testing.expectEqual("hello world", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "%48%65%6c%6c%6f");
|
||||
try testing.expectEqual("Hello", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "%48%65%6C%6C%6F");
|
||||
try testing.expectEqual("Hello", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "a%3Db");
|
||||
try testing.expectEqual("a=b", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "a%3DB");
|
||||
try testing.expectEqual("a=B", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "ZDIgPSAndHdvJzs%3D");
|
||||
try testing.expectEqual("ZDIgPSAndHdvJzs=", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "%5a%44%4d%67%50%53%41%6e%64%47%68%79%5a%57%55%6e%4f%77%3D%3D");
|
||||
try testing.expectEqual("ZDMgPSAndGhyZWUnOw==", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello%2world");
|
||||
try testing.expectEqual("hello%2world", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello%ZZworld");
|
||||
try testing.expectEqual("hello%ZZworld", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello%");
|
||||
try testing.expectEqual("hello%", result);
|
||||
}
|
||||
|
||||
{
|
||||
const result = try unescape(arena, "hello%2");
|
||||
try testing.expectEqual("hello%2", result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,10 +480,11 @@ fn consumeName(self: *Tokenizer) []const u8 {
|
||||
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);
|
||||
'\x80'...'\xFF' => {
|
||||
// Non-ASCII: advance over the complete UTF-8 code point in one step.
|
||||
// Using consumeChar() instead of advance(1) ensures we never land on
|
||||
// a continuation byte, which advance() asserts against.
|
||||
self.consumeChar();
|
||||
},
|
||||
else => {
|
||||
if (self.hasNonAsciiAt(0)) {
|
||||
@@ -583,7 +584,7 @@ fn consumeNumeric(self: *Tokenizer) Token {
|
||||
};
|
||||
|
||||
self.advance(2);
|
||||
} else if (self.hasAtLeast(1) and std.ascii.isDigit(self.byteAt(2))) {
|
||||
} else if (self.hasAtLeast(2) and std.ascii.isDigit(self.byteAt(2))) {
|
||||
self.advance(1);
|
||||
} else {
|
||||
break :blk;
|
||||
|
||||
@@ -20,16 +20,15 @@ const std = @import("std");
|
||||
const Page = @import("Page.zig");
|
||||
const Node = @import("webapi/Node.zig");
|
||||
const Slot = @import("webapi/element/html/Slot.zig");
|
||||
const IFrame = @import("webapi/element/html/IFrame.zig");
|
||||
|
||||
pub const RootOpts = struct {
|
||||
with_base: bool = false,
|
||||
strip: Opts.Strip = .{},
|
||||
shadow: Opts.Shadow = .rendered,
|
||||
};
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
pub const Opts = struct {
|
||||
strip: Strip = .{},
|
||||
shadow: Shadow = .rendered,
|
||||
with_base: bool = false,
|
||||
with_frames: bool = false,
|
||||
strip: Opts.Strip = .{},
|
||||
shadow: Opts.Shadow = .rendered,
|
||||
|
||||
pub const Strip = struct {
|
||||
js: bool = false,
|
||||
@@ -49,7 +48,7 @@ pub const Opts = struct {
|
||||
};
|
||||
};
|
||||
|
||||
pub fn root(doc: *Node.Document, opts: RootOpts, writer: *std.Io.Writer, page: *Page) !void {
|
||||
pub fn root(doc: *Node.Document, opts: Opts, writer: *std.Io.Writer, page: *Page) !void {
|
||||
if (doc.is(Node.Document.HTMLDocument)) |html_doc| {
|
||||
blk: {
|
||||
// Ideally we just render the doctype which is part of the document
|
||||
@@ -71,7 +70,7 @@ pub fn root(doc: *Node.Document, opts: RootOpts, writer: *std.Io.Writer, page: *
|
||||
}
|
||||
}
|
||||
|
||||
return deep(doc.asNode(), .{ .strip = opts.strip, .shadow = opts.shadow }, writer, page);
|
||||
return deep(doc.asNode(), opts, writer, page);
|
||||
}
|
||||
|
||||
pub fn deep(node: *Node, opts: Opts, writer: *std.Io.Writer, page: *Page) error{WriteFailed}!void {
|
||||
@@ -83,19 +82,19 @@ fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Wri
|
||||
.cdata => |cd| {
|
||||
if (node.is(Node.CData.Comment)) |_| {
|
||||
try writer.writeAll("<!--");
|
||||
try writer.writeAll(cd.getData());
|
||||
try writer.writeAll(cd.getData().str());
|
||||
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(cd.getData().str());
|
||||
try writer.writeAll("?>");
|
||||
} else {
|
||||
if (shouldEscapeText(node._parent)) {
|
||||
try writeEscapedText(cd.getData(), writer);
|
||||
try writeEscapedText(cd.getData().str(), writer);
|
||||
} else {
|
||||
try writer.writeAll(cd.getData());
|
||||
try writer.writeAll(cd.getData().str());
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -140,7 +139,24 @@ fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Wri
|
||||
}
|
||||
}
|
||||
|
||||
try children(node, opts, writer, page);
|
||||
if (opts.with_frames and el.is(IFrame) != null) {
|
||||
const frame = el.as(IFrame);
|
||||
if (frame.getContentDocument()) |doc| {
|
||||
// A frame's document should always ahave a page, but
|
||||
// I'm not willing to crash a release build on that assertion.
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(doc._page != null);
|
||||
}
|
||||
if (doc._page) |frame_page| {
|
||||
try writer.writeByte('\n');
|
||||
root(doc, opts, writer, frame_page) catch return error.WriteFailed;
|
||||
try writer.writeByte('\n');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try children(node, opts, writer, page);
|
||||
}
|
||||
|
||||
if (!isVoidElement(el)) {
|
||||
try writer.writeAll("</");
|
||||
try writer.writeAll(el.getTagNameDump());
|
||||
@@ -172,7 +188,11 @@ fn _deep(node: *Node, opts: Opts, comptime force_slot: bool, writer: *std.Io.Wri
|
||||
try writer.writeAll(">\n");
|
||||
},
|
||||
.document_fragment => try children(node, opts, writer, page),
|
||||
.attribute => unreachable,
|
||||
.attribute => {
|
||||
// Not called normally, but can be called via XMLSerializer.serializeToString
|
||||
// in which case it should return an empty string
|
||||
try writer.writeAll("");
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,6 +314,12 @@ fn shouldEscapeText(node_: ?*Node) bool {
|
||||
if (node.is(Node.Element.Html.Script) != null) {
|
||||
return false;
|
||||
}
|
||||
// When scripting is enabled, <noscript> is a raw text element per the HTML spec
|
||||
// (https://html.spec.whatwg.org/multipage/parsing.html#serialising-html-fragments).
|
||||
// Its text content must not be HTML-escaped during serialization.
|
||||
if (node.is(Node.Element.Html.Generic)) |generic| {
|
||||
if (generic._tag == .noscript) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
fn writeEscapedText(text: []const u8, writer: *std.Io.Writer) !void {
|
||||
|
||||
@@ -23,42 +23,48 @@ const string = @import("../../string.zig");
|
||||
const Page = @import("../Page.zig");
|
||||
|
||||
const js = @import("js.zig");
|
||||
const bridge = @import("bridge.zig");
|
||||
const Local = @import("Local.zig");
|
||||
const Context = @import("Context.zig");
|
||||
const TaggedOpaque = @import("TaggedOpaque.zig");
|
||||
|
||||
const v8 = js.v8;
|
||||
const Allocator = std.mem.Allocator;
|
||||
const ArenaAllocator = std.heap.ArenaAllocator;
|
||||
|
||||
const CALL_ARENA_RETAIN = 1024 * 16;
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
const Caller = @This();
|
||||
local: js.Local,
|
||||
local: Local,
|
||||
prev_local: ?*const js.Local,
|
||||
prev_context: *Context,
|
||||
|
||||
// Takes the raw v8 isolate and extracts the context from it.
|
||||
pub fn init(self: *Caller, v8_isolate: *v8.Isolate) void {
|
||||
const v8_context_handle = v8.v8__Isolate__GetCurrentContext(v8_isolate);
|
||||
|
||||
const embedder_data = v8.v8__Context__GetEmbedderData(v8_context_handle, 1);
|
||||
var lossless: bool = undefined;
|
||||
const ctx: *Context = @ptrFromInt(v8.v8__BigInt__Uint64Value(embedder_data, &lossless));
|
||||
const v8_context = v8.v8__Isolate__GetCurrentContext(v8_isolate).?;
|
||||
initWithContext(self, Context.fromC(v8_context), v8_context);
|
||||
}
|
||||
|
||||
fn initWithContext(self: *Caller, ctx: *Context, v8_context: *const v8.Context) void {
|
||||
ctx.call_depth += 1;
|
||||
self.* = Caller{
|
||||
.local = .{
|
||||
.ctx = ctx,
|
||||
.handle = v8_context_handle.?,
|
||||
.handle = v8_context,
|
||||
.call_arena = ctx.call_arena,
|
||||
.isolate = .{ .handle = v8_isolate },
|
||||
.isolate = ctx.isolate,
|
||||
},
|
||||
.prev_local = ctx.local,
|
||||
.prev_context = ctx.page.js,
|
||||
};
|
||||
ctx.page.js = ctx;
|
||||
ctx.local = &self.local;
|
||||
}
|
||||
|
||||
pub fn initFromHandle(self: *Caller, handle: ?*const v8.FunctionCallbackInfo) void {
|
||||
const isolate = v8.v8__FunctionCallbackInfo__GetIsolate(handle).?;
|
||||
self.init(isolate);
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Caller) void {
|
||||
const ctx = self.local.ctx;
|
||||
const call_depth = ctx.call_depth - 1;
|
||||
@@ -81,35 +87,38 @@ pub fn deinit(self: *Caller) void {
|
||||
|
||||
ctx.call_depth = call_depth;
|
||||
ctx.local = self.prev_local;
|
||||
ctx.page.js = self.prev_context;
|
||||
}
|
||||
|
||||
pub const CallOpts = struct {
|
||||
cache: ?[]const u8 = null,
|
||||
dom_exception: bool = false,
|
||||
null_as_undefined: bool = false,
|
||||
as_typed_array: bool = false,
|
||||
};
|
||||
|
||||
pub fn constructor(self: *Caller, comptime T: type, func: anytype, handle: *const v8.FunctionCallbackInfo, comptime opts: CallOpts) void {
|
||||
const local = &self.local;
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(self.local.isolate);
|
||||
hs.init(local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const info = FunctionCallbackInfo{ .handle = handle };
|
||||
|
||||
if (!info.isConstructCall()) {
|
||||
self.handleError(T, @TypeOf(func), error.InvalidArgument, info, opts);
|
||||
handleError(T, @TypeOf(func), local, error.InvalidArgument, info, opts);
|
||||
return;
|
||||
}
|
||||
|
||||
self._constructor(func, info) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
handleError(T, @TypeOf(func), local, err, info, opts);
|
||||
};
|
||||
}
|
||||
|
||||
fn _constructor(self: *Caller, func: anytype, info: FunctionCallbackInfo) !void {
|
||||
const F = @TypeOf(func);
|
||||
const args = try self.getArgs(F, 0, info);
|
||||
const local = &self.local;
|
||||
const args = try getArgs(F, 0, local, info);
|
||||
const res = @call(.auto, func, args);
|
||||
|
||||
const ReturnType = @typeInfo(F).@"fn".return_type orelse {
|
||||
@@ -117,12 +126,12 @@ fn _constructor(self: *Caller, func: anytype, info: FunctionCallbackInfo) !void
|
||||
};
|
||||
|
||||
const new_this_handle = info.getThis();
|
||||
var this = js.Object{ .local = &self.local, .handle = new_this_handle };
|
||||
var this = js.Object{ .local = local, .handle = new_this_handle };
|
||||
if (@typeInfo(ReturnType) == .error_union) {
|
||||
const non_error_res = res catch |err| return err;
|
||||
this = try self.local.mapZigInstanceToJs(new_this_handle, non_error_res);
|
||||
this = try local.mapZigInstanceToJs(new_this_handle, non_error_res);
|
||||
} else {
|
||||
this = try self.local.mapZigInstanceToJs(new_this_handle, res);
|
||||
this = try local.mapZigInstanceToJs(new_this_handle, res);
|
||||
}
|
||||
|
||||
// If we got back a different object (existing wrapper), copy the prototype
|
||||
@@ -139,144 +148,141 @@ fn _constructor(self: *Caller, func: anytype, info: FunctionCallbackInfo) !void
|
||||
info.getReturnValue().set(this.handle);
|
||||
}
|
||||
|
||||
pub fn method(self: *Caller, comptime T: type, func: anytype, handle: *const v8.FunctionCallbackInfo, comptime opts: CallOpts) void {
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(self.local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const info = FunctionCallbackInfo{ .handle = handle };
|
||||
self._method(T, func, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
};
|
||||
}
|
||||
|
||||
fn _method(self: *Caller, comptime T: type, func: anytype, info: FunctionCallbackInfo, comptime opts: CallOpts) !void {
|
||||
const F = @TypeOf(func);
|
||||
var args = try self.getArgs(F, 1, info);
|
||||
|
||||
const js_this = info.getThis();
|
||||
@field(args, "0") = try TaggedOpaque.fromJS(*T, js_this);
|
||||
|
||||
const res = @call(.auto, func, args);
|
||||
|
||||
const mapped = try self.local.zigValueToJs(res, opts);
|
||||
const return_value = info.getReturnValue();
|
||||
return_value.set(mapped);
|
||||
}
|
||||
|
||||
pub fn function(self: *Caller, comptime T: type, func: anytype, handle: *const v8.FunctionCallbackInfo, comptime opts: CallOpts) void {
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(self.local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const info = FunctionCallbackInfo{ .handle = handle };
|
||||
self._function(func, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
};
|
||||
}
|
||||
|
||||
fn _function(self: *Caller, func: anytype, info: FunctionCallbackInfo, comptime opts: CallOpts) !void {
|
||||
const F = @TypeOf(func);
|
||||
const args = try self.getArgs(F, 0, info);
|
||||
const res = @call(.auto, func, args);
|
||||
info.getReturnValue().set(try self.local.zigValueToJs(res, opts));
|
||||
}
|
||||
|
||||
pub fn getIndex(self: *Caller, comptime T: type, func: anytype, idx: u32, handle: *const v8.PropertyCallbackInfo, comptime opts: CallOpts) u8 {
|
||||
const local = &self.local;
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(self.local.isolate);
|
||||
hs.init(local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const info = PropertyCallbackInfo{ .handle = handle };
|
||||
return self._getIndex(T, func, idx, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
return _getIndex(T, local, func, idx, info, opts) catch |err| {
|
||||
handleError(T, @TypeOf(func), local, err, info, opts);
|
||||
// not intercepted
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
|
||||
fn _getIndex(self: *Caller, comptime T: type, func: anytype, idx: u32, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
fn _getIndex(comptime T: type, local: *const Local, func: anytype, idx: u32, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
const F = @TypeOf(func);
|
||||
var args = try self.getArgs(F, 2, info);
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
|
||||
@field(args, "1") = idx;
|
||||
if (@typeInfo(F).@"fn".params.len == 3) {
|
||||
@field(args, "2") = local.ctx.page;
|
||||
}
|
||||
const ret = @call(.auto, func, args);
|
||||
return self.handleIndexedReturn(T, F, true, ret, info, opts);
|
||||
return handleIndexedReturn(T, F, true, local, ret, info, opts);
|
||||
}
|
||||
|
||||
pub fn getNamedIndex(self: *Caller, comptime T: type, func: anytype, name: *const v8.Name, handle: *const v8.PropertyCallbackInfo, comptime opts: CallOpts) u8 {
|
||||
const local = &self.local;
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(self.local.isolate);
|
||||
hs.init(local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const info = PropertyCallbackInfo{ .handle = handle };
|
||||
return self._getNamedIndex(T, func, name, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
return _getNamedIndex(T, local, func, name, info, opts) catch |err| {
|
||||
handleError(T, @TypeOf(func), local, err, info, opts);
|
||||
// not intercepted
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
|
||||
fn _getNamedIndex(self: *Caller, comptime T: type, func: anytype, name: *const v8.Name, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
fn _getNamedIndex(comptime T: type, local: *const Local, func: anytype, name: *const v8.Name, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
const F = @TypeOf(func);
|
||||
var args = try self.getArgs(F, 2, info);
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
|
||||
@field(args, "1") = try self.nameToString(@TypeOf(args.@"1"), name);
|
||||
@field(args, "1") = try nameToString(local, @TypeOf(args.@"1"), name);
|
||||
if (@typeInfo(F).@"fn".params.len == 3) {
|
||||
@field(args, "2") = local.ctx.page;
|
||||
}
|
||||
const ret = @call(.auto, func, args);
|
||||
return self.handleIndexedReturn(T, F, true, ret, info, opts);
|
||||
return handleIndexedReturn(T, F, true, local, ret, info, opts);
|
||||
}
|
||||
|
||||
pub fn setNamedIndex(self: *Caller, comptime T: type, func: anytype, name: *const v8.Name, js_value: *const v8.Value, handle: *const v8.PropertyCallbackInfo, comptime opts: CallOpts) u8 {
|
||||
const local = &self.local;
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(self.local.isolate);
|
||||
hs.init(local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const info = PropertyCallbackInfo{ .handle = handle };
|
||||
return self._setNamedIndex(T, func, name, .{ .local = &self.local, .handle = js_value }, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
return _setNamedIndex(T, local, func, name, .{ .local = &self.local, .handle = js_value }, info, opts) catch |err| {
|
||||
handleError(T, @TypeOf(func), local, err, info, opts);
|
||||
// not intercepted
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
|
||||
fn _setNamedIndex(self: *Caller, comptime T: type, func: anytype, name: *const v8.Name, js_value: js.Value, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
fn _setNamedIndex(comptime T: type, local: *const Local, func: anytype, name: *const v8.Name, js_value: js.Value, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
const F = @TypeOf(func);
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
|
||||
@field(args, "1") = try self.nameToString(@TypeOf(args.@"1"), name);
|
||||
@field(args, "2") = try self.local.jsValueToZig(@TypeOf(@field(args, "2")), js_value);
|
||||
@field(args, "1") = try nameToString(local, @TypeOf(args.@"1"), name);
|
||||
@field(args, "2") = try local.jsValueToZig(@TypeOf(@field(args, "2")), js_value);
|
||||
if (@typeInfo(F).@"fn".params.len == 4) {
|
||||
@field(args, "3") = self.local.ctx.page;
|
||||
@field(args, "3") = local.ctx.page;
|
||||
}
|
||||
const ret = @call(.auto, func, args);
|
||||
return self.handleIndexedReturn(T, F, false, ret, info, opts);
|
||||
return handleIndexedReturn(T, F, false, local, ret, info, opts);
|
||||
}
|
||||
|
||||
pub fn deleteNamedIndex(self: *Caller, comptime T: type, func: anytype, name: *const v8.Name, handle: *const v8.PropertyCallbackInfo, comptime opts: CallOpts) u8 {
|
||||
const local = &self.local;
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(self.local.isolate);
|
||||
hs.init(local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const info = PropertyCallbackInfo{ .handle = handle };
|
||||
return self._deleteNamedIndex(T, func, name, info, opts) catch |err| {
|
||||
self.handleError(T, @TypeOf(func), err, info, opts);
|
||||
return _deleteNamedIndex(T, local, func, name, info, opts) catch |err| {
|
||||
handleError(T, @TypeOf(func), local, err, info, opts);
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
|
||||
fn _deleteNamedIndex(self: *Caller, comptime T: type, func: anytype, name: *const v8.Name, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
fn _deleteNamedIndex(comptime T: type, local: *const Local, func: anytype, name: *const v8.Name, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
const F = @TypeOf(func);
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
|
||||
@field(args, "1") = try self.nameToString(@TypeOf(args.@"1"), name);
|
||||
@field(args, "1") = try nameToString(local, @TypeOf(args.@"1"), name);
|
||||
if (@typeInfo(F).@"fn".params.len == 3) {
|
||||
@field(args, "2") = self.local.ctx.page;
|
||||
@field(args, "2") = local.ctx.page;
|
||||
}
|
||||
const ret = @call(.auto, func, args);
|
||||
return self.handleIndexedReturn(T, F, false, ret, info, opts);
|
||||
return handleIndexedReturn(T, F, false, local, ret, info, opts);
|
||||
}
|
||||
|
||||
fn handleIndexedReturn(self: *Caller, comptime T: type, comptime F: type, comptime getter: bool, ret: anytype, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
pub fn getEnumerator(self: *Caller, comptime T: type, func: anytype, handle: *const v8.PropertyCallbackInfo, comptime opts: CallOpts) u8 {
|
||||
const local = &self.local;
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const info = PropertyCallbackInfo{ .handle = handle };
|
||||
return _getEnumerator(T, local, func, info, opts) catch |err| {
|
||||
handleError(T, @TypeOf(func), local, err, info, opts);
|
||||
// not intercepted
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
|
||||
fn _getEnumerator(comptime T: type, local: *const Local, func: anytype, info: PropertyCallbackInfo, comptime opts: CallOpts) !u8 {
|
||||
const F = @TypeOf(func);
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
|
||||
if (@typeInfo(F).@"fn".params.len == 2) {
|
||||
@field(args, "1") = local.ctx.page;
|
||||
}
|
||||
const ret = @call(.auto, func, args);
|
||||
return handleIndexedReturn(T, F, true, local, ret, info, opts);
|
||||
}
|
||||
|
||||
fn handleIndexedReturn(comptime T: type, comptime F: type, comptime with_value: bool, local: *const Local, ret: anytype, info: 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))) {
|
||||
@@ -291,7 +297,7 @@ fn handleIndexedReturn(self: *Caller, comptime T: type, comptime F: type, compti
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
self.handleError(T, F, err, info, opts);
|
||||
handleError(T, F, local, err, info, opts);
|
||||
// not intercepted
|
||||
return 0;
|
||||
};
|
||||
@@ -299,8 +305,8 @@ fn handleIndexedReturn(self: *Caller, comptime T: type, comptime F: type, compti
|
||||
else => ret,
|
||||
};
|
||||
|
||||
if (comptime getter) {
|
||||
info.getReturnValue().set(try self.local.zigValueToJs(non_error_ret, opts));
|
||||
if (comptime with_value) {
|
||||
info.getReturnValue().set(try local.zigValueToJs(non_error_ret, opts));
|
||||
}
|
||||
// intercepted
|
||||
return 1;
|
||||
@@ -313,35 +319,41 @@ fn isInErrorSet(err: anyerror, comptime T: type) bool {
|
||||
return false;
|
||||
}
|
||||
|
||||
fn nameToString(self: *const Caller, comptime T: type, name: *const v8.Name) !T {
|
||||
const v8_string = @as(*const v8.String, @ptrCast(name));
|
||||
fn nameToString(local: *const Local, comptime T: type, name: *const v8.Name) !T {
|
||||
const handle = @as(*const v8.String, @ptrCast(name));
|
||||
if (T == string.String) {
|
||||
return self.local.jsStringToStringSSO(v8_string, .{});
|
||||
return js.String.toSSO(.{ .local = local, .handle = handle }, false);
|
||||
}
|
||||
if (T == string.Global) {
|
||||
return self.local.jsStringToStringSSO(v8_string, .{ .allocator = self.local.ctx.allocator });
|
||||
return js.String.toSSO(.{ .local = local, .handle = handle }, true);
|
||||
}
|
||||
return try self.local.valueHandleToString(v8_string, .{});
|
||||
return try js.String.toSlice(.{ .local = local, .handle = handle });
|
||||
}
|
||||
|
||||
fn handleError(self: *Caller, comptime T: type, comptime F: type, err: anyerror, info: anytype, comptime opts: CallOpts) void {
|
||||
const isolate = self.local.isolate;
|
||||
fn handleError(comptime T: type, comptime F: type, local: *const Local, err: anyerror, info: anytype, comptime opts: CallOpts) void {
|
||||
const isolate = local.isolate;
|
||||
|
||||
if (comptime @import("builtin").mode == .Debug and @TypeOf(info) == FunctionCallbackInfo) {
|
||||
if (log.enabled(.js, .warn)) {
|
||||
self.logFunctionCallError(@typeName(T), @typeName(F), err, info);
|
||||
if (comptime IS_DEBUG and @TypeOf(info) == FunctionCallbackInfo) {
|
||||
if (log.enabled(.js, .debug)) {
|
||||
const DOMException = @import("../webapi/DOMException.zig");
|
||||
if (DOMException.fromError(err) == null) {
|
||||
// This isn't a DOMException, let's log it
|
||||
logFunctionCallError(local, @typeName(T), @typeName(F), err, info);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const js_err: *const v8.Value = switch (err) {
|
||||
error.TryCatchRethrow => return,
|
||||
error.InvalidArgument => isolate.createTypeError("invalid argument"),
|
||||
error.TypeError => isolate.createTypeError(""),
|
||||
error.OutOfMemory => isolate.createError("out of memory"),
|
||||
error.IllegalConstructor => isolate.createError("Illegal Contructor"),
|
||||
else => blk: {
|
||||
if (comptime opts.dom_exception) {
|
||||
const DOMException = @import("../webapi/DOMException.zig");
|
||||
if (DOMException.fromError(err)) |ex| {
|
||||
const value = self.local.zigValueToJs(ex, .{}) catch break :blk isolate.createError("internal error");
|
||||
const value = local.zigValueToJs(ex, .{}) catch break :blk isolate.createError("internal error");
|
||||
break :blk value.handle;
|
||||
}
|
||||
}
|
||||
@@ -353,6 +365,320 @@ fn handleError(self: *Caller, comptime T: type, comptime F: type, err: anyerror,
|
||||
info.getReturnValue().setValueHandle(js_exception);
|
||||
}
|
||||
|
||||
// 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(local: *const Local, type_name: []const u8, func: []const u8, err: anyerror, info: FunctionCallbackInfo) void {
|
||||
const args_dump = serializeFunctionArgs(local, info) catch "failed to serialize args";
|
||||
log.debug(.js, "function call error", .{
|
||||
.type = type_name,
|
||||
.func = func,
|
||||
.err = err,
|
||||
.args = args_dump,
|
||||
.stack = local.stackTrace() catch |err1| @errorName(err1),
|
||||
});
|
||||
}
|
||||
|
||||
fn serializeFunctionArgs(local: *const Local, info: FunctionCallbackInfo) ![]const u8 {
|
||||
var buf = std.Io.Writer.Allocating.init(local.call_arena);
|
||||
|
||||
const separator = log.separator();
|
||||
for (0..info.length()) |i| {
|
||||
try buf.writer.print("{s}{d} - ", .{ separator, i + 1 });
|
||||
const js_value = info.getArg(@intCast(i), local);
|
||||
try local.debugValue(js_value, &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;
|
||||
}
|
||||
|
||||
// These wrap the raw v8 C API to provide a cleaner interface.
|
||||
pub const FunctionCallbackInfo = struct {
|
||||
handle: *const v8.FunctionCallbackInfo,
|
||||
|
||||
pub fn length(self: FunctionCallbackInfo) u32 {
|
||||
return @intCast(v8.v8__FunctionCallbackInfo__Length(self.handle));
|
||||
}
|
||||
|
||||
pub fn getArg(self: FunctionCallbackInfo, index: u32, local: *const js.Local) js.Value {
|
||||
return .{ .local = local, .handle = v8.v8__FunctionCallbackInfo__INDEX(self.handle, @intCast(index)).? };
|
||||
}
|
||||
|
||||
pub fn getData(self: FunctionCallbackInfo) ?*anyopaque {
|
||||
const data = v8.v8__FunctionCallbackInfo__Data(self.handle) orelse return null;
|
||||
return v8.v8__External__Value(@ptrCast(data));
|
||||
}
|
||||
|
||||
pub fn getThis(self: FunctionCallbackInfo) *const v8.Object {
|
||||
return v8.v8__FunctionCallbackInfo__This(self.handle).?;
|
||||
}
|
||||
|
||||
pub fn getReturnValue(self: FunctionCallbackInfo) ReturnValue {
|
||||
var rv: v8.ReturnValue = undefined;
|
||||
v8.v8__FunctionCallbackInfo__GetReturnValue(self.handle, &rv);
|
||||
return .{ .handle = rv };
|
||||
}
|
||||
|
||||
fn isConstructCall(self: FunctionCallbackInfo) bool {
|
||||
return v8.v8__FunctionCallbackInfo__IsConstructCall(self.handle);
|
||||
}
|
||||
};
|
||||
|
||||
pub const PropertyCallbackInfo = struct {
|
||||
handle: *const v8.PropertyCallbackInfo,
|
||||
|
||||
pub fn getThis(self: PropertyCallbackInfo) *const v8.Object {
|
||||
return v8.v8__PropertyCallbackInfo__This(self.handle).?;
|
||||
}
|
||||
|
||||
pub fn getReturnValue(self: PropertyCallbackInfo) ReturnValue {
|
||||
var rv: v8.ReturnValue = undefined;
|
||||
v8.v8__PropertyCallbackInfo__GetReturnValue(self.handle, &rv);
|
||||
return .{ .handle = rv };
|
||||
}
|
||||
};
|
||||
|
||||
const ReturnValue = struct {
|
||||
handle: v8.ReturnValue,
|
||||
|
||||
pub fn set(self: ReturnValue, value: anytype) void {
|
||||
const T = @TypeOf(value);
|
||||
if (T == *const v8.Object) {
|
||||
self.setValueHandle(@ptrCast(value));
|
||||
} else if (T == *const v8.Value) {
|
||||
self.setValueHandle(value);
|
||||
} else if (T == js.Value) {
|
||||
self.setValueHandle(value.handle);
|
||||
} else {
|
||||
@compileError("Unsupported type for ReturnValue.set: " ++ @typeName(T));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn setValueHandle(self: ReturnValue, handle: *const v8.Value) void {
|
||||
v8.v8__ReturnValue__Set(self.handle, handle);
|
||||
}
|
||||
};
|
||||
|
||||
pub const Function = struct {
|
||||
pub const Opts = struct {
|
||||
noop: bool = false,
|
||||
static: bool = false,
|
||||
dom_exception: bool = false,
|
||||
as_typed_array: bool = false,
|
||||
null_as_undefined: bool = false,
|
||||
cache: ?Caching = null,
|
||||
embedded_receiver: bool = false,
|
||||
|
||||
// We support two ways to cache a value directly into a v8::Object. The
|
||||
// difference between the two is like the difference between a Map
|
||||
// and a Struct.
|
||||
// 1 - Using the object's internal fields. Think of this as
|
||||
// adding a field to the struct. It's fast, but the space is reserved
|
||||
// upfront for _every_ instance, whether we use it or not.
|
||||
//
|
||||
// 2 - Using the object's private state with a v8::Private key. Think of
|
||||
// this as a HashMap. It takes no memory if the cache isn't used
|
||||
// but has overhead when used.
|
||||
//
|
||||
// Consider `window.document`, (1) we have relatively few Window objects,
|
||||
// (2) They all have a document and (3) The document is accessed _a lot_.
|
||||
// An internal field makes sense.
|
||||
//
|
||||
// Consider `node.childNodes`, (1) we can have 20K+ node objects, (2)
|
||||
// 95% of nodes will never have their .childNodes access by JavaScript.
|
||||
// Private map lookup makes sense.
|
||||
pub const Caching = union(enum) {
|
||||
internal: u8,
|
||||
private: []const u8,
|
||||
};
|
||||
};
|
||||
|
||||
pub fn call(comptime T: type, info_handle: *const v8.FunctionCallbackInfo, func: anytype, comptime opts: Opts) void {
|
||||
const v8_isolate = v8.v8__FunctionCallbackInfo__GetIsolate(info_handle).?;
|
||||
const v8_context = v8.v8__Isolate__GetCurrentContext(v8_isolate).?;
|
||||
|
||||
const ctx = Context.fromC(v8_context);
|
||||
const info = FunctionCallbackInfo{ .handle = info_handle };
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.initWithIsolateHandle(v8_isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
var cache_state: CacheState = undefined;
|
||||
if (comptime opts.cache) |cache| {
|
||||
// This API is a bit weird. On
|
||||
if (respondFromCache(cache, ctx, v8_context, info, &cache_state)) {
|
||||
// Value was fetched from the cache and returned already
|
||||
return;
|
||||
} else {
|
||||
// Cache miss: cache_state will have been populated
|
||||
}
|
||||
}
|
||||
|
||||
var caller: Caller = undefined;
|
||||
caller.initWithContext(ctx, v8_context);
|
||||
defer caller.deinit();
|
||||
|
||||
const js_value = _call(T, &caller.local, info, func, opts) catch |err| {
|
||||
handleError(T, @TypeOf(func), &caller.local, err, info, .{
|
||||
.dom_exception = opts.dom_exception,
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
return;
|
||||
};
|
||||
|
||||
if (comptime opts.cache) |cache| {
|
||||
cache_state.save(cache, js_value);
|
||||
}
|
||||
}
|
||||
|
||||
fn _call(comptime T: type, local: *const Local, info: FunctionCallbackInfo, func: anytype, comptime opts: Opts) !js.Value {
|
||||
const F = @TypeOf(func);
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
if (comptime opts.static) {
|
||||
args = try getArgs(F, 0, local, info);
|
||||
} else if (comptime opts.embedded_receiver) {
|
||||
args = try getArgs(F, 1, local, info);
|
||||
@field(args, "0") = @ptrCast(@alignCast(info.getData() orelse unreachable));
|
||||
} else {
|
||||
args = try getArgs(F, 1, local, info);
|
||||
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
|
||||
}
|
||||
const res = @call(.auto, func, args);
|
||||
const js_value = try local.zigValueToJs(res, .{
|
||||
.dom_exception = opts.dom_exception,
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
info.getReturnValue().set(js_value);
|
||||
return js_value;
|
||||
}
|
||||
|
||||
// We can cache a value directly into the v8::Object so that our callback to fetch a property
|
||||
// can be fast. Generally, think of it like this:
|
||||
// fn callback(handle: *const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
// const js_obj = info.getThis();
|
||||
// const cached_value = js_obj.getFromCache("Nodes.childNodes");
|
||||
// info.returnValue().set(cached_value);
|
||||
// }
|
||||
//
|
||||
// That above pseudocode snippet is largely what this respondFromCache is doing.
|
||||
// But on miss, it's also setting the `cache_state` with all of the data it
|
||||
// got checking the cache, so that, once we get the value from our Zig code,
|
||||
// it's quick to store in the v8::Object for subsequent calls.
|
||||
fn respondFromCache(comptime cache: Opts.Caching, ctx: *Context, v8_context: *const v8.Context, info: FunctionCallbackInfo, cache_state: *CacheState) bool {
|
||||
const js_this = info.getThis();
|
||||
const return_value = info.getReturnValue();
|
||||
|
||||
switch (cache) {
|
||||
.internal => |idx| {
|
||||
if (v8.v8__Object__GetInternalField(js_this, idx)) |cached| {
|
||||
// means we can't cache undefined, since we can't tell the
|
||||
// difference between "it isn't in the cache" and "it's
|
||||
// in the cache with a valud of undefined"
|
||||
if (!v8.v8__Value__IsUndefined(cached)) {
|
||||
return_value.set(cached);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// store this so that we can quickly save the result into the cache
|
||||
cache_state.* = .{
|
||||
.js_this = js_this,
|
||||
.v8_context = v8_context,
|
||||
.mode = .{ .internal = idx },
|
||||
};
|
||||
},
|
||||
.private => |private_symbol| {
|
||||
const global_handle = &@field(ctx.env.private_symbols, private_symbol).handle;
|
||||
const private_key: *const v8.Private = v8.v8__Global__Get(global_handle, ctx.isolate.handle).?;
|
||||
if (v8.v8__Object__GetPrivate(js_this, v8_context, private_key)) |cached| {
|
||||
// This means we can't cache "undefined", since we can't tell
|
||||
// the difference between a (a) undefined == not in the cache
|
||||
// and (b) undefined == the cache value. If this becomes
|
||||
// important, we can check HasPrivate first. But that requires
|
||||
// calling HasPrivate then GetPrivate.
|
||||
if (!v8.v8__Value__IsUndefined(cached)) {
|
||||
return_value.set(cached);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// store this so that we can quickly save the result into the cache
|
||||
cache_state.* = .{
|
||||
.js_this = js_this,
|
||||
.v8_context = v8_context,
|
||||
.mode = .{ .private = private_key },
|
||||
};
|
||||
},
|
||||
}
|
||||
|
||||
// cache miss
|
||||
return false;
|
||||
}
|
||||
|
||||
const CacheState = struct {
|
||||
js_this: *const v8.Object,
|
||||
v8_context: *const v8.Context,
|
||||
mode: union(enum) {
|
||||
internal: u8,
|
||||
private: *const v8.Private,
|
||||
},
|
||||
|
||||
pub fn save(self: *const CacheState, comptime cache: Opts.Caching, js_value: js.Value) void {
|
||||
if (comptime cache == .internal) {
|
||||
v8.v8__Object__SetInternalField(self.js_this, self.mode.internal, js_value.handle);
|
||||
} else {
|
||||
var out: v8.MaybeBool = undefined;
|
||||
v8.v8__Object__SetPrivate(self.js_this, self.v8_context, self.mode.private, js_value.handle, &out);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// 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.
|
||||
@@ -366,8 +692,7 @@ fn handleError(self: *Caller, comptime T: type, comptime F: type, err: anyerror,
|
||||
// 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 local = &self.local;
|
||||
fn getArgs(comptime F: type, comptime offset: usize, local: *const Local, info: FunctionCallbackInfo) !ParameterTypes(F) {
|
||||
var args: ParameterTypes(F) = undefined;
|
||||
|
||||
const params = @typeInfo(F).@"fn".params[offset..];
|
||||
@@ -451,135 +776,3 @@ fn getArgs(self: *const Caller, comptime F: type, comptime offset: usize, info:
|
||||
|
||||
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: 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.local.stackTrace() catch |err1| @errorName(err1),
|
||||
});
|
||||
}
|
||||
|
||||
fn serializeFunctionArgs(self: *Caller, info: FunctionCallbackInfo) ![]const u8 {
|
||||
const local = &self.local;
|
||||
var buf = std.Io.Writer.Allocating.init(local.call_arena);
|
||||
|
||||
const separator = log.separator();
|
||||
for (0..info.length()) |i| {
|
||||
try buf.writer.print("{s}{d} - ", .{ separator, i + 1 });
|
||||
const js_value = info.getArg(@intCast(i), local);
|
||||
try local.debugValue(js_value, &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;
|
||||
}
|
||||
|
||||
// These wrap the raw v8 C API to provide a cleaner interface.
|
||||
pub const FunctionCallbackInfo = struct {
|
||||
handle: *const v8.FunctionCallbackInfo,
|
||||
|
||||
pub fn length(self: FunctionCallbackInfo) u32 {
|
||||
return @intCast(v8.v8__FunctionCallbackInfo__Length(self.handle));
|
||||
}
|
||||
|
||||
pub fn getArg(self: FunctionCallbackInfo, index: u32, local: *const js.Local) js.Value {
|
||||
return .{ .local = local, .handle = v8.v8__FunctionCallbackInfo__INDEX(self.handle, @intCast(index)).? };
|
||||
}
|
||||
|
||||
pub fn getThis(self: FunctionCallbackInfo) *const v8.Object {
|
||||
return v8.v8__FunctionCallbackInfo__This(self.handle).?;
|
||||
}
|
||||
|
||||
pub fn getReturnValue(self: FunctionCallbackInfo) ReturnValue {
|
||||
var rv: v8.ReturnValue = undefined;
|
||||
v8.v8__FunctionCallbackInfo__GetReturnValue(self.handle, &rv);
|
||||
return .{ .handle = rv };
|
||||
}
|
||||
|
||||
fn isConstructCall(self: FunctionCallbackInfo) bool {
|
||||
return v8.v8__FunctionCallbackInfo__IsConstructCall(self.handle);
|
||||
}
|
||||
};
|
||||
|
||||
pub const PropertyCallbackInfo = struct {
|
||||
handle: *const v8.PropertyCallbackInfo,
|
||||
|
||||
pub fn getThis(self: PropertyCallbackInfo) *const v8.Object {
|
||||
return v8.v8__PropertyCallbackInfo__This(self.handle).?;
|
||||
}
|
||||
|
||||
pub fn getReturnValue(self: PropertyCallbackInfo) ReturnValue {
|
||||
var rv: v8.ReturnValue = undefined;
|
||||
v8.v8__PropertyCallbackInfo__GetReturnValue(self.handle, &rv);
|
||||
return .{ .handle = rv };
|
||||
}
|
||||
};
|
||||
|
||||
const ReturnValue = struct {
|
||||
handle: v8.ReturnValue,
|
||||
|
||||
pub fn set(self: ReturnValue, value: anytype) void {
|
||||
const T = @TypeOf(value);
|
||||
if (T == *const v8.Object) {
|
||||
self.setValueHandle(@ptrCast(value));
|
||||
} else if (T == *const v8.Value) {
|
||||
self.setValueHandle(value);
|
||||
} else if (T == js.Value) {
|
||||
self.setValueHandle(value.handle);
|
||||
} else {
|
||||
@compileError("Unsupported type for ReturnValue.set: " ++ @typeName(T));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn setValueHandle(self: ReturnValue, handle: *const v8.Value) void {
|
||||
v8.v8__ReturnValue__Set(self.handle, handle);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -21,8 +21,9 @@ const lp = @import("lightpanda");
|
||||
const log = @import("../../log.zig");
|
||||
|
||||
const js = @import("js.zig");
|
||||
const Env = @import("Env.zig");
|
||||
const bridge = @import("bridge.zig");
|
||||
const TaggedOpaque = @import("TaggedOpaque.zig");
|
||||
const Scheduler = @import("Scheduler.zig");
|
||||
|
||||
const Page = @import("../Page.zig");
|
||||
const ScriptManager = @import("../ScriptManager.zig");
|
||||
@@ -38,16 +39,17 @@ const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
const Context = @This();
|
||||
|
||||
id: usize,
|
||||
env: *Env,
|
||||
page: *Page,
|
||||
isolate: js.Isolate,
|
||||
|
||||
// Per-context microtask queue for isolation between contexts
|
||||
microtask_queue: *v8.MicrotaskQueue,
|
||||
|
||||
// The v8::Global<v8::Context>. When necessary, we can create a v8::Local<<v8::Context>>
|
||||
// from this, and we can free it when the context is done.
|
||||
handle: v8.Global,
|
||||
|
||||
// True if the context is auto-entered,
|
||||
entered: bool,
|
||||
|
||||
cpu_profiler: ?*v8.CpuProfiler = null,
|
||||
|
||||
heap_profiler: ?*v8.HeapProfiler = null,
|
||||
@@ -82,7 +84,8 @@ identity_map: std.AutoHashMapUnmanaged(usize, v8.Global) = .empty,
|
||||
// Any type that is stored in the identity_map which has a finalizer declared
|
||||
// will have its finalizer stored here. This is only used when shutting down
|
||||
// if v8 hasn't called the finalizer directly itself.
|
||||
finalizer_callbacks: std.AutoHashMapUnmanaged(usize, FinalizerCallback) = .empty,
|
||||
finalizer_callbacks: std.AutoHashMapUnmanaged(usize, *FinalizerCallback) = .empty,
|
||||
finalizer_callback_pool: std.heap.MemoryPool(FinalizerCallback),
|
||||
|
||||
// Some web APIs have to manage opaque values. Ideally, they use an
|
||||
// js.Object, but the js.Object has no lifetime guarantee beyond the
|
||||
@@ -102,6 +105,7 @@ global_promise_resolvers: std.ArrayList(v8.Global) = .empty,
|
||||
// Temp variants stored in HashMaps for O(1) early cleanup.
|
||||
// Key is global.data_ptr.
|
||||
global_values_temp: std.AutoHashMapUnmanaged(usize, v8.Global) = .empty,
|
||||
global_promises_temp: std.AutoHashMapUnmanaged(usize, v8.Global) = .empty,
|
||||
global_functions_temp: std.AutoHashMapUnmanaged(usize, v8.Global) = .empty,
|
||||
|
||||
// Our module cache: normalized module specifier => module.
|
||||
@@ -117,6 +121,11 @@ module_identifier: std.AutoHashMapUnmanaged(u32, [:0]const u8) = .empty,
|
||||
// the page's script manager
|
||||
script_manager: ?*ScriptManager,
|
||||
|
||||
// Our macrotasks
|
||||
scheduler: Scheduler,
|
||||
|
||||
unknown_properties: (if (IS_DEBUG) std.StringHashMapUnmanaged(UnknownPropertyStat) else void) = if (IS_DEBUG) .{} else {},
|
||||
|
||||
const ModuleEntry = struct {
|
||||
// Can be null if we're asynchrously loading the module, in
|
||||
// which case resolver_promise cannot be null.
|
||||
@@ -135,20 +144,36 @@ const ModuleEntry = struct {
|
||||
resolver_promise: ?js.Promise.Global = null,
|
||||
};
|
||||
|
||||
fn fromC(c_context: *const v8.Context) *Context {
|
||||
const data = v8.v8__Context__GetEmbedderData(c_context, 1).?;
|
||||
const big_int = js.BigInt{ .handle = @ptrCast(data) };
|
||||
return @ptrFromInt(big_int.getUint64());
|
||||
pub fn fromC(c_context: *const v8.Context) *Context {
|
||||
return @ptrCast(@alignCast(v8.v8__Context__GetAlignedPointerFromEmbedderData(c_context, 1)));
|
||||
}
|
||||
|
||||
pub fn fromIsolate(isolate: js.Isolate) *Context {
|
||||
const v8_context = v8.v8__Isolate__GetCurrentContext(isolate.handle).?;
|
||||
const data = v8.v8__Context__GetEmbedderData(v8_context, 1).?;
|
||||
const big_int = js.BigInt{ .handle = @ptrCast(data) };
|
||||
return @ptrFromInt(big_int.getUint64());
|
||||
return fromC(v8.v8__Isolate__GetCurrentContext(isolate.handle).?);
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Context) void {
|
||||
if (comptime IS_DEBUG) {
|
||||
var it = self.unknown_properties.iterator();
|
||||
while (it.next()) |kv| {
|
||||
log.debug(.unknown_prop, "unknown property", .{
|
||||
.property = kv.key_ptr.*,
|
||||
.occurrences = kv.value_ptr.count,
|
||||
.first_stack = kv.value_ptr.first_stack,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const env = self.env;
|
||||
defer env.app.arena_pool.release(self.arena);
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
const entered = self.enter(&hs);
|
||||
defer entered.exit();
|
||||
|
||||
// this can release objects
|
||||
self.scheduler.deinit();
|
||||
|
||||
{
|
||||
var it = self.identity_map.valueIterator();
|
||||
while (it.next()) |global| {
|
||||
@@ -158,8 +183,9 @@ pub fn deinit(self: *Context) void {
|
||||
{
|
||||
var it = self.finalizer_callbacks.valueIterator();
|
||||
while (it.next()) |finalizer| {
|
||||
finalizer.deinit();
|
||||
finalizer.*.deinit();
|
||||
}
|
||||
self.finalizer_callback_pool.deinit();
|
||||
}
|
||||
|
||||
for (self.global_values.items) |*global| {
|
||||
@@ -193,6 +219,13 @@ pub fn deinit(self: *Context) void {
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var it = self.global_promises_temp.valueIterator();
|
||||
while (it.next()) |global| {
|
||||
v8.v8__Global__Reset(global);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
var it = self.global_functions_temp.valueIterator();
|
||||
while (it.next()) |global| {
|
||||
@@ -200,35 +233,46 @@ pub fn deinit(self: *Context) void {
|
||||
}
|
||||
}
|
||||
|
||||
if (self.entered) {
|
||||
var ls: js.Local.Scope = undefined;
|
||||
self.localScope(&ls);
|
||||
defer ls.deinit();
|
||||
v8.v8__Context__Exit(ls.local.handle);
|
||||
}
|
||||
v8.v8__Global__Reset(&self.handle);
|
||||
env.isolate.notifyContextDisposed();
|
||||
// There can be other tasks associated with this context that we need to
|
||||
// purge while the context is still alive.
|
||||
_ = env.pumpMessageLoop();
|
||||
v8.v8__MicrotaskQueue__DELETE(self.microtask_queue);
|
||||
}
|
||||
|
||||
pub fn weakRef(self: *Context, obj: anytype) void {
|
||||
const global = self.identity_map.getPtr(@intFromPtr(obj)) orelse {
|
||||
const fc = self.finalizer_callbacks.get(@intFromPtr(obj)) orelse {
|
||||
if (comptime IS_DEBUG) {
|
||||
// should not be possible
|
||||
std.debug.assert(false);
|
||||
}
|
||||
return;
|
||||
};
|
||||
v8.v8__Global__SetWeakFinalizer(global, obj, bridge.Struct(@TypeOf(obj)).JsApi.Meta.finalizer.from_v8, v8.kParameter);
|
||||
v8.v8__Global__SetWeakFinalizer(&fc.global, fc, bridge.Struct(@TypeOf(obj)).JsApi.Meta.finalizer.from_v8, v8.kParameter);
|
||||
}
|
||||
|
||||
pub fn safeWeakRef(self: *Context, obj: anytype) void {
|
||||
const fc = self.finalizer_callbacks.get(@intFromPtr(obj)) orelse {
|
||||
if (comptime IS_DEBUG) {
|
||||
// should not be possible
|
||||
std.debug.assert(false);
|
||||
}
|
||||
return;
|
||||
};
|
||||
v8.v8__Global__ClearWeak(&fc.global);
|
||||
v8.v8__Global__SetWeakFinalizer(&fc.global, fc, bridge.Struct(@TypeOf(obj)).JsApi.Meta.finalizer.from_v8, v8.kParameter);
|
||||
}
|
||||
|
||||
pub fn strongRef(self: *Context, obj: anytype) void {
|
||||
const global = self.identity_map.getPtr(@intFromPtr(obj)) orelse {
|
||||
const fc = self.finalizer_callbacks.get(@intFromPtr(obj)) orelse {
|
||||
if (comptime IS_DEBUG) {
|
||||
// should not be possible
|
||||
std.debug.assert(false);
|
||||
}
|
||||
return;
|
||||
};
|
||||
v8.v8__Global__ClearWeak(global);
|
||||
v8.v8__Global__ClearWeak(&fc.global);
|
||||
}
|
||||
|
||||
pub fn release(self: *Context, item: anytype) void {
|
||||
@@ -246,17 +290,20 @@ pub fn release(self: *Context, item: anytype) void {
|
||||
|
||||
// The item has been fianalized, remove it for the finalizer callback so that
|
||||
// we don't try to call it again on shutdown.
|
||||
_ = self.finalizer_callbacks.fetchRemove(@intFromPtr(item)) orelse {
|
||||
const fc = self.finalizer_callbacks.fetchRemove(@intFromPtr(item)) orelse {
|
||||
if (comptime IS_DEBUG) {
|
||||
// should not be possible
|
||||
std.debug.assert(false);
|
||||
}
|
||||
return;
|
||||
};
|
||||
self.finalizer_callback_pool.destroy(fc.value);
|
||||
return;
|
||||
}
|
||||
|
||||
var map = switch (@TypeOf(item)) {
|
||||
js.Value.Temp => &self.global_values_temp,
|
||||
js.Promise.Temp => &self.global_promises_temp,
|
||||
js.Function.Temp => &self.global_functions_temp,
|
||||
else => |T| @compileError("Context.release cannot be called with a " ++ @typeName(T)),
|
||||
};
|
||||
@@ -272,11 +319,14 @@ pub fn localScope(self: *Context, ls: *js.Local.Scope) void {
|
||||
const isolate = self.isolate;
|
||||
js.HandleScope.init(&ls.handle_scope, isolate);
|
||||
|
||||
const local_v8_context: *const v8.Context = @ptrCast(v8.v8__Global__Get(&self.handle, isolate.handle));
|
||||
v8.v8__Context__Enter(local_v8_context);
|
||||
|
||||
// TODO: add and init ls.hs for the handlescope
|
||||
ls.local = .{
|
||||
.ctx = self,
|
||||
.handle = @ptrCast(v8.v8__Global__Get(&self.handle, isolate.handle)),
|
||||
.isolate = isolate,
|
||||
.handle = local_v8_context,
|
||||
.call_arena = self.call_arena,
|
||||
};
|
||||
}
|
||||
@@ -303,7 +353,6 @@ pub fn stringToPersistedFunction(self: *Context, str: []const u8) !js.Function.G
|
||||
extra = "(e)";
|
||||
}
|
||||
const full = try std.fmt.allocPrintSentinel(self.call_arena, "(function(e) {{ {s}{s} }})", .{ normalized, extra }, 0);
|
||||
|
||||
const js_val = try ls.local.compileAndRun(full, null);
|
||||
if (!js_val.isFunction()) {
|
||||
return error.StringFunctionError;
|
||||
@@ -320,7 +369,25 @@ pub fn module(self: *Context, comptime want_result: bool, local: *const js.Local
|
||||
if (cacheable) {
|
||||
gop = try self.module_cache.getOrPut(arena, url);
|
||||
if (gop.found_existing) {
|
||||
if (gop.value_ptr.module != null) {
|
||||
if (gop.value_ptr.module) |cache_mod| {
|
||||
if (gop.value_ptr.module_promise == null) {
|
||||
// This an usual case, but it can happen if a module is
|
||||
// first asynchronously requested and then synchronously
|
||||
// requested as a child of some root import. In that case,
|
||||
// the module may not be instantiated yet (so we have to
|
||||
// do that). It might not be evaluated yet. So we have
|
||||
// to do that too. Evaluation is particularly important
|
||||
// as it sets up our cache entry's module_promise.
|
||||
// It appears that v8 handles potential double-instantiated
|
||||
// and double-evaluated modules safely. The 2nd instantiation
|
||||
// is a no-op, and the second evaluation returns the same
|
||||
// promise.
|
||||
const mod = local.toLocal(cache_mod);
|
||||
if (mod.getStatus() == .kUninstantiated and try mod.instantiate(resolveModuleCallback) == false) {
|
||||
return error.ModuleInstantiationError;
|
||||
}
|
||||
return self.evaluateModule(want_result, mod, url, true);
|
||||
}
|
||||
return if (comptime want_result) gop.value_ptr.* else {};
|
||||
}
|
||||
} else {
|
||||
@@ -350,6 +417,10 @@ pub fn module(self: *Context, comptime want_result: bool, local: *const js.Local
|
||||
return error.ModuleInstantiationError;
|
||||
}
|
||||
|
||||
return self.evaluateModule(want_result, mod, owned_url, cacheable);
|
||||
}
|
||||
|
||||
fn evaluateModule(self: *Context, comptime want_result: bool, mod: js.Module, url: []const u8, cacheable: bool) !(if (want_result) ModuleEntry else void) {
|
||||
const evaluated = mod.evaluate() catch {
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(mod.getStatus() == .kErrored);
|
||||
@@ -357,9 +428,13 @@ pub fn module(self: *Context, comptime want_result: bool, local: *const js.Local
|
||||
|
||||
// Some module-loading errors aren't handled by TryCatch. We need to
|
||||
// get the error from the module itself.
|
||||
const message = blk: {
|
||||
const e = mod.getException().toString() catch break :blk "???";
|
||||
break :blk e.toSlice() catch "???";
|
||||
};
|
||||
log.warn(.js, "evaluate module", .{
|
||||
.specifier = owned_url,
|
||||
.message = mod.getException().toString(.{}) catch "???",
|
||||
.message = message,
|
||||
.specifier = url,
|
||||
});
|
||||
return error.EvaluationError;
|
||||
};
|
||||
@@ -368,24 +443,15 @@ pub fn module(self: *Context, comptime want_result: bool, local: *const js.Local
|
||||
// Must be a promise that gets returned here.
|
||||
lp.assert(evaluated.isPromise(), "Context.module non-promise", .{});
|
||||
|
||||
if (comptime !want_result) {
|
||||
// avoid creating a bunch of persisted objects if it isn't
|
||||
// cacheable and the caller doesn't care about results.
|
||||
// This is pretty common, i.e. every <script type=module>
|
||||
// within the html page.
|
||||
if (!cacheable) {
|
||||
return;
|
||||
if (!cacheable) {
|
||||
switch (comptime want_result) {
|
||||
false => return,
|
||||
true => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
// anyone who cares about the result, should also want it to
|
||||
// be cached
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(cacheable);
|
||||
}
|
||||
|
||||
// entry has to have been created atop this function
|
||||
const entry = self.module_cache.getPtr(owned_url).?;
|
||||
const entry = self.module_cache.getPtr(url).?;
|
||||
|
||||
// and the module must have been set after we compiled it
|
||||
lp.assert(entry.module != null, "Context.module with module", .{});
|
||||
@@ -457,11 +523,11 @@ fn postCompileModule(self: *Context, mod: js.Module, url: [:0]const u8, local: *
|
||||
const request_len = requests.len();
|
||||
const script_manager = self.script_manager.?;
|
||||
for (0..request_len) |i| {
|
||||
const specifier = try local.jsStringToZigZ(requests.get(i).specifier(), .{});
|
||||
const specifier = requests.get(i).specifier(local);
|
||||
const normalized_specifier = try script_manager.resolveSpecifier(
|
||||
self.call_arena,
|
||||
url,
|
||||
specifier,
|
||||
try specifier.toSliceZ(),
|
||||
);
|
||||
const nested_gop = try self.module_cache.getOrPut(self.arena, normalized_specifier);
|
||||
if (!nested_gop.found_existing) {
|
||||
@@ -494,14 +560,14 @@ fn resolveModuleCallback(
|
||||
_ = import_attributes;
|
||||
|
||||
const self = fromC(c_context.?);
|
||||
var local = js.Local{
|
||||
const local = js.Local{
|
||||
.ctx = self,
|
||||
.handle = c_context.?,
|
||||
.isolate = self.isolate,
|
||||
.call_arena = self.call_arena,
|
||||
};
|
||||
|
||||
const specifier = local.jsStringToZigZ(c_specifier.?, .{}) catch |err| {
|
||||
const specifier = js.String.toSliceZ(.{ .local = &local, .handle = c_specifier.? }) catch |err| {
|
||||
log.err(.js, "resolve module", .{ .err = err });
|
||||
return null;
|
||||
};
|
||||
@@ -527,19 +593,28 @@ pub fn dynamicModuleCallback(
|
||||
_ = import_attrs;
|
||||
|
||||
const self = fromC(c_context.?);
|
||||
var local = js.Local{
|
||||
const local = js.Local{
|
||||
.ctx = self,
|
||||
.handle = c_context.?,
|
||||
.call_arena = self.call_arena,
|
||||
.isolate = self.isolate,
|
||||
};
|
||||
|
||||
const resource = local.jsStringToZigZ(resource_name.?, .{}) catch |err| {
|
||||
log.err(.app, "OOM", .{ .err = err, .src = "dynamicModuleCallback1" });
|
||||
return @constCast((local.rejectPromise("Out of memory") catch return null).handle);
|
||||
const resource = blk: {
|
||||
const resource_value = js.Value{ .handle = resource_name.?, .local = &local };
|
||||
if (resource_value.isNullOrUndefined()) {
|
||||
// will only be null / undefined in extreme cases (e.g. WPT tests)
|
||||
// where you're
|
||||
break :blk self.page.base();
|
||||
}
|
||||
|
||||
break :blk js.String.toSliceZ(.{ .local = &local, .handle = resource_name.? }) catch |err| {
|
||||
log.err(.app, "OOM", .{ .err = err, .src = "dynamicModuleCallback1" });
|
||||
return @constCast((local.rejectPromise("Out of memory") catch return null).handle);
|
||||
};
|
||||
};
|
||||
|
||||
const specifier = local.jsStringToZigZ(v8_specifier.?, .{}) catch |err| {
|
||||
const specifier = js.String.toSliceZ(.{ .local = &local, .handle = v8_specifier.? }) catch |err| {
|
||||
log.err(.app, "OOM", .{ .err = err, .src = "dynamicModuleCallback2" });
|
||||
return @constCast((local.rejectPromise("Out of memory") catch return null).handle);
|
||||
};
|
||||
@@ -684,6 +759,9 @@ fn _dynamicModuleCallback(self: *Context, specifier: [:0]const u8, referrer: []c
|
||||
return promise;
|
||||
}
|
||||
|
||||
// we might update the map, so we might need to re-fetch this.
|
||||
var entry = gop.value_ptr;
|
||||
|
||||
// So we have a module, but no async resolver. This can only
|
||||
// happen if the module was first synchronously loaded (Does that
|
||||
// ever even happen?!) You'd think we can just return the module
|
||||
@@ -696,7 +774,7 @@ fn _dynamicModuleCallback(self: *Context, specifier: [:0]const u8, referrer: []c
|
||||
|
||||
// If the module hasn't been evaluated yet (it was only instantiated
|
||||
// as a static import dependency), we need to evaluate it now.
|
||||
if (gop.value_ptr.module_promise == null) {
|
||||
if (entry.module_promise == null) {
|
||||
const mod = local.toLocal(gop.value_ptr.module.?);
|
||||
const status = mod.getStatus();
|
||||
if (status == .kEvaluated or status == .kEvaluating) {
|
||||
@@ -705,29 +783,38 @@ fn _dynamicModuleCallback(self: *Context, specifier: [:0]const u8, referrer: []c
|
||||
const module_resolver = local.createPromiseResolver();
|
||||
module_resolver.resolve("resolve module", mod.getModuleNamespace());
|
||||
_ = try module_resolver.persist();
|
||||
gop.value_ptr.module_promise = try module_resolver.promise().persist();
|
||||
entry.module_promise = try module_resolver.promise().persist();
|
||||
} else {
|
||||
// the module was loaded, but not evaluated, we _have_ to evaluate it now
|
||||
if (status == .kUninstantiated) {
|
||||
if (try mod.instantiate(resolveModuleCallback) == false) {
|
||||
_ = resolver.reject("module instantiation", local.newString("Module instantiation failed"));
|
||||
return promise;
|
||||
}
|
||||
}
|
||||
|
||||
const evaluated = mod.evaluate() catch {
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(status == .kErrored);
|
||||
std.debug.assert(mod.getStatus() == .kErrored);
|
||||
}
|
||||
_ = resolver.reject("module evaluation", local.newString("Module evaluation failed"));
|
||||
return promise;
|
||||
};
|
||||
lp.assert(evaluated.isPromise(), "Context._dynamicModuleCallback non-promise", .{});
|
||||
gop.value_ptr.module_promise = try evaluated.toPromise().persist();
|
||||
// mod.evaluate can invalidate or gop
|
||||
entry = self.module_cache.getPtr(specifier).?;
|
||||
entry.module_promise = try evaluated.toPromise().persist();
|
||||
}
|
||||
}
|
||||
|
||||
// like before, we want to set this up so that if anything else
|
||||
// tries to load this module, it can just return our promise
|
||||
// since we're going to be doing all the work.
|
||||
gop.value_ptr.resolver_promise = try promise.persist();
|
||||
entry.resolver_promise = try promise.persist();
|
||||
|
||||
// But we can skip direclty to `resolveDynamicModule` which is
|
||||
// what the above callback will eventually do.
|
||||
self.resolveDynamicModule(state, gop.value_ptr.*, local);
|
||||
self.resolveDynamicModule(state, entry.*, local);
|
||||
return promise;
|
||||
}
|
||||
|
||||
@@ -788,13 +875,12 @@ fn resolveDynamicModule(self: *Context, state: *DynamicModuleResolveState, modul
|
||||
|
||||
const then_callback = newFunctionWithData(local, struct {
|
||||
pub fn callback(callback_handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
const isolate = v8.v8__FunctionCallbackInfo__GetIsolate(callback_handle).?;
|
||||
var c: Caller = undefined;
|
||||
c.init(isolate);
|
||||
c.initFromHandle(callback_handle);
|
||||
defer c.deinit();
|
||||
|
||||
const info_data = v8.v8__FunctionCallbackInfo__Data(callback_handle).?;
|
||||
const s: *DynamicModuleResolveState = @ptrCast(@alignCast(v8.v8__External__Value(@ptrCast(info_data))));
|
||||
const info = Caller.FunctionCallbackInfo{ .handle = callback_handle.? };
|
||||
const s: *DynamicModuleResolveState = @ptrCast(@alignCast(info.getData() orelse return));
|
||||
|
||||
if (s.context_id != c.local.ctx.id) {
|
||||
// The microtask is tied to the isolate, not the context
|
||||
@@ -813,17 +899,15 @@ fn resolveDynamicModule(self: *Context, state: *DynamicModuleResolveState, modul
|
||||
|
||||
const catch_callback = newFunctionWithData(local, struct {
|
||||
pub fn callback(callback_handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
const isolate = v8.v8__FunctionCallbackInfo__GetIsolate(callback_handle).?;
|
||||
var c: Caller = undefined;
|
||||
c.init(isolate);
|
||||
c.initFromHandle(callback_handle);
|
||||
defer c.deinit();
|
||||
|
||||
const info_data = v8.v8__FunctionCallbackInfo__Data(callback_handle).?;
|
||||
const s: *DynamicModuleResolveState = @ptrCast(@alignCast(v8.v8__External__Value(@ptrCast(info_data))));
|
||||
const info = Caller.FunctionCallbackInfo{ .handle = callback_handle.? };
|
||||
const s: *DynamicModuleResolveState = @ptrCast(@alignCast(info.getData() orelse return));
|
||||
|
||||
const l = &c.local;
|
||||
const ctx = l.ctx;
|
||||
if (s.context_id != ctx.id) {
|
||||
if (s.context_id != l.ctx.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -844,45 +928,110 @@ fn resolveDynamicModule(self: *Context, state: *DynamicModuleResolveState, modul
|
||||
};
|
||||
}
|
||||
|
||||
// Microtasks
|
||||
// Used to make temporarily enter and exit a context, updating and restoring
|
||||
// page.js:
|
||||
// var hs: js.HandleScope = undefined;
|
||||
// const entered = ctx.enter(&hs);
|
||||
// defer entered.exit();
|
||||
pub fn enter(self: *Context, hs: *js.HandleScope) Entered {
|
||||
const isolate = self.isolate;
|
||||
js.HandleScope.init(hs, isolate);
|
||||
|
||||
const page = self.page;
|
||||
const original = page.js;
|
||||
page.js = self;
|
||||
|
||||
const handle: *const v8.Context = @ptrCast(v8.v8__Global__Get(&self.handle, isolate.handle));
|
||||
v8.v8__Context__Enter(handle);
|
||||
return .{ .original = original, .handle = handle, .handle_scope = hs };
|
||||
}
|
||||
|
||||
const Entered = struct {
|
||||
// the context we should restore on the page
|
||||
original: *Context,
|
||||
|
||||
// the handle of the entered context
|
||||
handle: *const v8.Context,
|
||||
|
||||
handle_scope: *js.HandleScope,
|
||||
|
||||
pub fn exit(self: Entered) void {
|
||||
self.original.page.js = self.original;
|
||||
v8.v8__Context__Exit(self.handle);
|
||||
self.handle_scope.deinit();
|
||||
}
|
||||
};
|
||||
|
||||
pub fn queueMutationDelivery(self: *Context) !void {
|
||||
self.isolate.enqueueMicrotask(struct {
|
||||
fn run(data: ?*anyopaque) callconv(.c) void {
|
||||
const page: *Page = @ptrCast(@alignCast(data.?));
|
||||
page.deliverMutations();
|
||||
self.enqueueMicrotask(struct {
|
||||
fn run(ctx: *Context) void {
|
||||
ctx.page.deliverMutations();
|
||||
}
|
||||
}.run, self.page);
|
||||
}.run);
|
||||
}
|
||||
|
||||
pub fn queueIntersectionChecks(self: *Context) !void {
|
||||
self.isolate.enqueueMicrotask(struct {
|
||||
fn run(data: ?*anyopaque) callconv(.c) void {
|
||||
const page: *Page = @ptrCast(@alignCast(data.?));
|
||||
page.performScheduledIntersectionChecks();
|
||||
self.enqueueMicrotask(struct {
|
||||
fn run(ctx: *Context) void {
|
||||
ctx.page.performScheduledIntersectionChecks();
|
||||
}
|
||||
}.run, self.page);
|
||||
}.run);
|
||||
}
|
||||
|
||||
pub fn queueIntersectionDelivery(self: *Context) !void {
|
||||
self.isolate.enqueueMicrotask(struct {
|
||||
fn run(data: ?*anyopaque) callconv(.c) void {
|
||||
const page: *Page = @ptrCast(@alignCast(data.?));
|
||||
page.deliverIntersections();
|
||||
self.enqueueMicrotask(struct {
|
||||
fn run(ctx: *Context) void {
|
||||
ctx.page.deliverIntersections();
|
||||
}
|
||||
}.run, self.page);
|
||||
}.run);
|
||||
}
|
||||
|
||||
pub fn queueSlotchangeDelivery(self: *Context) !void {
|
||||
self.isolate.enqueueMicrotask(struct {
|
||||
fn run(data: ?*anyopaque) callconv(.c) void {
|
||||
const page: *Page = @ptrCast(@alignCast(data.?));
|
||||
page.deliverSlotchangeEvents();
|
||||
self.enqueueMicrotask(struct {
|
||||
fn run(ctx: *Context) void {
|
||||
ctx.page.deliverSlotchangeEvents();
|
||||
}
|
||||
}.run, self.page);
|
||||
}.run);
|
||||
}
|
||||
|
||||
// Helper for executing a Microtask on this Context. In V8, microtasks aren't
|
||||
// associated to a Context - they are just functions to execute in an Isolate.
|
||||
// But for these Context microtasks, we want to (a) make sure the context isn't
|
||||
// being shut down and (b) that it's entered.
|
||||
fn enqueueMicrotask(self: *Context, callback: anytype) void {
|
||||
// Use context-specific microtask queue instead of isolate queue
|
||||
v8.v8__MicrotaskQueue__EnqueueMicrotask(self.microtask_queue, self.isolate.handle, struct {
|
||||
fn run(data: ?*anyopaque) callconv(.c) void {
|
||||
const ctx: *Context = @ptrCast(@alignCast(data.?));
|
||||
var hs: js.HandleScope = undefined;
|
||||
const entered = ctx.enter(&hs);
|
||||
defer entered.exit();
|
||||
callback(ctx);
|
||||
}
|
||||
}.run, self);
|
||||
}
|
||||
|
||||
// There's an assumption here: the js.Function will be alive when microtasks are
|
||||
// run. If we're Env.runMicrotasks in all the places that we're supposed to, then
|
||||
// this should be safe (I think). In whatever HandleScope a microtask is enqueued,
|
||||
// PerformCheckpoint should be run. So the v8::Local<v8::Function> should remain
|
||||
// valid. If we have problems with this, a simple solution is to provide a Zig
|
||||
// wrapper for these callbacks which references a js.Function.Temp, on callback
|
||||
// it executes the function and then releases the global.
|
||||
pub fn queueMicrotaskFunc(self: *Context, cb: js.Function) void {
|
||||
self.isolate.enqueueMicrotaskFunc(cb);
|
||||
// Use context-specific microtask queue instead of isolate queue
|
||||
v8.v8__MicrotaskQueue__EnqueueMicrotaskFunc(self.microtask_queue, self.isolate.handle, cb.handle);
|
||||
}
|
||||
|
||||
pub fn createFinalizerCallback(self: *Context, global: v8.Global, ptr: *anyopaque, finalizerFn: *const fn (ptr: *anyopaque, page: *Page) void) !*FinalizerCallback {
|
||||
const fc = try self.finalizer_callback_pool.create();
|
||||
fc.* = .{
|
||||
.ctx = self,
|
||||
.ptr = ptr,
|
||||
.global = global,
|
||||
.finalizerFn = finalizerFn,
|
||||
};
|
||||
return fc;
|
||||
}
|
||||
|
||||
// == Misc ==
|
||||
@@ -890,24 +1039,15 @@ pub fn queueMicrotaskFunc(self: *Context, cb: js.Function) void {
|
||||
// The first is from V8 via the WeakCallback we give to weakRef. But that isn't
|
||||
// guaranteed to fire, so we track this in ctx._finalizers and call them on
|
||||
// context shutdown.
|
||||
const FinalizerCallback = struct {
|
||||
pub const FinalizerCallback = struct {
|
||||
ctx: *Context,
|
||||
ptr: *anyopaque,
|
||||
finalizerFn: *const fn (ptr: *anyopaque) void,
|
||||
global: v8.Global,
|
||||
finalizerFn: *const fn (ptr: *anyopaque, page: *Page) void,
|
||||
|
||||
pub fn init(ptr: anytype) FinalizerCallback {
|
||||
const T = bridge.Struct(@TypeOf(ptr));
|
||||
return .{
|
||||
.ptr = ptr,
|
||||
.finalizerFn = struct {
|
||||
pub fn wrap(self: *anyopaque) void {
|
||||
T.JsApi.Meta.finalizer.from_zig(self);
|
||||
}
|
||||
}.wrap,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: FinalizerCallback) void {
|
||||
self.finalizerFn(self.ptr);
|
||||
pub fn deinit(self: *FinalizerCallback) void {
|
||||
self.finalizerFn(self.ptr, self.ctx.page);
|
||||
self.ctx.finalizer_callback_pool.destroy(self);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -940,7 +1080,7 @@ pub fn stopCpuProfiler(self: *Context) ![]const u8 {
|
||||
const title = self.isolate.initStringHandle("v8_cpu_profile");
|
||||
const handle = v8.v8__CpuProfiler__StopProfiling(self.cpu_profiler.?, title) orelse return error.NoProfiles;
|
||||
const string_handle = v8.v8__CpuProfile__Serialize(handle, self.isolate.handle) orelse return error.NoProfile;
|
||||
return ls.local.jsStringToZig(string_handle, .{});
|
||||
return (js.String{ .local = &ls.local, .handle = string_handle }).toSlice();
|
||||
}
|
||||
|
||||
pub fn startHeapProfiler(self: *Context) void {
|
||||
@@ -972,7 +1112,7 @@ pub fn stopHeapProfiler(self: *Context) !struct { []const u8, []const u8 } {
|
||||
const string_handle = v8.v8__AllocationProfile__Serialize(profile, self.isolate.handle);
|
||||
v8.v8__HeapProfiler__StopSamplingHeapProfiler(self.heap_profiler.?);
|
||||
v8.v8__AllocationProfile__Delete(profile);
|
||||
break :blk try ls.local.jsStringToZig(string_handle, .{});
|
||||
break :blk try (js.String{ .local = &ls.local, .handle = string_handle.? }).toSlice();
|
||||
};
|
||||
|
||||
const snapshot = blk: {
|
||||
@@ -980,8 +1120,13 @@ pub fn stopHeapProfiler(self: *Context) !struct { []const u8, []const u8 } {
|
||||
const string_handle = v8.v8__HeapSnapshot__Serialize(snapshot, self.isolate.handle);
|
||||
v8.v8__HeapProfiler__StopTrackingHeapObjects(self.heap_profiler.?);
|
||||
v8.v8__HeapSnapshot__Delete(snapshot);
|
||||
break :blk try ls.local.jsStringToZig(string_handle, .{});
|
||||
break :blk try (js.String{ .local = &ls.local, .handle = string_handle.? }).toSlice();
|
||||
};
|
||||
|
||||
return .{ allocating, snapshot };
|
||||
}
|
||||
|
||||
const UnknownPropertyStat = struct {
|
||||
count: usize,
|
||||
first_stack: []const u8,
|
||||
};
|
||||
|
||||
@@ -18,8 +18,11 @@
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const v8 = js.v8;
|
||||
|
||||
const App = @import("../../App.zig");
|
||||
const log = @import("../../log.zig");
|
||||
|
||||
const bridge = @import("bridge.zig");
|
||||
@@ -28,13 +31,21 @@ const Isolate = @import("Isolate.zig");
|
||||
const Platform = @import("Platform.zig");
|
||||
const Snapshot = @import("Snapshot.zig");
|
||||
const Inspector = @import("Inspector.zig");
|
||||
const ExecutionWorld = @import("ExecutionWorld.zig");
|
||||
|
||||
const Page = @import("../Page.zig");
|
||||
const Window = @import("../webapi/Window.zig");
|
||||
|
||||
const JsApis = bridge.JsApis;
|
||||
const Allocator = std.mem.Allocator;
|
||||
const ArenaAllocator = std.heap.ArenaAllocator;
|
||||
const IS_DEBUG = builtin.mode == .Debug;
|
||||
|
||||
fn initClassIds() void {
|
||||
inline for (JsApis, 0..) |JsApi, i| {
|
||||
JsApi.Meta.class_id = i;
|
||||
}
|
||||
}
|
||||
|
||||
var class_id_once = std.once(initClassIds);
|
||||
|
||||
// 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,
|
||||
@@ -44,13 +55,16 @@ const ArenaAllocator = std.heap.ArenaAllocator;
|
||||
// The `types` parameter is a tuple of Zig structures we want to bind to V8.
|
||||
const Env = @This();
|
||||
|
||||
allocator: Allocator,
|
||||
app: *App,
|
||||
|
||||
platform: *const Platform,
|
||||
|
||||
// the global isolate
|
||||
isolate: js.Isolate,
|
||||
|
||||
contexts: [64]*Context,
|
||||
context_count: usize,
|
||||
|
||||
// just kept around because we need to free it on deinit
|
||||
isolate_params: *v8.CreateParams,
|
||||
|
||||
@@ -65,7 +79,34 @@ templates: []*const v8.FunctionTemplate,
|
||||
// Global template created once per isolate and reused across all contexts
|
||||
global_template: v8.Eternal,
|
||||
|
||||
pub fn init(allocator: Allocator, platform: *const Platform, snapshot: *Snapshot) !Env {
|
||||
// Inspector associated with the Isolate. Exists when CDP is being used.
|
||||
inspector: ?*Inspector,
|
||||
|
||||
// We can store data in a v8::Object's Private data bag. The keys are v8::Private
|
||||
// which an be created once per isolaet.
|
||||
private_symbols: PrivateSymbols,
|
||||
|
||||
microtask_queues_are_running: bool,
|
||||
|
||||
pub const InitOpts = struct {
|
||||
with_inspector: bool = false,
|
||||
};
|
||||
|
||||
pub fn init(app: *App, opts: InitOpts) !Env {
|
||||
if (comptime IS_DEBUG) {
|
||||
comptime {
|
||||
// V8 requirement for any data using SetAlignedPointerInInternalField
|
||||
const a = @alignOf(@import("TaggedOpaque.zig"));
|
||||
std.debug.assert(a >= 2 and a % 2 == 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize class IDs once before any V8 work
|
||||
class_id_once.call();
|
||||
|
||||
const allocator = app.allocator;
|
||||
const snapshot = &app.snapshot;
|
||||
|
||||
var params = try allocator.create(v8.CreateParams);
|
||||
errdefer allocator.destroy(params);
|
||||
v8.v8__Isolate__CreateParams__CONSTRUCT(params);
|
||||
@@ -78,17 +119,18 @@ pub fn init(allocator: Allocator, platform: *const Platform, snapshot: *Snapshot
|
||||
|
||||
var isolate = js.Isolate.init(params);
|
||||
errdefer isolate.deinit();
|
||||
const isolate_handle = isolate.handle;
|
||||
|
||||
v8.v8__Isolate__SetHostImportModuleDynamicallyCallback(isolate.handle, Context.dynamicModuleCallback);
|
||||
v8.v8__Isolate__SetPromiseRejectCallback(isolate.handle, promiseRejectCallback);
|
||||
v8.v8__Isolate__SetMicrotasksPolicy(isolate.handle, v8.kExplicit);
|
||||
v8.v8__Isolate__SetFatalErrorHandler(isolate.handle, fatalCallback);
|
||||
v8.v8__Isolate__SetOOMErrorHandler(isolate.handle, oomCallback);
|
||||
v8.v8__Isolate__SetHostImportModuleDynamicallyCallback(isolate_handle, Context.dynamicModuleCallback);
|
||||
v8.v8__Isolate__SetPromiseRejectCallback(isolate_handle, promiseRejectCallback);
|
||||
v8.v8__Isolate__SetMicrotasksPolicy(isolate_handle, v8.kExplicit);
|
||||
v8.v8__Isolate__SetFatalErrorHandler(isolate_handle, fatalCallback);
|
||||
v8.v8__Isolate__SetOOMErrorHandler(isolate_handle, oomCallback);
|
||||
|
||||
isolate.enter();
|
||||
errdefer isolate.exit();
|
||||
|
||||
v8.v8__Isolate__SetHostInitializeImportMetaObjectCallback(isolate.handle, Context.metaObjectCallback);
|
||||
v8.v8__Isolate__SetHostInitializeImportMetaObjectCallback(isolate_handle, Context.metaObjectCallback);
|
||||
|
||||
// Allocate arrays dynamically to avoid comptime dependency on JsApis.len
|
||||
const eternal_function_templates = try allocator.alloc(v8.Eternal, JsApis.len);
|
||||
@@ -98,26 +140,26 @@ pub fn init(allocator: Allocator, platform: *const Platform, snapshot: *Snapshot
|
||||
errdefer allocator.free(templates);
|
||||
|
||||
var global_eternal: v8.Eternal = undefined;
|
||||
var private_symbols: PrivateSymbols = undefined;
|
||||
{
|
||||
var temp_scope: js.HandleScope = undefined;
|
||||
temp_scope.init(isolate);
|
||||
defer temp_scope.deinit();
|
||||
|
||||
inline for (JsApis, 0..) |JsApi, i| {
|
||||
JsApi.Meta.class_id = i;
|
||||
const data = v8.v8__Isolate__GetDataFromSnapshotOnce(isolate.handle, snapshot.data_start + i);
|
||||
inline for (JsApis, 0..) |_, i| {
|
||||
const data = v8.v8__Isolate__GetDataFromSnapshotOnce(isolate_handle, snapshot.data_start + i);
|
||||
const function_handle: *const v8.FunctionTemplate = @ptrCast(data);
|
||||
// Make function template eternal
|
||||
v8.v8__Eternal__New(isolate.handle, @ptrCast(function_handle), &eternal_function_templates[i]);
|
||||
v8.v8__Eternal__New(isolate_handle, @ptrCast(function_handle), &eternal_function_templates[i]);
|
||||
|
||||
// Extract the local handle from the global for easy access
|
||||
const eternal_ptr = v8.v8__Eternal__Get(&eternal_function_templates[i], isolate.handle);
|
||||
const eternal_ptr = v8.v8__Eternal__Get(&eternal_function_templates[i], isolate_handle);
|
||||
templates[i] = @ptrCast(@alignCast(eternal_ptr.?));
|
||||
}
|
||||
|
||||
// Create global template once per isolate
|
||||
const js_global = v8.v8__FunctionTemplate__New__DEFAULT(isolate.handle);
|
||||
const window_name = v8.v8__String__NewFromUtf8(isolate.handle, "Window", v8.kNormal, 6);
|
||||
const js_global = v8.v8__FunctionTemplate__New__DEFAULT(isolate_handle);
|
||||
const window_name = v8.v8__String__NewFromUtf8(isolate_handle, "Window", v8.kNormal, 6);
|
||||
v8.v8__FunctionTemplate__SetClassName(js_global, window_name);
|
||||
|
||||
// Find Window in JsApis by name (avoids circular import)
|
||||
@@ -126,7 +168,7 @@ pub fn init(allocator: Allocator, platform: *const Platform, snapshot: *Snapshot
|
||||
|
||||
const global_template_local = v8.v8__FunctionTemplate__InstanceTemplate(js_global).?;
|
||||
v8.v8__ObjectTemplate__SetNamedHandler(global_template_local, &.{
|
||||
.getter = bridge.unknownPropertyCallback,
|
||||
.getter = bridge.unknownWindowPropertyCallback,
|
||||
.setter = null,
|
||||
.query = null,
|
||||
.deleter = null,
|
||||
@@ -136,59 +178,248 @@ pub fn init(allocator: Allocator, platform: *const Platform, snapshot: *Snapshot
|
||||
.data = null,
|
||||
.flags = v8.kOnlyInterceptStrings | v8.kNonMasking,
|
||||
});
|
||||
v8.v8__Eternal__New(isolate.handle, @ptrCast(global_template_local), &global_eternal);
|
||||
// I don't 100% understand this. We actually set this up in the snapshot,
|
||||
// but for the global instance, it doesn't work. SetIndexedHandler and
|
||||
// SetNamedHandler are set on the Instance template, and that's the key
|
||||
// difference. The context has its own global instance, so we need to set
|
||||
// these back up directly on it. There might be a better way to do this.
|
||||
v8.v8__ObjectTemplate__SetIndexedHandler(global_template_local, &.{
|
||||
.getter = Window.JsApi.index.getter,
|
||||
.setter = null,
|
||||
.query = null,
|
||||
.deleter = null,
|
||||
.enumerator = null,
|
||||
.definer = null,
|
||||
.descriptor = null,
|
||||
.data = null,
|
||||
.flags = 0,
|
||||
});
|
||||
v8.v8__Eternal__New(isolate_handle, @ptrCast(global_template_local), &global_eternal);
|
||||
private_symbols = PrivateSymbols.init(isolate_handle);
|
||||
}
|
||||
|
||||
var inspector: ?*js.Inspector = null;
|
||||
if (opts.with_inspector) {
|
||||
inspector = try Inspector.init(allocator, isolate_handle);
|
||||
}
|
||||
|
||||
return .{
|
||||
.app = app,
|
||||
.context_id = 0,
|
||||
.contexts = undefined,
|
||||
.context_count = 0,
|
||||
.isolate = isolate,
|
||||
.platform = platform,
|
||||
.allocator = allocator,
|
||||
.platform = &app.platform,
|
||||
.templates = templates,
|
||||
.isolate_params = params,
|
||||
.eternal_function_templates = eternal_function_templates,
|
||||
.inspector = inspector,
|
||||
.global_template = global_eternal,
|
||||
.private_symbols = private_symbols,
|
||||
.microtask_queues_are_running = false,
|
||||
.eternal_function_templates = eternal_function_templates,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Env) void {
|
||||
self.allocator.free(self.templates);
|
||||
self.allocator.free(self.eternal_function_templates);
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(self.context_count == 0);
|
||||
}
|
||||
for (self.contexts[0..self.context_count]) |ctx| {
|
||||
ctx.deinit();
|
||||
}
|
||||
|
||||
const allocator = self.app.allocator;
|
||||
if (self.inspector) |i| {
|
||||
i.deinit(allocator);
|
||||
}
|
||||
|
||||
allocator.free(self.templates);
|
||||
allocator.free(self.eternal_function_templates);
|
||||
self.private_symbols.deinit();
|
||||
|
||||
self.isolate.exit();
|
||||
self.isolate.deinit();
|
||||
v8.v8__ArrayBuffer__Allocator__DELETE(self.isolate_params.array_buffer_allocator.?);
|
||||
self.allocator.destroy(self.isolate_params);
|
||||
allocator.destroy(self.isolate_params);
|
||||
}
|
||||
|
||||
pub fn newInspector(self: *Env, arena: Allocator, ctx: anytype) !*Inspector {
|
||||
const inspector = try arena.create(Inspector);
|
||||
try Inspector.init(inspector, self.isolate.handle, ctx);
|
||||
return inspector;
|
||||
pub fn createContext(self: *Env, page: *Page) !*Context {
|
||||
const context_arena = try self.app.arena_pool.acquire();
|
||||
errdefer self.app.arena_pool.release(context_arena);
|
||||
|
||||
const isolate = self.isolate;
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
// Create a per-context microtask queue for isolation
|
||||
const microtask_queue = v8.v8__MicrotaskQueue__New(isolate.handle, v8.kExplicit).?;
|
||||
errdefer v8.v8__MicrotaskQueue__DELETE(microtask_queue);
|
||||
|
||||
// Get the global template that was created once per isolate
|
||||
const global_template: *const v8.ObjectTemplate = @ptrCast(@alignCast(v8.v8__Eternal__Get(&self.global_template, isolate.handle).?));
|
||||
v8.v8__ObjectTemplate__SetInternalFieldCount(global_template, comptime Snapshot.countInternalFields(Window.JsApi));
|
||||
|
||||
const v8_context = v8.v8__Context__New__Config(isolate.handle, &.{
|
||||
.global_template = global_template,
|
||||
.global_object = null,
|
||||
.microtask_queue = microtask_queue,
|
||||
}).?;
|
||||
|
||||
// Create the v8::Context and wrap it in a v8::Global
|
||||
var context_global: v8.Global = undefined;
|
||||
v8.v8__Global__New(isolate.handle, v8_context, &context_global);
|
||||
|
||||
// get the global object for the context, this maps to our Window
|
||||
const global_obj = v8.v8__Context__Global(v8_context).?;
|
||||
{
|
||||
// Store our TAO inside the internal field of the global object. This
|
||||
// maps the v8::Object -> Zig instance. Almost all objects have this, and
|
||||
// it gets setup automatically as objects are created, but the Window
|
||||
// object already exists in v8 (it's the global) so we manually create
|
||||
// the mapping here.
|
||||
const tao = try context_arena.create(@import("TaggedOpaque.zig"));
|
||||
tao.* = .{
|
||||
.value = @ptrCast(page.window),
|
||||
.prototype_chain = (&Window.JsApi.Meta.prototype_chain).ptr,
|
||||
.prototype_len = @intCast(Window.JsApi.Meta.prototype_chain.len),
|
||||
.subtype = .node, // this probably isn't right, but it's what we've been doing all along
|
||||
};
|
||||
v8.v8__Object__SetAlignedPointerInInternalField(global_obj, 0, tao);
|
||||
}
|
||||
// our window wrapped in a v8::Global
|
||||
var global_global: v8.Global = undefined;
|
||||
v8.v8__Global__New(isolate.handle, global_obj, &global_global);
|
||||
|
||||
const context_id = self.context_id;
|
||||
self.context_id = context_id + 1;
|
||||
|
||||
const context = try context_arena.create(Context);
|
||||
context.* = .{
|
||||
.env = self,
|
||||
.page = page,
|
||||
.id = context_id,
|
||||
.isolate = isolate,
|
||||
.arena = context_arena,
|
||||
.handle = context_global,
|
||||
.templates = self.templates,
|
||||
.call_arena = page.call_arena,
|
||||
.microtask_queue = microtask_queue,
|
||||
.script_manager = &page._script_manager,
|
||||
.scheduler = .init(context_arena),
|
||||
.finalizer_callback_pool = std.heap.MemoryPool(Context.FinalizerCallback).init(self.app.allocator),
|
||||
};
|
||||
try context.identity_map.putNoClobber(context_arena, @intFromPtr(page.window), global_global);
|
||||
|
||||
// Store a pointer to our context inside the v8 context so that, given
|
||||
// a v8 context, we can get our context out
|
||||
v8.v8__Context__SetAlignedPointerInEmbedderData(v8_context, 1, @ptrCast(context));
|
||||
|
||||
const count = self.context_count;
|
||||
if (count >= self.contexts.len) {
|
||||
return error.TooManyContexts;
|
||||
}
|
||||
self.contexts[count] = context;
|
||||
self.context_count = count + 1;
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
pub fn runMicrotasks(self: *const Env) void {
|
||||
self.isolate.performMicrotasksCheckpoint();
|
||||
pub fn destroyContext(self: *Env, context: *Context) void {
|
||||
for (self.contexts[0..self.context_count], 0..) |ctx, i| {
|
||||
if (ctx == context) {
|
||||
// Swap with last element and decrement count
|
||||
self.context_count -= 1;
|
||||
self.contexts[i] = self.contexts[self.context_count];
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (comptime IS_DEBUG) {
|
||||
@panic("Tried to remove unknown context");
|
||||
}
|
||||
}
|
||||
|
||||
const isolate = self.isolate;
|
||||
if (self.inspector) |inspector| {
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(isolate);
|
||||
defer hs.deinit();
|
||||
inspector.contextDestroyed(@ptrCast(v8.v8__Global__Get(&context.handle, isolate.handle)));
|
||||
}
|
||||
|
||||
context.deinit();
|
||||
}
|
||||
|
||||
pub fn pumpMessageLoop(self: *const Env) bool {
|
||||
pub fn runMicrotasks(self: *Env) void {
|
||||
if (self.microtask_queues_are_running == false) {
|
||||
const v8_isolate = self.isolate.handle;
|
||||
|
||||
self.microtask_queues_are_running = true;
|
||||
defer self.microtask_queues_are_running = false;
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < self.context_count) : (i += 1) {
|
||||
const ctx = self.contexts[i];
|
||||
v8.v8__MicrotaskQueue__PerformCheckpoint(ctx.microtask_queue, v8_isolate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn runMacrotasks(self: *Env) !?u64 {
|
||||
var ms_to_next_task: ?u64 = null;
|
||||
for (self.contexts[0..self.context_count]) |ctx| {
|
||||
if (comptime builtin.is_test == false) {
|
||||
// I hate this comptime check as much as you do. But we have tests
|
||||
// which rely on short execution before shutdown. In real world, it's
|
||||
// underterministic whether a timer will or won't run before the
|
||||
// page shutsdown. But for tests, we need to run them to their end.
|
||||
if (ctx.scheduler.hasReadyTasks() == false) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
const entered = ctx.enter(&hs);
|
||||
defer entered.exit();
|
||||
|
||||
const ms = (try ctx.scheduler.run()) orelse continue;
|
||||
if (ms_to_next_task == null or ms < ms_to_next_task.?) {
|
||||
ms_to_next_task = ms;
|
||||
}
|
||||
}
|
||||
return ms_to_next_task;
|
||||
}
|
||||
|
||||
pub fn pumpMessageLoop(self: *const Env) void {
|
||||
var hs: v8.HandleScope = undefined;
|
||||
v8.v8__HandleScope__CONSTRUCT(&hs, self.isolate.handle);
|
||||
defer v8.v8__HandleScope__DESTRUCT(&hs);
|
||||
|
||||
return v8.v8__Platform__PumpMessageLoop(self.platform.handle, self.isolate.handle, false);
|
||||
const isolate = self.isolate.handle;
|
||||
const platform = self.platform.handle;
|
||||
while (v8.v8__Platform__PumpMessageLoop(platform, isolate, false)) {}
|
||||
}
|
||||
|
||||
pub fn hasBackgroundTasks(self: *const Env) bool {
|
||||
return v8.v8__Isolate__HasPendingBackgroundTasks(self.isolate.handle);
|
||||
}
|
||||
|
||||
pub fn waitForBackgroundTasks(self: *Env) void {
|
||||
var hs: v8.HandleScope = undefined;
|
||||
v8.v8__HandleScope__CONSTRUCT(&hs, self.isolate.handle);
|
||||
defer v8.v8__HandleScope__DESTRUCT(&hs);
|
||||
|
||||
const isolate = self.isolate.handle;
|
||||
const platform = self.platform.handle;
|
||||
while (v8.v8__Isolate__HasPendingBackgroundTasks(isolate)) {
|
||||
_ = v8.v8__Platform__PumpMessageLoop(platform, isolate, true);
|
||||
self.runMicrotasks();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn runIdleTasks(self: *const Env) void {
|
||||
v8.v8__Platform__RunIdleTasks(self.platform.handle, self.isolate.handle, 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
|
||||
@@ -239,6 +470,10 @@ pub fn dumpMemoryStats(self: *Env) void {
|
||||
, .{ 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 });
|
||||
}
|
||||
|
||||
pub fn terminate(self: *const Env) void {
|
||||
v8.v8__Isolate__TerminateExecution(self.isolate.handle);
|
||||
}
|
||||
|
||||
fn promiseRejectCallback(message_handle: v8.PromiseRejectMessage) callconv(.c) void {
|
||||
const promise_handle = v8.v8__PromiseRejectMessage__GetPromise(&message_handle).?;
|
||||
const v8_isolate = v8.v8__Object__GetIsolate(@ptrCast(promise_handle)).?;
|
||||
@@ -252,18 +487,13 @@ fn promiseRejectCallback(message_handle: v8.PromiseRejectMessage) callconv(.c) v
|
||||
.call_arena = ctx.call_arena,
|
||||
};
|
||||
|
||||
const value =
|
||||
if (v8.v8__PromiseRejectMessage__GetValue(&message_handle)) |v8_value|
|
||||
// @HandleScope - no reason to create a js.Context here
|
||||
local.valueHandleToString(v8_value, .{}) catch |err| @errorName(err)
|
||||
else
|
||||
"no value";
|
||||
|
||||
log.debug(.js, "unhandled rejection", .{
|
||||
.value = value,
|
||||
.stack = local.stackTrace() catch |err| @errorName(err) orelse "???",
|
||||
.note = "This should be updated to call window.unhandledrejection",
|
||||
});
|
||||
const page = ctx.page;
|
||||
page.window.unhandledPromiseRejection(.{
|
||||
.local = &local,
|
||||
.handle = &message_handle,
|
||||
}, page) catch |err| {
|
||||
log.warn(.browser, "unhandled rejection handler", .{ .err = err });
|
||||
};
|
||||
}
|
||||
|
||||
fn fatalCallback(c_location: [*c]const u8, c_message: [*c]const u8) callconv(.c) void {
|
||||
@@ -279,3 +509,19 @@ fn oomCallback(c_location: [*c]const u8, details: ?*const v8.OOMDetails) callcon
|
||||
log.fatal(.app, "V8 OOM", .{ .location = location, .detail = detail });
|
||||
@import("../../crash_handler.zig").crash("V8 OOM", .{ .location = location, .detail = detail }, @returnAddress());
|
||||
}
|
||||
|
||||
const PrivateSymbols = struct {
|
||||
const Private = @import("Private.zig");
|
||||
|
||||
child_nodes: Private,
|
||||
|
||||
fn init(isolate: *v8.Isolate) PrivateSymbols {
|
||||
return .{
|
||||
.child_nodes = Private.init(isolate, "child_nodes"),
|
||||
};
|
||||
}
|
||||
|
||||
fn deinit(self: *PrivateSymbols) void {
|
||||
self.child_nodes.deinit();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
// 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 lp = @import("lightpanda");
|
||||
|
||||
const log = @import("../../log.zig");
|
||||
const Page = @import("../Page.zig");
|
||||
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const Env = @import("Env.zig");
|
||||
const bridge = @import("bridge.zig");
|
||||
const Context = @import("Context.zig");
|
||||
|
||||
const ArenaAllocator = std.heap.ArenaAllocator;
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
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 js.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 {
|
||||
lp.assert(self.context == null, "ExecptionWorld.createContext has context", .{});
|
||||
|
||||
const env = self.env;
|
||||
const isolate = env.isolate;
|
||||
const arena = self.context_arena.allocator();
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
// Get the global template that was created once per isolate
|
||||
const global_template: *const v8.ObjectTemplate = @ptrCast(@alignCast(v8.v8__Eternal__Get(&env.global_template, isolate.handle).?));
|
||||
const v8_context = v8.v8__Context__New(isolate.handle, global_template, null).?;
|
||||
|
||||
// Create the v8::Context and wrap it in a v8::Global
|
||||
var context_global: v8.Global = undefined;
|
||||
v8.v8__Global__New(isolate.handle, v8_context, &context_global);
|
||||
|
||||
// our window wrapped in a v8::Global
|
||||
const global_obj = v8.v8__Context__Global(v8_context).?;
|
||||
var global_global: v8.Global = undefined;
|
||||
v8.v8__Global__New(isolate.handle, global_obj, &global_global);
|
||||
|
||||
if (enter) {
|
||||
v8.v8__Context__Enter(v8_context);
|
||||
}
|
||||
errdefer if (enter) {
|
||||
v8.v8__Context__Exit(v8_context);
|
||||
};
|
||||
|
||||
const context_id = env.context_id;
|
||||
env.context_id = context_id + 1;
|
||||
|
||||
self.context = Context{
|
||||
.page = page,
|
||||
.id = context_id,
|
||||
.entered = enter,
|
||||
.isolate = isolate,
|
||||
.handle = context_global,
|
||||
.templates = env.templates,
|
||||
.script_manager = &page._script_manager,
|
||||
.call_arena = page.call_arena,
|
||||
.arena = arena,
|
||||
};
|
||||
|
||||
var context = &self.context.?;
|
||||
try context.identity_map.putNoClobber(arena, @intFromPtr(page.window), global_global);
|
||||
|
||||
// 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.initBigInt(@intFromPtr(&self.context.?));
|
||||
v8.v8__Context__SetEmbedderData(v8_context, 1, @ptrCast(data.handle));
|
||||
|
||||
return &self.context.?;
|
||||
}
|
||||
|
||||
pub fn removeContext(self: *ExecutionWorld) void {
|
||||
var context = &(self.context orelse return);
|
||||
context.deinit();
|
||||
self.context = null;
|
||||
|
||||
self.env.isolate.notifyContextDisposed();
|
||||
_ = self.context_arena.reset(.{ .retain_with_limit = CONTEXT_ARENA_RETAIN });
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
@@ -22,8 +22,6 @@ const v8 = js.v8;
|
||||
|
||||
const log = @import("../../log.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const Function = @This();
|
||||
|
||||
local: *const js.Local,
|
||||
@@ -71,7 +69,15 @@ pub fn newInstance(self: *const Function, caught: *js.TryCatch.Caught) !js.Objec
|
||||
|
||||
pub fn call(self: *const Function, comptime T: type, args: anytype) !T {
|
||||
var caught: js.TryCatch.Caught = undefined;
|
||||
return self._tryCallWithThis(T, self.getThis(), args, &caught) catch |err| {
|
||||
return self._tryCallWithThis(T, self.getThis(), args, &caught, .{}) catch |err| {
|
||||
log.warn(.js, "call caught", .{ .err = err, .caught = caught });
|
||||
return err;
|
||||
};
|
||||
}
|
||||
|
||||
pub fn callRethrow(self: *const Function, comptime T: type, args: anytype) !T {
|
||||
var caught: js.TryCatch.Caught = undefined;
|
||||
return self._tryCallWithThis(T, self.getThis(), args, &caught, .{ .rethrow = true }) catch |err| {
|
||||
log.warn(.js, "call caught", .{ .err = err, .caught = caught });
|
||||
return err;
|
||||
};
|
||||
@@ -79,21 +85,24 @@ pub fn call(self: *const Function, comptime T: type, args: anytype) !T {
|
||||
|
||||
pub fn callWithThis(self: *const Function, comptime T: type, this: anytype, args: anytype) !T {
|
||||
var caught: js.TryCatch.Caught = undefined;
|
||||
return self._tryCallWithThis(T, this, args, &caught) catch |err| {
|
||||
return self._tryCallWithThis(T, this, args, &caught, .{}) catch |err| {
|
||||
log.warn(.js, "callWithThis caught", .{ .err = err, .caught = caught });
|
||||
return err;
|
||||
};
|
||||
}
|
||||
|
||||
pub fn tryCall(self: *const Function, comptime T: type, args: anytype, caught: *js.TryCatch.Caught) !T {
|
||||
return self._tryCallWithThis(T, self.getThis(), args, caught);
|
||||
return self._tryCallWithThis(T, self.getThis(), args, caught, .{});
|
||||
}
|
||||
|
||||
pub fn tryCallWithThis(self: *const Function, comptime T: type, this: anytype, args: anytype, caught: *js.TryCatch.Caught) !T {
|
||||
return self._tryCallWithThis(T, this, args, caught);
|
||||
return self._tryCallWithThis(T, this, args, caught, .{});
|
||||
}
|
||||
|
||||
pub fn _tryCallWithThis(self: *const Function, comptime T: type, this: anytype, args: anytype, caught: *js.TryCatch.Caught) !T {
|
||||
const CallOpts = struct {
|
||||
rethrow: bool = false,
|
||||
};
|
||||
fn _tryCallWithThis(self: *const Function, comptime T: type, this: anytype, args: anytype, caught: *js.TryCatch.Caught, comptime opts: CallOpts) !T {
|
||||
caught.* = .{};
|
||||
const local = self.local;
|
||||
|
||||
@@ -147,6 +156,10 @@ pub fn _tryCallWithThis(self: *const Function, comptime T: type, this: anytype,
|
||||
defer try_catch.deinit();
|
||||
|
||||
const handle = v8.v8__Function__Call(self.handle, local.handle, js_this.handle, @as(c_int, @intCast(js_args.len)), c_args) orelse {
|
||||
if ((comptime opts.rethrow) and try_catch.hasCaught()) {
|
||||
try_catch.rethrow();
|
||||
return error.TryCatchRethrow;
|
||||
}
|
||||
caught.* = try_catch.caughtOrError(local.call_arena, error.JSExecCallback);
|
||||
return error.JSExecCallback;
|
||||
};
|
||||
|
||||
@@ -28,7 +28,11 @@ handle: v8.HandleScope,
|
||||
// value, as v8 will then have taken the address of the function-scopped (and no
|
||||
// longer valid) local.
|
||||
pub fn init(self: *HandleScope, isolate: js.Isolate) void {
|
||||
v8.v8__HandleScope__CONSTRUCT(&self.handle, isolate.handle);
|
||||
self.initWithIsolateHandle(isolate.handle);
|
||||
}
|
||||
|
||||
pub fn initWithIsolateHandle(self: *HandleScope, isolate: *v8.Isolate) void {
|
||||
v8.v8__HandleScope__CONSTRUCT(&self.handle, isolate);
|
||||
}
|
||||
|
||||
pub fn deinit(self: *HandleScope) void {
|
||||
|
||||
@@ -23,99 +23,76 @@ const v8 = js.v8;
|
||||
const TaggedOpaque = @import("TaggedOpaque.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const RndGen = std.Random.DefaultPrng;
|
||||
|
||||
const CONTEXT_GROUP_ID = 1;
|
||||
const CLIENT_TRUST_LEVEL = 1;
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
// Inspector exists for the lifetime of the Isolate/Env. 1 Isolate = 1 Inspector.
|
||||
// It combines the v8.Inspector and the v8.InspectorClientImpl. The v8.InspectorClientImpl
|
||||
// is our own implementation that fulfills the InspectorClient API, i.e. it's the
|
||||
// mechanism v8 provides to let us tweak how the inspector works. For example, it
|
||||
// Below, you'll find a few pub export fn v8_inspector__Client__IMPL__XYZ functions
|
||||
// which is our implementation of what the v8::Inspector requires of our Client
|
||||
// (not much at all)
|
||||
const Inspector = @This();
|
||||
|
||||
handle: *v8.Inspector,
|
||||
unique_id: i64,
|
||||
isolate: *v8.Isolate,
|
||||
client: Client,
|
||||
channel: Channel,
|
||||
session: Session,
|
||||
rnd: RndGen = RndGen.init(0),
|
||||
handle: *v8.Inspector,
|
||||
client: *v8.InspectorClientImpl,
|
||||
default_context: ?v8.Global,
|
||||
session: ?Session,
|
||||
|
||||
// We expect allocator to be an arena
|
||||
// Note: This initializes the pre-allocated inspector in-place
|
||||
pub fn init(self: *Inspector, isolate: *v8.Isolate, ctx: anytype) !void {
|
||||
const ContextT = @TypeOf(ctx);
|
||||
pub fn init(allocator: Allocator, isolate: *v8.Isolate) !*Inspector {
|
||||
const self = try allocator.create(Inspector);
|
||||
errdefer allocator.destroy(self);
|
||||
|
||||
const Container = 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;
|
||||
|
||||
// Initialize the fields that callbacks need first
|
||||
self.* = .{
|
||||
.handle = undefined,
|
||||
.unique_id = 1,
|
||||
.session = null,
|
||||
.isolate = isolate,
|
||||
.client = undefined,
|
||||
.channel = undefined,
|
||||
.rnd = RndGen.init(0),
|
||||
.handle = undefined,
|
||||
.default_context = null,
|
||||
.session = undefined,
|
||||
};
|
||||
|
||||
// Create client and set inspector data BEFORE creating the inspector
|
||||
// because V8 will call generateUniqueId during inspector creation
|
||||
const client = Client.init();
|
||||
self.client = client;
|
||||
client.setInspector(self);
|
||||
self.client = v8.v8_inspector__Client__IMPL__CREATE();
|
||||
errdefer v8.v8_inspector__Client__IMPL__DELETE(self.client);
|
||||
v8.v8_inspector__Client__IMPL__SET_DATA(self.client, self);
|
||||
|
||||
// Now create the inspector - generateUniqueId will work because data is set
|
||||
const handle = v8.v8_inspector__Inspector__Create(isolate, client.handle).?;
|
||||
self.handle = handle;
|
||||
self.handle = v8.v8_inspector__Inspector__Create(isolate, self.client).?;
|
||||
errdefer v8.v8_inspector__Inspector__DELETE(self.handle);
|
||||
|
||||
// Create the channel
|
||||
const channel = Channel.init(
|
||||
safe_context,
|
||||
Container.onInspectorResponse,
|
||||
Container.onInspectorEvent,
|
||||
Container.onRunMessageLoopOnPause,
|
||||
Container.onQuitMessageLoopOnPause,
|
||||
isolate,
|
||||
);
|
||||
self.channel = channel;
|
||||
channel.setInspector(self);
|
||||
|
||||
// Create the session
|
||||
const session_handle = v8.v8_inspector__Inspector__Connect(
|
||||
handle,
|
||||
CONTEXT_GROUP_ID,
|
||||
channel.handle,
|
||||
CLIENT_TRUST_LEVEL,
|
||||
).?;
|
||||
self.session = .{ .handle = session_handle };
|
||||
return self;
|
||||
}
|
||||
|
||||
pub fn deinit(self: *const Inspector) void {
|
||||
pub fn deinit(self: *const Inspector, allocator: Allocator) void {
|
||||
var hs: v8.HandleScope = undefined;
|
||||
v8.v8__HandleScope__CONSTRUCT(&hs, self.isolate);
|
||||
defer v8.v8__HandleScope__DESTRUCT(&hs);
|
||||
|
||||
self.session.deinit();
|
||||
self.client.deinit();
|
||||
self.channel.deinit();
|
||||
if (self.session) |*s| {
|
||||
s.deinit();
|
||||
}
|
||||
v8.v8_inspector__Client__IMPL__DELETE(self.client);
|
||||
v8.v8_inspector__Inspector__DELETE(self.handle);
|
||||
allocator.destroy(self);
|
||||
}
|
||||
|
||||
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.v8__HandleScope__CONSTRUCT(&temp_scope, isolate);
|
||||
defer v8.v8__HandleScope__DESTRUCT(&temp_scope);
|
||||
pub fn startSession(self: *Inspector, ctx: anytype) *Session {
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(self.session == null);
|
||||
}
|
||||
|
||||
self.session.dispatchProtocolMessage(isolate, msg);
|
||||
self.session = @as(Session, undefined);
|
||||
Session.init(&self.session.?, self, ctx);
|
||||
return &self.session.?;
|
||||
}
|
||||
|
||||
pub fn stopSession(self: *Inspector) void {
|
||||
self.session.?.deinit();
|
||||
self.session = null;
|
||||
}
|
||||
|
||||
// From CDP docs
|
||||
@@ -151,8 +128,8 @@ pub fn contextCreated(
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contextDestroyed(self: *Inspector, local: *const js.Local) void {
|
||||
v8.v8_inspector__Inspector__ContextDestroyed(self.handle, local.handle);
|
||||
pub fn contextDestroyed(self: *Inspector, context: *const v8.Context) void {
|
||||
v8.v8_inspector__Inspector__ContextDestroyed(self.handle, context);
|
||||
}
|
||||
|
||||
pub fn resetContextGroup(self: *const Inspector) void {
|
||||
@@ -163,51 +140,6 @@ pub fn resetContextGroup(self: *const Inspector) void {
|
||||
v8.v8_inspector__Inspector__ResetContextGroup(self.handle, CONTEXT_GROUP_ID);
|
||||
}
|
||||
|
||||
// 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.Global(js.Object) and if not
|
||||
// we'll create it and track it for cleanup when the context ends.
|
||||
pub fn getRemoteObject(
|
||||
self: *const Inspector,
|
||||
local: *const js.Local,
|
||||
group: []const u8,
|
||||
value: anytype,
|
||||
) !RemoteObject {
|
||||
const js_val = try local.zigValueToJs(value, .{});
|
||||
|
||||
// We do not want to expose this as a parameter for now
|
||||
const generate_preview = false;
|
||||
return self.session.wrapObject(
|
||||
local.isolate.handle,
|
||||
local.handle,
|
||||
js_val.handle,
|
||||
group,
|
||||
generate_preview,
|
||||
);
|
||||
}
|
||||
|
||||
// Gets a value by object ID regardless of which context it is in.
|
||||
// Our TaggedOpaque 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 TaggedOpaque.fromJS does.
|
||||
pub fn getNodePtr(self: *const Inspector, allocator: Allocator, object_id: []const u8, local: *js.Local) !*anyopaque {
|
||||
// just to indicate that the caller is responsible for ensure there's a local environment
|
||||
_ = local;
|
||||
const unwrapped = try self.session.unwrapObject(allocator, object_id);
|
||||
// The values context and groupId are not used here
|
||||
const js_val = unwrapped.value;
|
||||
if (!v8.v8__Value__IsObject(js_val)) {
|
||||
return error.ObjectIdIsNotANode;
|
||||
}
|
||||
|
||||
const Node = @import("../webapi/Node.zig");
|
||||
// Cast to *const v8.Object for typeTaggedAnyOpaque
|
||||
return TaggedOpaque.fromJS(*Node, @ptrCast(js_val)) catch return error.ObjectIdIsNotANode;
|
||||
}
|
||||
|
||||
pub const RemoteObject = struct {
|
||||
handle: *v8.RemoteObject,
|
||||
|
||||
@@ -254,14 +186,55 @@ pub const RemoteObject = struct {
|
||||
}
|
||||
};
|
||||
|
||||
const Session = struct {
|
||||
// Combines a v8::InspectorSession and a v8::InspectorChannelImpl. The
|
||||
// InspectorSession is for zig -> v8 (sending messages to the inspector). The
|
||||
// Channel is for v8 -> zig, getting events from the Inspector (that we'll pass
|
||||
// back ot some opaque context, i.e the CDP BrowserContext).
|
||||
// The channel callbacks are defined below, as:
|
||||
// pub export fn v8_inspector__Channel__IMPL__XYZ
|
||||
pub const Session = struct {
|
||||
inspector: *Inspector,
|
||||
handle: *v8.InspectorSession,
|
||||
channel: *v8.InspectorChannelImpl,
|
||||
|
||||
fn deinit(self: Session) void {
|
||||
v8.v8_inspector__Session__DELETE(self.handle);
|
||||
// callbacks
|
||||
ctx: *anyopaque,
|
||||
onNotif: *const fn (ctx: *anyopaque, msg: []const u8) void,
|
||||
onResp: *const fn (ctx: *anyopaque, call_id: u32, msg: []const u8) void,
|
||||
|
||||
fn init(self: *Session, inspector: *Inspector, ctx: anytype) void {
|
||||
const Container = @typeInfo(@TypeOf(ctx)).pointer.child;
|
||||
|
||||
const channel = v8.v8_inspector__Channel__IMPL__CREATE(inspector.isolate);
|
||||
const handle = v8.v8_inspector__Inspector__Connect(
|
||||
inspector.handle,
|
||||
CONTEXT_GROUP_ID,
|
||||
channel,
|
||||
CLIENT_TRUST_LEVEL,
|
||||
).?;
|
||||
v8.v8_inspector__Channel__IMPL__SET_DATA(channel, self);
|
||||
|
||||
self.* = .{
|
||||
.ctx = ctx,
|
||||
.handle = handle,
|
||||
.channel = channel,
|
||||
.inspector = inspector,
|
||||
.onResp = Container.onInspectorResponse,
|
||||
.onNotif = Container.onInspectorEvent,
|
||||
};
|
||||
}
|
||||
|
||||
fn dispatchProtocolMessage(self: Session, isolate: *v8.Isolate, msg: []const u8) void {
|
||||
fn deinit(self: *const Session) void {
|
||||
v8.v8_inspector__Session__DELETE(self.handle);
|
||||
v8.v8_inspector__Channel__IMPL__DELETE(self.channel);
|
||||
}
|
||||
|
||||
pub fn send(self: *const Session, msg: []const u8) void {
|
||||
const isolate = self.inspector.isolate;
|
||||
var hs: v8.HandleScope = undefined;
|
||||
v8.v8__HandleScope__CONSTRUCT(&hs, isolate);
|
||||
defer v8.v8__HandleScope__DESTRUCT(&hs);
|
||||
|
||||
v8.v8_inspector__Session__dispatchProtocolMessage(
|
||||
self.handle,
|
||||
isolate,
|
||||
@@ -270,6 +243,52 @@ const Session = struct {
|
||||
);
|
||||
}
|
||||
|
||||
// Gets a value by object ID regardless of which context it is in.
|
||||
// Our TaggedOpaque 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 TaggedOpaque.fromJS does.
|
||||
pub fn getNodePtr(self: *const Session, allocator: Allocator, object_id: []const u8, local: *js.Local) !*anyopaque {
|
||||
// just to indicate that the caller is responsible for ensuring there's a local environment
|
||||
_ = local;
|
||||
|
||||
const unwrapped = try self.unwrapObject(allocator, object_id);
|
||||
// The values context and groupId are not used here
|
||||
const js_val = unwrapped.value;
|
||||
if (!v8.v8__Value__IsObject(js_val)) {
|
||||
return error.ObjectIdIsNotANode;
|
||||
}
|
||||
|
||||
const Node = @import("../webapi/Node.zig");
|
||||
// Cast to *const v8.Object for typeTaggedAnyOpaque
|
||||
return TaggedOpaque.fromJS(*Node, @ptrCast(js_val)) catch return error.ObjectIdIsNotANode;
|
||||
}
|
||||
|
||||
// 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.Global(js.Object) and if not
|
||||
// we'll create it and track it for cleanup when the context ends.
|
||||
pub fn getRemoteObject(
|
||||
self: *const Session,
|
||||
local: *const js.Local,
|
||||
group: []const u8,
|
||||
value: anytype,
|
||||
) !RemoteObject {
|
||||
const js_val = try local.zigValueToJs(value, .{});
|
||||
|
||||
// We do not want to expose this as a parameter for now
|
||||
const generate_preview = false;
|
||||
return self.wrapObject(
|
||||
local.isolate.handle,
|
||||
local.handle,
|
||||
js_val.handle,
|
||||
group,
|
||||
generate_preview,
|
||||
);
|
||||
}
|
||||
|
||||
fn wrapObject(
|
||||
self: Session,
|
||||
isolate: *v8.Isolate,
|
||||
@@ -334,84 +353,6 @@ const UnwrappedObject = struct {
|
||||
object_group: ?[]const u8,
|
||||
};
|
||||
|
||||
const Channel = struct {
|
||||
handle: *v8.InspectorChannelImpl,
|
||||
|
||||
// callbacks
|
||||
ctx: *anyopaque,
|
||||
onNotif: onNotifFn = undefined,
|
||||
onResp: onRespFn = undefined,
|
||||
onRunMessageLoopOnPause: onRunMessageLoopOnPauseFn = undefined,
|
||||
onQuitMessageLoopOnPause: onQuitMessageLoopOnPauseFn = undefined,
|
||||
|
||||
pub const onNotifFn = *const fn (ctx: *anyopaque, msg: []const u8) void;
|
||||
pub const onRespFn = *const fn (ctx: *anyopaque, call_id: u32, msg: []const u8) void;
|
||||
pub const onRunMessageLoopOnPauseFn = *const fn (ctx: *anyopaque, context_group_id: u32) void;
|
||||
pub const onQuitMessageLoopOnPauseFn = *const fn (ctx: *anyopaque) void;
|
||||
|
||||
fn init(
|
||||
ctx: *anyopaque,
|
||||
onResp: onRespFn,
|
||||
onNotif: onNotifFn,
|
||||
onRunMessageLoopOnPause: onRunMessageLoopOnPauseFn,
|
||||
onQuitMessageLoopOnPause: onQuitMessageLoopOnPauseFn,
|
||||
isolate: *v8.Isolate,
|
||||
) Channel {
|
||||
const handle = v8.v8_inspector__Channel__IMPL__CREATE(isolate);
|
||||
return .{
|
||||
.handle = handle,
|
||||
.ctx = ctx,
|
||||
.onResp = onResp,
|
||||
.onNotif = onNotif,
|
||||
.onRunMessageLoopOnPause = onRunMessageLoopOnPause,
|
||||
.onQuitMessageLoopOnPause = onQuitMessageLoopOnPause,
|
||||
};
|
||||
}
|
||||
|
||||
fn deinit(self: Channel) void {
|
||||
v8.v8_inspector__Channel__IMPL__DELETE(self.handle);
|
||||
}
|
||||
|
||||
fn setInspector(self: Channel, inspector: *anyopaque) void {
|
||||
v8.v8_inspector__Channel__IMPL__SET_DATA(self.handle, inspector);
|
||||
}
|
||||
|
||||
fn resp(self: Channel, call_id: u32, msg: []const u8) void {
|
||||
self.onResp(self.ctx, call_id, msg);
|
||||
}
|
||||
|
||||
fn notif(self: Channel, msg: []const u8) void {
|
||||
self.onNotif(self.ctx, msg);
|
||||
}
|
||||
};
|
||||
|
||||
const Client = struct {
|
||||
handle: *v8.InspectorClientImpl,
|
||||
|
||||
fn init() Client {
|
||||
return .{ .handle = v8.v8_inspector__Client__IMPL__CREATE() };
|
||||
}
|
||||
|
||||
fn deinit(self: Client) void {
|
||||
v8.v8_inspector__Client__IMPL__DELETE(self.handle);
|
||||
}
|
||||
|
||||
fn setInspector(self: Client, inspector: *anyopaque) void {
|
||||
v8.v8_inspector__Client__IMPL__SET_DATA(self.handle, inspector);
|
||||
}
|
||||
};
|
||||
|
||||
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 {}
|
||||
};
|
||||
|
||||
fn fromData(data: *anyopaque) *Inspector {
|
||||
return @ptrCast(@alignCast(data));
|
||||
}
|
||||
|
||||
pub fn getTaggedOpaque(value: *const v8.Value) ?*TaggedOpaque {
|
||||
if (!v8.v8__Value__IsObject(value)) {
|
||||
return null;
|
||||
@@ -421,9 +362,8 @@ pub fn getTaggedOpaque(value: *const v8.Value) ?*TaggedOpaque {
|
||||
return null;
|
||||
}
|
||||
|
||||
const external_value = v8.v8__Object__GetInternalField(value, 0).?;
|
||||
const external_data = v8.v8__External__Value(external_value).?;
|
||||
return @ptrCast(@alignCast(external_data));
|
||||
const tao_ptr = v8.v8__Object__GetAlignedPointerFromInternalField(value, 0).?;
|
||||
return @ptrCast(@alignCast(tao_ptr));
|
||||
}
|
||||
|
||||
fn cZigStringToString(s: v8.CZigString) ?[]const u8 {
|
||||
@@ -437,24 +377,25 @@ pub export fn v8_inspector__Client__IMPL__generateUniqueId(
|
||||
data: *anyopaque,
|
||||
) callconv(.c) i64 {
|
||||
const inspector: *Inspector = @ptrCast(@alignCast(data));
|
||||
return inspector.rnd.random().int(i64);
|
||||
const unique_id = inspector.unique_id + 1;
|
||||
inspector.unique_id = unique_id;
|
||||
return unique_id;
|
||||
}
|
||||
|
||||
pub export fn v8_inspector__Client__IMPL__runMessageLoopOnPause(
|
||||
_: *v8.InspectorClientImpl,
|
||||
data: *anyopaque,
|
||||
ctx_group_id: c_int,
|
||||
context_group_id: c_int,
|
||||
) callconv(.c) void {
|
||||
const inspector: *Inspector = @ptrCast(@alignCast(data));
|
||||
inspector.channel.onRunMessageLoopOnPause(inspector.channel.ctx, @intCast(ctx_group_id));
|
||||
_ = data;
|
||||
_ = context_group_id;
|
||||
}
|
||||
|
||||
pub export fn v8_inspector__Client__IMPL__quitMessageLoopOnPause(
|
||||
_: *v8.InspectorClientImpl,
|
||||
data: *anyopaque,
|
||||
) callconv(.c) void {
|
||||
const inspector: *Inspector = @ptrCast(@alignCast(data));
|
||||
inspector.channel.onQuitMessageLoopOnPause(inspector.channel.ctx);
|
||||
_ = data;
|
||||
}
|
||||
|
||||
pub export fn v8_inspector__Client__IMPL__runIfWaitingForDebugger(
|
||||
@@ -493,8 +434,8 @@ pub export fn v8_inspector__Channel__IMPL__sendResponse(
|
||||
msg: [*c]u8,
|
||||
length: usize,
|
||||
) callconv(.c) void {
|
||||
const inspector: *Inspector = @ptrCast(@alignCast(data));
|
||||
inspector.channel.resp(@as(u32, @intCast(call_id)), msg[0..length]);
|
||||
const session: *Session = @ptrCast(@alignCast(data));
|
||||
session.onResp(session.ctx, @intCast(call_id), msg[0..length]);
|
||||
}
|
||||
|
||||
pub export fn v8_inspector__Channel__IMPL__sendNotification(
|
||||
@@ -503,8 +444,8 @@ pub export fn v8_inspector__Channel__IMPL__sendNotification(
|
||||
msg: [*c]u8,
|
||||
length: usize,
|
||||
) callconv(.c) void {
|
||||
const inspector: *Inspector = @ptrCast(@alignCast(data));
|
||||
inspector.channel.notif(msg[0..length]);
|
||||
const session: *Session = @ptrCast(@alignCast(data));
|
||||
session.onNotif(session.ctx, msg[0..length]);
|
||||
}
|
||||
|
||||
pub export fn v8_inspector__Channel__IMPL__flushProtocolNotifications(
|
||||
|
||||
@@ -41,18 +41,6 @@ pub fn exit(self: Isolate) void {
|
||||
v8.v8__Isolate__Exit(self.handle);
|
||||
}
|
||||
|
||||
pub fn performMicrotasksCheckpoint(self: Isolate) void {
|
||||
v8.v8__Isolate__PerformMicrotaskCheckpoint(self.handle);
|
||||
}
|
||||
|
||||
pub fn enqueueMicrotask(self: Isolate, callback: anytype, data: anytype) void {
|
||||
v8.v8__Isolate__EnqueueMicrotask(self.handle, callback, data);
|
||||
}
|
||||
|
||||
pub fn enqueueMicrotaskFunc(self: Isolate, function: js.Function) void {
|
||||
v8.v8__Isolate__EnqueueMicrotaskFunc(self.handle, function.handle);
|
||||
}
|
||||
|
||||
pub fn lowMemoryNotification(self: Isolate) void {
|
||||
v8.v8__Isolate__LowMemoryNotification(self.handle);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
const std = @import("std");
|
||||
const Page = @import("../Page.zig");
|
||||
const log = @import("../../log.zig");
|
||||
const string = @import("../../string.zig");
|
||||
|
||||
@@ -75,8 +76,34 @@ pub fn newArray(self: *const Local, len: u32) js.Array {
|
||||
};
|
||||
}
|
||||
|
||||
/// Creates a new typed array. Memory is owned by JS context.
|
||||
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Typed_arrays
|
||||
pub fn createTypedArray(self: *const Local, comptime array_type: js.ArrayType, size: usize) js.ArrayBufferRef(array_type) {
|
||||
return .init(self, size);
|
||||
}
|
||||
|
||||
pub fn newCallback(
|
||||
self: *const Local,
|
||||
callback: anytype,
|
||||
data: anytype,
|
||||
) js.Function {
|
||||
const external = self.isolate.createExternal(data);
|
||||
const handle = v8.v8__Function__New__DEFAULT2(self.handle, struct {
|
||||
fn wrap(info_handle: ?*const js.v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
Caller.Function.call(@TypeOf(data), info_handle.?, callback, .{ .embedded_receiver = true });
|
||||
}
|
||||
}.wrap, @ptrCast(external)).?;
|
||||
return .{ .local = self, .handle = handle };
|
||||
}
|
||||
|
||||
pub fn runMacrotasks(self: *const Local) void {
|
||||
const env = self.ctx.env;
|
||||
env.pumpMessageLoop();
|
||||
env.runMicrotasks(); // macrotasks can cause microtasks to queue
|
||||
}
|
||||
|
||||
pub fn runMicrotasks(self: *const Local) void {
|
||||
self.isolate.performMicrotasksCheckpoint();
|
||||
self.ctx.env.runMicrotasks();
|
||||
}
|
||||
|
||||
// == Executors ==
|
||||
@@ -181,11 +208,7 @@ pub fn mapZigInstanceToJs(self: *const Local, js_obj_handle: ?*const v8.Object,
|
||||
.subtype = if (@hasDecl(JsApi.Meta, "subtype")) JsApi.Meta.subype else .node,
|
||||
};
|
||||
|
||||
// Skip setting internal field for the global object (Window)
|
||||
// Window accessors get the instance from context.page.window instead
|
||||
// if (resolved.class_id != @import("../webapi/Window.zig").JsApi.Meta.class_id) {
|
||||
v8.v8__Object__SetInternalField(js_obj.handle, 0, isolate.createExternal(tao));
|
||||
// }
|
||||
v8.v8__Object__SetAlignedPointerInInternalField(js_obj.handle, 0, tao);
|
||||
} else {
|
||||
// If the struct is empty, we don't need to do all
|
||||
// the TOA stuff and setting the internal data.
|
||||
@@ -198,21 +221,28 @@ pub fn mapZigInstanceToJs(self: *const Local, js_obj_handle: ?*const v8.Object,
|
||||
// context.global_objects, we want to track it in context.identity_map.
|
||||
v8.v8__Global__New(isolate.handle, js_obj.handle, gop.value_ptr);
|
||||
if (@hasDecl(JsApi.Meta, "finalizer")) {
|
||||
if (comptime IS_DEBUG) {
|
||||
// You can normally return a "*Node" and we'll correctly
|
||||
// handle it as what it really is, e.g. an HTMLScriptElement.
|
||||
// But for finalizers, we can't do that. I think this
|
||||
// limitation will be OK - this auto-resolution is largely
|
||||
// limited to Node -> HtmlElement, none of which has finalizers
|
||||
std.debug.assert(resolved.class_id == JsApi.Meta.class_id);
|
||||
// It would be great if resolved knew the resolved type, but I
|
||||
// can't figure out how to make that work, since it depends on
|
||||
// the [runtime] `value`.
|
||||
// We need the resolved finalizer, which we have in resolved.
|
||||
// The above if statement would be more clear as:
|
||||
// if (resolved.finalizer_from_v8) |finalizer| {
|
||||
// But that's a runtime check.
|
||||
// Instead, we check if the base has finalizer. The assumption
|
||||
// here is that if a resolve type has a finalizer, then the base
|
||||
// should have a finalizer too.
|
||||
const fc = try ctx.createFinalizerCallback(gop.value_ptr.*, resolved.ptr, resolved.finalizer_from_zig.?);
|
||||
{
|
||||
errdefer fc.deinit();
|
||||
try ctx.finalizer_callbacks.put(ctx.arena, @intFromPtr(resolved.ptr), fc);
|
||||
}
|
||||
|
||||
try ctx.finalizer_callbacks.put(ctx.arena, @intFromPtr(resolved.ptr), .init(value));
|
||||
conditionallyReference(value);
|
||||
if (@hasDecl(JsApi.Meta, "weak")) {
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(JsApi.Meta.weak == true);
|
||||
}
|
||||
v8.v8__Global__SetWeakFinalizer(gop.value_ptr, resolved.ptr, JsApi.Meta.finalizer.from_v8, v8.kParameter);
|
||||
v8.v8__Global__SetWeakFinalizer(gop.value_ptr, fc, resolved.finalizer_from_v8, v8.kParameter);
|
||||
}
|
||||
}
|
||||
return js_obj;
|
||||
@@ -303,7 +333,17 @@ pub fn zigValueToJs(self: *const Local, value: anytype, comptime opts: CallOpts)
|
||||
js.Value => return value,
|
||||
js.Exception => return .{ .local = self, .handle = isolate.throwException(value.handle) },
|
||||
|
||||
js.ArrayBufferRef(.int8).Global, js.ArrayBufferRef(.uint8).Global,
|
||||
js.ArrayBufferRef(.uint8_clamped).Global, js.ArrayBufferRef(.int16).Global,
|
||||
js.ArrayBufferRef(.uint16).Global, js.ArrayBufferRef(.int32).Global,
|
||||
js.ArrayBufferRef(.uint32).Global, js.ArrayBufferRef(.float16).Global,
|
||||
js.ArrayBufferRef(.float32).Global, js.ArrayBufferRef(.float64).Global,
|
||||
=> {
|
||||
return .{ .local = self, .handle = value.local(self).handle };
|
||||
},
|
||||
|
||||
inline
|
||||
js.Array,
|
||||
js.Function,
|
||||
js.Object,
|
||||
js.Promise,
|
||||
@@ -316,6 +356,7 @@ pub fn zigValueToJs(self: *const Local, value: anytype, comptime opts: CallOpts)
|
||||
js.Value.Temp,
|
||||
js.Object.Global,
|
||||
js.Promise.Global,
|
||||
js.Promise.Temp,
|
||||
js.PromiseResolver.Global,
|
||||
js.Module.Global => return .{ .local = self, .handle = @ptrCast(value.local(self).handle) },
|
||||
else => {}
|
||||
@@ -434,6 +475,13 @@ pub fn jsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !T {
|
||||
return js_val;
|
||||
}
|
||||
|
||||
if (comptime o.child == js.NullableString) {
|
||||
if (js_val.isUndefined()) {
|
||||
return null;
|
||||
}
|
||||
return .{ .value = try js_val.toStringSlice() };
|
||||
}
|
||||
|
||||
if (comptime o.child == js.Object) {
|
||||
return js.Object{
|
||||
.local = self,
|
||||
@@ -473,10 +521,10 @@ pub fn jsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !T {
|
||||
if (ptr.child == u8) {
|
||||
if (ptr.sentinel()) |s| {
|
||||
if (comptime s == 0) {
|
||||
return self.valueToStringZ(js_val, .{});
|
||||
return try js_val.toStringSliceZ();
|
||||
}
|
||||
} else {
|
||||
return self.valueToString(js_val, .{});
|
||||
return try js_val.toStringSlice();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -549,10 +597,8 @@ pub fn jsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !T {
|
||||
},
|
||||
.@"enum" => |e| {
|
||||
if (@hasDecl(T, "js_enum_from_string")) {
|
||||
if (!js_val.isString()) {
|
||||
return error.InvalidArgument;
|
||||
}
|
||||
return std.meta.stringToEnum(T, try self.valueToString(js_val, .{})) orelse return error.InvalidArgument;
|
||||
const js_str = js_val.isString() orelse return error.InvalidArgument;
|
||||
return std.meta.stringToEnum(T, try js_str.toSlice()) orelse return error.InvalidArgument;
|
||||
}
|
||||
switch (@typeInfo(e.tag_type)) {
|
||||
.int => return std.meta.intToEnum(T, try jsIntToZig(e.tag_type, js_val)),
|
||||
@@ -614,28 +660,27 @@ fn jsValueToStruct(self: *const Local, comptime T: type, js_val: js.Value) !?T {
|
||||
return try obj.persist();
|
||||
},
|
||||
|
||||
js.Promise.Global => {
|
||||
js.Promise.Global, js.Promise.Temp => {
|
||||
if (!js_val.isPromise()) {
|
||||
return null;
|
||||
}
|
||||
const promise = js.Promise{
|
||||
.ctx = self,
|
||||
const js_promise = js.Promise{
|
||||
.local = self,
|
||||
.handle = @ptrCast(js_val.handle),
|
||||
};
|
||||
return try promise.persist();
|
||||
return switch (T) {
|
||||
js.Promise.Temp => try js_promise.temp(),
|
||||
js.Promise.Global => try js_promise.persist(),
|
||||
else => unreachable,
|
||||
};
|
||||
},
|
||||
string.String => {
|
||||
if (!js_val.isString()) {
|
||||
return null;
|
||||
}
|
||||
return try self.valueToStringSSO(js_val, .{ .allocator = self.ctx.call_arena });
|
||||
const js_str = js_val.isString() orelse return null;
|
||||
return try js_str.toSSO(false);
|
||||
},
|
||||
string.Global => {
|
||||
if (!js_val.isString()) {
|
||||
return null;
|
||||
}
|
||||
// Use arena for persistent strings
|
||||
return .{ .str = try self.valueToStringSSO(js_val, .{ .allocator = self.ctx.arena }) };
|
||||
const js_str = js_val.isString() orelse return null;
|
||||
return try js_str.toSSO(true);
|
||||
},
|
||||
else => {
|
||||
if (!js_val.isObject()) {
|
||||
@@ -883,7 +928,7 @@ fn probeJsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !Pr
|
||||
}
|
||||
|
||||
if (ptr.child == u8) {
|
||||
if (js_val.isString()) {
|
||||
if (v8.v8__Value__IsString(js_val.handle)) {
|
||||
return .{ .ok = {} };
|
||||
}
|
||||
// anything can be coerced into a string
|
||||
@@ -931,10 +976,11 @@ fn probeJsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !Pr
|
||||
if (js_arr.len() == arr.len) {
|
||||
return .{ .ok = {} };
|
||||
}
|
||||
} else if (js_val.isString() and arr.child == u8) {
|
||||
const str = try js_val.toString(self.local);
|
||||
if (str.lenUtf8(self.isolate) == arr.len) {
|
||||
return .{ .ok = {} };
|
||||
} else if (arr.child == u8) {
|
||||
if (js_val.isString()) |js_str| {
|
||||
if (js_str.lenUtf8(self.isolate) == arr.len) {
|
||||
return .{ .ok = {} };
|
||||
}
|
||||
}
|
||||
}
|
||||
return .{ .invalid = {} };
|
||||
@@ -947,7 +993,7 @@ fn probeJsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !Pr
|
||||
.@"struct" => {
|
||||
// Handle string.String and string.Global specially
|
||||
if (T == string.String or T == string.Global) {
|
||||
if (js_val.isString()) {
|
||||
if (v8.v8__Value__IsString(js_val.handle)) {
|
||||
return .{ .ok = {} };
|
||||
}
|
||||
// Anything can be coerced to a string
|
||||
@@ -1032,9 +1078,12 @@ fn jsUnsignedIntToZig(comptime T: type, max: comptime_int, maybe: u32) !T {
|
||||
// This function recursively walks the _type union field (if there is one) to
|
||||
// get the most specific class_id possible.
|
||||
const Resolved = struct {
|
||||
weak: bool,
|
||||
ptr: *anyopaque,
|
||||
class_id: u16,
|
||||
prototype_chain: []const @import("TaggedOpaque.zig").PrototypeChainEntry,
|
||||
finalizer_from_v8: ?*const fn (handle: ?*const v8.WeakCallbackInfo) callconv(.c) void = null,
|
||||
finalizer_from_zig: ?*const fn (ptr: *anyopaque, page: *Page) void = null,
|
||||
};
|
||||
pub fn resolveValue(value: anytype) Resolved {
|
||||
const T = bridge.Struct(@TypeOf(value));
|
||||
@@ -1062,13 +1111,28 @@ pub fn resolveValue(value: anytype) Resolved {
|
||||
}
|
||||
|
||||
fn resolveT(comptime T: type, value: *anyopaque) Resolved {
|
||||
const Meta = T.JsApi.Meta;
|
||||
return .{
|
||||
.ptr = value,
|
||||
.class_id = T.JsApi.Meta.class_id,
|
||||
.prototype_chain = &T.JsApi.Meta.prototype_chain,
|
||||
.class_id = Meta.class_id,
|
||||
.prototype_chain = &Meta.prototype_chain,
|
||||
.weak = if (@hasDecl(Meta, "weak")) Meta.weak else false,
|
||||
.finalizer_from_v8 = if (@hasDecl(Meta, "finalizer")) Meta.finalizer.from_v8 else null,
|
||||
.finalizer_from_zig = if (@hasDecl(Meta, "finalizer")) Meta.finalizer.from_zig else null,
|
||||
};
|
||||
}
|
||||
|
||||
fn conditionallyReference(value: anytype) void {
|
||||
const T = bridge.Struct(@TypeOf(value));
|
||||
if (@hasDecl(T, "acquireRef")) {
|
||||
value.acquireRef();
|
||||
return;
|
||||
}
|
||||
if (@hasField(T, "_proto")) {
|
||||
conditionallyReference(value._proto);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stackTrace(self: *const Local) !?[]const u8 {
|
||||
const isolate = self.isolate;
|
||||
const separator = log.separator();
|
||||
@@ -1080,14 +1144,15 @@ pub fn stackTrace(self: *const Local) !?[]const u8 {
|
||||
const frame_count = v8.v8__StackTrace__GetFrameCount(stack_trace_handle);
|
||||
|
||||
if (v8.v8__StackTrace__CurrentScriptNameOrSourceURL__STATIC(isolate.handle)) |script| {
|
||||
try writer.print("{s}<{s}>", .{ separator, try self.jsStringToZig(script, .{}) });
|
||||
const stack = js.String{ .local = self, .handle = script };
|
||||
try writer.print("{s}<{f}>", .{ separator, stack });
|
||||
}
|
||||
|
||||
for (0..@intCast(frame_count)) |i| {
|
||||
const frame_handle = v8.v8__StackTrace__GetFrame(stack_trace_handle, isolate.handle, @intCast(i)).?;
|
||||
if (v8.v8__StackFrame__GetFunctionName(frame_handle)) |name| {
|
||||
const script = try self.jsStringToZig(name, .{});
|
||||
try writer.print("{s}{s}:{d}", .{ separator, script, v8.v8__StackFrame__GetLineNumber(frame_handle) });
|
||||
const script = js.String{ .local = self, .handle = name };
|
||||
try writer.print("{s}{f}:{d}", .{ separator, script, v8.v8__StackFrame__GetLineNumber(frame_handle) });
|
||||
} else {
|
||||
try writer.print("{s}<anonymous>:{d}", .{ separator, v8.v8__StackFrame__GetLineNumber(frame_handle) });
|
||||
}
|
||||
@@ -1095,100 +1160,6 @@ pub fn stackTrace(self: *const Local) !?[]const u8 {
|
||||
return buf.items;
|
||||
}
|
||||
|
||||
// == Stringifiers ==
|
||||
const ToStringOpts = struct {
|
||||
allocator: ?Allocator = null,
|
||||
};
|
||||
pub fn valueToString(self: *const Local, js_val: js.Value, opts: ToStringOpts) ![]u8 {
|
||||
return self.valueHandleToString(js_val.handle, opts);
|
||||
}
|
||||
pub fn valueToStringZ(self: *const Local, js_val: js.Value, opts: ToStringOpts) ![:0]u8 {
|
||||
return self.valueHandleToStringZ(js_val.handle, opts);
|
||||
}
|
||||
|
||||
pub fn valueHandleToString(self: *const Local, js_val: *const v8.Value, opts: ToStringOpts) ![]u8 {
|
||||
return self._valueToString(false, js_val, opts);
|
||||
}
|
||||
pub fn valueHandleToStringZ(self: *const Local, js_val: *const v8.Value, opts: ToStringOpts) ![:0]u8 {
|
||||
return self._valueToString(true, js_val, opts);
|
||||
}
|
||||
|
||||
fn _valueToString(self: *const Local, comptime null_terminate: bool, value_handle: *const v8.Value, opts: ToStringOpts) !(if (null_terminate) [:0]u8 else []u8) {
|
||||
var resolved_value_handle = value_handle;
|
||||
if (v8.v8__Value__IsSymbol(value_handle)) {
|
||||
const symbol_handle = v8.v8__Symbol__Description(@ptrCast(value_handle), self.isolate.handle).?;
|
||||
resolved_value_handle = @ptrCast(symbol_handle);
|
||||
}
|
||||
|
||||
const string_handle = v8.v8__Value__ToString(resolved_value_handle, self.handle) orelse {
|
||||
return error.JsException;
|
||||
};
|
||||
|
||||
return self._jsStringToZig(null_terminate, string_handle, opts);
|
||||
}
|
||||
|
||||
pub fn jsStringToZig(self: *const Local, str: anytype, opts: ToStringOpts) ![]u8 {
|
||||
return self._jsStringToZig(false, str, opts);
|
||||
}
|
||||
pub fn jsStringToZigZ(self: *const Local, str: anytype, opts: ToStringOpts) ![:0]u8 {
|
||||
return self._jsStringToZig(true, str, opts);
|
||||
}
|
||||
fn _jsStringToZig(self: *const Local, comptime null_terminate: bool, str: anytype, opts: ToStringOpts) !(if (null_terminate) [:0]u8 else []u8) {
|
||||
const handle = if (@TypeOf(str) == js.String) str.handle else str;
|
||||
|
||||
const len = v8.v8__String__Utf8Length(handle, self.isolate.handle);
|
||||
const allocator = opts.allocator orelse self.call_arena;
|
||||
const buf = try (if (comptime null_terminate) allocator.allocSentinel(u8, @intCast(len), 0) else allocator.alloc(u8, @intCast(len)));
|
||||
const n = v8.v8__String__WriteUtf8(handle, self.isolate.handle, buf.ptr, buf.len, v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8);
|
||||
std.debug.assert(n == len);
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
// Convert JS string to string.String with SSO
|
||||
pub fn valueToStringSSO(self: *const Local, js_val: js.Value, opts: ToStringOpts) !string.String {
|
||||
const string_handle = v8.v8__Value__ToString(js_val.handle, self.handle) orelse {
|
||||
return error.JsException;
|
||||
};
|
||||
return self.jsStringToStringSSO(string_handle, opts);
|
||||
}
|
||||
|
||||
pub fn jsStringToStringSSO(self: *const Local, str: anytype, opts: ToStringOpts) !string.String {
|
||||
const handle = if (@TypeOf(str) == js.String) str.handle else str;
|
||||
const len: usize = @intCast(v8.v8__String__Utf8Length(handle, self.isolate.handle));
|
||||
|
||||
if (len <= 12) {
|
||||
var content: [12]u8 = undefined;
|
||||
const n = v8.v8__String__WriteUtf8(handle, self.isolate.handle, &content[0], content.len, v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8);
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(n == len);
|
||||
}
|
||||
// Weird that we do this _after_, but we have to..I've seen weird issues
|
||||
// in ReleaseMode where v8 won't write to content if it starts off zero
|
||||
// initiated
|
||||
@memset(content[len..], 0);
|
||||
return .{ .len = @intCast(len), .payload = .{ .content = content } };
|
||||
}
|
||||
|
||||
const allocator = opts.allocator orelse self.call_arena;
|
||||
const buf = try allocator.alloc(u8, len);
|
||||
const n = v8.v8__String__WriteUtf8(handle, self.isolate.handle, buf.ptr, buf.len, v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8);
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(n == len);
|
||||
}
|
||||
|
||||
var prefix: [4]u8 = @splat(0);
|
||||
@memcpy(&prefix, buf[0..4]);
|
||||
|
||||
return .{
|
||||
.len = @intCast(len),
|
||||
.payload = .{ .heap = .{
|
||||
.prefix = prefix,
|
||||
.ptr = buf.ptr,
|
||||
} },
|
||||
};
|
||||
}
|
||||
|
||||
// == Promise Helpers ==
|
||||
pub fn rejectPromise(self: *const Local, value: anytype) !js.Promise {
|
||||
var resolver = js.PromiseResolver.init(self);
|
||||
@@ -1233,18 +1204,19 @@ fn _debugValue(self: *const Local, js_val: js.Value, seen: *std.AutoHashMapUnman
|
||||
|
||||
if (js_val.isSymbol()) {
|
||||
const symbol_handle = v8.v8__Symbol__Description(@ptrCast(js_val.handle), self.isolate.handle).?;
|
||||
const js_sym_str = try self.valueToString(.{ .local = self, .handle = symbol_handle }, .{});
|
||||
return writer.print("{s} (symbol)", .{js_sym_str});
|
||||
if (v8.v8__Value__IsUndefined(symbol_handle)) {
|
||||
return writer.writeAll("undefined (symbol)");
|
||||
}
|
||||
return writer.print("{f} (symbol)", .{js.String{ .local = self, .handle = @ptrCast(symbol_handle) }});
|
||||
}
|
||||
const js_type = try self.jsStringToZig(js_val.typeOf(), .{});
|
||||
const js_val_str = try self.valueToString(js_val, .{});
|
||||
const js_val_str = try js_val.toStringSlice();
|
||||
if (js_val_str.len > 2000) {
|
||||
try writer.writeAll(js_val_str[0..2000]);
|
||||
try writer.writeAll(" ... (truncated)");
|
||||
} else {
|
||||
try writer.writeAll(js_val_str);
|
||||
}
|
||||
return writer.print(" ({s})", .{js_type});
|
||||
return writer.print(" ({f})", .{js_val.typeOf()});
|
||||
}
|
||||
|
||||
const js_obj = js_val.toObject();
|
||||
@@ -1258,15 +1230,22 @@ fn _debugValue(self: *const Local, js_val: js.Value, seen: *std.AutoHashMapUnman
|
||||
gop.value_ptr.* = {};
|
||||
}
|
||||
|
||||
const names_arr = js_obj.getOwnPropertyNames();
|
||||
const len = names_arr.len();
|
||||
|
||||
if (depth > 20) {
|
||||
return writer.writeAll("...deeply nested object...");
|
||||
}
|
||||
const own_len = js_obj.getOwnPropertyNames().len();
|
||||
|
||||
const names_arr = js_obj.getOwnPropertyNames() catch {
|
||||
return writer.writeAll("...invalid object...");
|
||||
};
|
||||
const len = names_arr.len();
|
||||
|
||||
const own_len = blk: {
|
||||
const own_names = js_obj.getOwnPropertyNames() catch break :blk 0;
|
||||
break :blk own_names.len();
|
||||
};
|
||||
|
||||
if (own_len == 0) {
|
||||
const js_val_str = try self.valueToString(js_val, .{});
|
||||
const js_val_str = try js_val.toStringSlice();
|
||||
if (js_val_str.len > 2000) {
|
||||
try writer.writeAll(js_val_str[0..2000]);
|
||||
return writer.writeAll(" ... (truncated)");
|
||||
@@ -1281,10 +1260,11 @@ fn _debugValue(self: *const Local, js_val: js.Value, seen: *std.AutoHashMapUnman
|
||||
try writer.writeByte('\n');
|
||||
}
|
||||
const field_name = try names_arr.get(@intCast(i));
|
||||
const name = try self.valueToString(field_name, .{});
|
||||
const name = try field_name.toStringSlice();
|
||||
try writer.splatByteAll(' ', depth);
|
||||
try writer.writeAll(name);
|
||||
try writer.writeAll(": ");
|
||||
|
||||
const field_val = try js_obj.get(name);
|
||||
try self._debugValue(field_val, seen, depth + 1, writer);
|
||||
if (i != len - 1) {
|
||||
@@ -1382,6 +1362,7 @@ pub const Scope = struct {
|
||||
handle_scope: js.HandleScope,
|
||||
|
||||
pub fn deinit(self: *Scope) void {
|
||||
v8.v8__Context__Exit(self.local.handle);
|
||||
self.handle_scope.deinit();
|
||||
}
|
||||
|
||||
|
||||
@@ -131,7 +131,7 @@ const Requests = struct {
|
||||
const Request = struct {
|
||||
handle: *const v8.ModuleRequest,
|
||||
|
||||
pub fn specifier(self: Request) *const v8.String {
|
||||
return v8.v8__ModuleRequest__GetSpecifier(self.handle).?;
|
||||
pub fn specifier(self: Request, local: *const js.Local) js.String {
|
||||
return .{ .local = local, .handle = v8.v8__ModuleRequest__GetSpecifier(self.handle).? };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
@@ -22,10 +22,6 @@ const v8 = js.v8;
|
||||
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
const Context = @import("Context.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const Object = @This();
|
||||
|
||||
local: *const js.Local,
|
||||
@@ -80,10 +76,6 @@ pub fn defineOwnProperty(self: Object, name: []const u8, value: js.Value, attr:
|
||||
}
|
||||
}
|
||||
|
||||
pub fn toString(self: Object) ![]const u8 {
|
||||
return self.local.ctx.valueToString(self.toValue(), .{});
|
||||
}
|
||||
|
||||
pub fn toValue(self: Object) js.Value {
|
||||
return .{
|
||||
.local = self.local,
|
||||
@@ -137,8 +129,14 @@ pub fn isNullOrUndefined(self: Object) bool {
|
||||
return v8.v8__Value__IsNullOrUndefined(@ptrCast(self.handle));
|
||||
}
|
||||
|
||||
pub fn getOwnPropertyNames(self: Object) js.Array {
|
||||
const handle = v8.v8__Object__GetOwnPropertyNames(self.handle, self.local.handle).?;
|
||||
pub fn getOwnPropertyNames(self: Object) !js.Array {
|
||||
const handle = v8.v8__Object__GetOwnPropertyNames(self.handle, self.local.handle) orelse {
|
||||
// This is almost always a fatal error case. Either we're in some exception
|
||||
// and things are messy, or we're shutting down, or someone has messed up
|
||||
// the object (like some WPT tests do).
|
||||
return error.TypeError;
|
||||
};
|
||||
|
||||
return .{
|
||||
.local = self.local,
|
||||
.handle = handle,
|
||||
@@ -153,8 +151,11 @@ pub fn getPropertyNames(self: Object) js.Array {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn nameIterator(self: Object) NameIterator {
|
||||
const handle = v8.v8__Object__GetPropertyNames(self.handle, self.local.handle).?;
|
||||
pub fn nameIterator(self: Object) !NameIterator {
|
||||
const handle = v8.v8__Object__GetPropertyNames(self.handle, self.local.handle) orelse {
|
||||
// see getOwnPropertyNames above
|
||||
return error.TypeError;
|
||||
};
|
||||
const count = v8.v8__Array__Length(handle);
|
||||
|
||||
return .{
|
||||
@@ -201,8 +202,8 @@ pub const NameIterator = struct {
|
||||
}
|
||||
self.idx += 1;
|
||||
|
||||
const js_val_handle = v8.v8__Object__GetIndex(@ptrCast(self.handle), self.local.handle, idx) orelse return error.JsException;
|
||||
const js_val = js.Value{ .local = self.local, .handle = js_val_handle };
|
||||
return try self.local.valueToString(js_val, .{});
|
||||
const local = self.local;
|
||||
const js_val_handle = v8.v8__Object__GetIndex(@ptrCast(self.handle), local.handle, idx) orelse return error.JsException;
|
||||
return try js.Value.toStringSlice(.{ .local = local, .handle = js_val_handle });
|
||||
}
|
||||
};
|
||||
|
||||
42
src/browser/js/Private.zig
Normal file
42
src/browser/js/Private.zig
Normal file
@@ -0,0 +1,42 @@
|
||||
// Copyright (C) 2023-2026 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 Private = @This();
|
||||
|
||||
// Unlike most types, we always store the Private as a Global. It makes more
|
||||
// sense for this type given how it's used.
|
||||
handle: v8.Global,
|
||||
|
||||
pub fn init(isolate: *v8.Isolate, name: []const u8) Private {
|
||||
const v8_name = v8.v8__String__NewFromUtf8(isolate, name.ptr, v8.kNormal, @intCast(name.len));
|
||||
const private_handle = v8.v8__Private__New(isolate, v8_name);
|
||||
|
||||
var global: v8.Global = undefined;
|
||||
v8.v8__Global__New(isolate, private_handle, &global);
|
||||
|
||||
return .{
|
||||
.handle = global,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Private) void {
|
||||
v8.v8__Global__Reset(&self.handle);
|
||||
}
|
||||
@@ -47,25 +47,49 @@ pub fn thenAndCatch(self: Promise, on_fulfilled: js.Function, on_rejected: js.Fu
|
||||
}
|
||||
return error.PromiseChainFailed;
|
||||
}
|
||||
|
||||
pub fn persist(self: Promise) !Global {
|
||||
return self._persist(true);
|
||||
}
|
||||
|
||||
pub fn temp(self: Promise) !Temp {
|
||||
return self._persist(false);
|
||||
}
|
||||
|
||||
fn _persist(self: *const Promise, comptime is_global: bool) !(if (is_global) Global else Temp) {
|
||||
var ctx = self.local.ctx;
|
||||
|
||||
var global: v8.Global = undefined;
|
||||
v8.v8__Global__New(ctx.isolate.handle, self.handle, &global);
|
||||
try ctx.global_promises.append(ctx.arena, global);
|
||||
if (comptime is_global) {
|
||||
try ctx.global_promises.append(ctx.arena, global);
|
||||
} else {
|
||||
try ctx.global_promises_temp.put(ctx.arena, global.data_ptr, global);
|
||||
}
|
||||
return .{ .handle = global };
|
||||
}
|
||||
|
||||
pub const Global = struct {
|
||||
handle: v8.Global,
|
||||
pub const Temp = G(0);
|
||||
pub const Global = G(1);
|
||||
|
||||
pub fn deinit(self: *Global) void {
|
||||
v8.v8__Global__Reset(&self.handle);
|
||||
}
|
||||
fn G(comptime discriminator: u8) type {
|
||||
return struct {
|
||||
handle: v8.Global,
|
||||
|
||||
pub fn local(self: *const Global, l: *const js.Local) Promise {
|
||||
return .{
|
||||
.local = l,
|
||||
.handle = @ptrCast(v8.v8__Global__Get(&self.handle, l.isolate.handle)),
|
||||
};
|
||||
}
|
||||
};
|
||||
// makes the types different (G(0) != G(1)), without taking up space
|
||||
comptime _: u8 = discriminator,
|
||||
|
||||
const Self = @This();
|
||||
|
||||
pub fn deinit(self: *Self) void {
|
||||
v8.v8__Global__Reset(&self.handle);
|
||||
}
|
||||
|
||||
pub fn local(self: *const Self, l: *const js.Local) Promise {
|
||||
return .{
|
||||
.local = l,
|
||||
.handle = @ptrCast(v8.v8__Global__Get(&self.handle, l.isolate.handle)),
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
@@ -19,6 +19,23 @@
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const Name = @This();
|
||||
const PromiseRejection = @This();
|
||||
|
||||
handle: *const v8.Name,
|
||||
local: *const js.Local,
|
||||
handle: *const v8.PromiseRejectMessage,
|
||||
|
||||
pub fn promise(self: PromiseRejection) js.Promise {
|
||||
return .{
|
||||
.local = self.local,
|
||||
.handle = v8.v8__PromiseRejectMessage__GetPromise(self.handle).?,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn reason(self: PromiseRejection) ?js.Value {
|
||||
const value_handle = v8.v8__PromiseRejectMessage__GetValue(self.handle) orelse return null;
|
||||
|
||||
return .{
|
||||
.local = self.local,
|
||||
.handle = value_handle,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
@@ -19,9 +19,8 @@
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
|
||||
const js = @import("js/js.zig");
|
||||
const log = @import("../log.zig");
|
||||
const milliTimestamp = @import("../datetime.zig").milliTimestamp;
|
||||
const log = @import("../../log.zig");
|
||||
const milliTimestamp = @import("../../datetime.zig").milliTimestamp;
|
||||
|
||||
const IS_DEBUG = builtin.mode == .Debug;
|
||||
|
||||
@@ -48,9 +47,15 @@ pub fn init(allocator: std.mem.Allocator) Scheduler {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Scheduler) void {
|
||||
finalizeTasks(&self.low_priority);
|
||||
finalizeTasks(&self.high_priority);
|
||||
}
|
||||
|
||||
const AddOpts = struct {
|
||||
name: []const u8 = "",
|
||||
low_priority: bool = false,
|
||||
finalizer: ?Finalizer = null,
|
||||
};
|
||||
pub fn add(self: *Scheduler, ctx: *anyopaque, cb: Callback, run_in_ms: u32, opts: AddOpts) !void {
|
||||
if (comptime IS_DEBUG) {
|
||||
@@ -64,6 +69,7 @@ pub fn add(self: *Scheduler, ctx: *anyopaque, cb: Callback, run_in_ms: u32, opts
|
||||
.callback = cb,
|
||||
.sequence = seq,
|
||||
.name = opts.name,
|
||||
.finalizer = opts.finalizer,
|
||||
.run_at = milliTimestamp(.monotonic) + run_in_ms,
|
||||
});
|
||||
}
|
||||
@@ -73,6 +79,11 @@ pub fn run(self: *Scheduler) !?u64 {
|
||||
return self.runQueue(&self.high_priority);
|
||||
}
|
||||
|
||||
pub fn hasReadyTasks(self: *Scheduler) bool {
|
||||
const now = milliTimestamp(.monotonic);
|
||||
return queueuHasReadyTask(&self.low_priority, now) or queueuHasReadyTask(&self.high_priority, now);
|
||||
}
|
||||
|
||||
fn runQueue(self: *Scheduler, queue: *Queue) !?u64 {
|
||||
if (queue.count() == 0) {
|
||||
return null;
|
||||
@@ -106,12 +117,28 @@ fn runQueue(self: *Scheduler, queue: *Queue) !?u64 {
|
||||
return null;
|
||||
}
|
||||
|
||||
fn queueuHasReadyTask(queue: *Queue, now: u64) bool {
|
||||
const task = queue.peek() orelse return false;
|
||||
return task.run_at <= now;
|
||||
}
|
||||
|
||||
fn finalizeTasks(queue: *Queue) void {
|
||||
var it = queue.iterator();
|
||||
while (it.next()) |t| {
|
||||
if (t.finalizer) |func| {
|
||||
func(t.ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const Task = struct {
|
||||
run_at: u64,
|
||||
sequence: u64,
|
||||
ctx: *anyopaque,
|
||||
name: []const u8,
|
||||
callback: Callback,
|
||||
finalizer: ?Finalizer,
|
||||
};
|
||||
|
||||
const Callback = *const fn (ctx: *anyopaque) anyerror!?u32;
|
||||
const Finalizer = *const fn (ctx: *anyopaque) void;
|
||||
@@ -202,12 +202,16 @@ pub fn create() !Snapshot {
|
||||
const name = JsApi.Meta.name;
|
||||
const illegal_class_name = v8.v8__String__NewFromUtf8(isolate, name.ptr, v8.kNormal, @intCast(name.len));
|
||||
var maybe_result2: v8.MaybeBool = undefined;
|
||||
v8.v8__Object__Set(global_obj, context, illegal_class_name, func, &maybe_result2);
|
||||
v8.v8__Object__DefineOwnProperty(global_obj, context, illegal_class_name, func, 0, &maybe_result2);
|
||||
} else {
|
||||
const name = JsApi.Meta.name;
|
||||
const v8_class_name = v8.v8__String__NewFromUtf8(isolate, name.ptr, v8.kNormal, @intCast(name.len));
|
||||
var maybe_result: v8.MaybeBool = undefined;
|
||||
v8.v8__Object__Set(global_obj, context, v8_class_name, func, &maybe_result);
|
||||
var properties: v8.PropertyAttribute = v8.None;
|
||||
if (@hasDecl(JsApi.Meta, "enumerable") and JsApi.Meta.enumerable == false) {
|
||||
properties |= v8.DontEnum;
|
||||
}
|
||||
v8.v8__Object__DefineOwnProperty(global_obj, context, v8_class_name, func, properties, &maybe_result);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -261,12 +265,30 @@ pub fn create() !Snapshot {
|
||||
};
|
||||
}
|
||||
|
||||
// Helper to check if a JsApi has a NamedIndexed handler
|
||||
fn hasNamedIndexedGetter(comptime JsApi: type) bool {
|
||||
const declarations = @typeInfo(JsApi).@"struct".decls;
|
||||
inline for (declarations) |d| {
|
||||
const value = @field(JsApi, d.name);
|
||||
const T = @TypeOf(value);
|
||||
if (T == bridge.NamedIndexed) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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;
|
||||
var count: comptime_int = 0;
|
||||
|
||||
// +1 for the illegal constructor callback shared by various types
|
||||
count += 1;
|
||||
|
||||
// +1 for the noop function shared by various types
|
||||
count += 1;
|
||||
|
||||
inline for (JsApis) |JsApi| {
|
||||
// Constructor (only if explicit)
|
||||
@@ -286,13 +308,18 @@ fn countExternalReferences() comptime_int {
|
||||
const T = @TypeOf(value);
|
||||
if (T == bridge.Accessor) {
|
||||
count += 1; // getter
|
||||
if (value.setter != null) count += 1; // setter
|
||||
if (value.setter != null) {
|
||||
count += 1;
|
||||
}
|
||||
} else if (T == bridge.Function) {
|
||||
count += 1;
|
||||
} else if (T == bridge.Iterator) {
|
||||
count += 1;
|
||||
} else if (T == bridge.Indexed) {
|
||||
count += 1;
|
||||
if (value.enumerator != null) {
|
||||
count += 1;
|
||||
}
|
||||
} else if (T == bridge.NamedIndexed) {
|
||||
count += 1; // getter
|
||||
if (value.setter != null) count += 1;
|
||||
@@ -301,6 +328,15 @@ fn countExternalReferences() comptime_int {
|
||||
}
|
||||
}
|
||||
|
||||
// In debug mode, add unknown property callbacks for types without NamedIndexed
|
||||
if (comptime IS_DEBUG) {
|
||||
inline for (JsApis) |JsApi| {
|
||||
if (!hasNamedIndexedGetter(JsApi)) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count + 1; // +1 for null terminator
|
||||
}
|
||||
|
||||
@@ -311,6 +347,9 @@ fn collectExternalReferences() [countExternalReferences()]isize {
|
||||
references[idx] = @bitCast(@intFromPtr(&illegalConstructorCallback));
|
||||
idx += 1;
|
||||
|
||||
references[idx] = @bitCast(@intFromPtr(&bridge.Function.noopFunction));
|
||||
idx += 1;
|
||||
|
||||
inline for (JsApis) |JsApi| {
|
||||
if (@hasDecl(JsApi, "constructor")) {
|
||||
references[idx] = @bitCast(@intFromPtr(JsApi.constructor.func));
|
||||
@@ -342,6 +381,10 @@ fn collectExternalReferences() [countExternalReferences()]isize {
|
||||
} else if (T == bridge.Indexed) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.getter));
|
||||
idx += 1;
|
||||
if (value.enumerator) |enumerator| {
|
||||
references[idx] = @bitCast(@intFromPtr(enumerator));
|
||||
idx += 1;
|
||||
}
|
||||
} else if (T == bridge.NamedIndexed) {
|
||||
references[idx] = @bitCast(@intFromPtr(value.getter));
|
||||
idx += 1;
|
||||
@@ -357,6 +400,16 @@ fn collectExternalReferences() [countExternalReferences()]isize {
|
||||
}
|
||||
}
|
||||
|
||||
// In debug mode, collect unknown property callbacks for types without NamedIndexed
|
||||
if (comptime IS_DEBUG) {
|
||||
inline for (JsApis) |JsApi| {
|
||||
if (!hasNamedIndexedGetter(JsApi)) {
|
||||
references[idx] = @bitCast(@intFromPtr(bridge.unknownObjectPropertyCallback(JsApi)));
|
||||
idx += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return references;
|
||||
}
|
||||
|
||||
@@ -377,9 +430,12 @@ fn generateConstructor(comptime JsApi: type, isolate: *v8.Isolate) *v8.FunctionT
|
||||
};
|
||||
|
||||
const template = @constCast(v8.v8__FunctionTemplate__New__DEFAULT2(isolate, callback).?);
|
||||
if (!@hasDecl(JsApi.Meta, "empty_with_no_proto")) {
|
||||
const instance_template = v8.v8__FunctionTemplate__InstanceTemplate(template);
|
||||
v8.v8__ObjectTemplate__SetInternalFieldCount(instance_template, 1);
|
||||
{
|
||||
const internal_field_count = comptime countInternalFields(JsApi);
|
||||
if (internal_field_count > 0) {
|
||||
const instance_template = v8.v8__FunctionTemplate__InstanceTemplate(template);
|
||||
v8.v8__ObjectTemplate__SetInternalFieldCount(instance_template, internal_field_count);
|
||||
}
|
||||
}
|
||||
const name_str = if (@hasDecl(JsApi.Meta, "name")) JsApi.Meta.name else @typeName(JsApi);
|
||||
const class_name = v8.v8__String__NewFromUtf8(isolate, name_str.ptr, v8.kNormal, @intCast(name_str.len));
|
||||
@@ -387,12 +443,51 @@ fn generateConstructor(comptime JsApi: type, isolate: *v8.Isolate) *v8.FunctionT
|
||||
return template;
|
||||
}
|
||||
|
||||
pub fn countInternalFields(comptime JsApi: type) u8 {
|
||||
var last_used_id = 0;
|
||||
var cache_count: u8 = 0;
|
||||
|
||||
inline for (@typeInfo(JsApi).@"struct".decls) |d| {
|
||||
const name: [:0]const u8 = d.name;
|
||||
const value = @field(JsApi, name);
|
||||
const definition = @TypeOf(value);
|
||||
|
||||
switch (definition) {
|
||||
inline bridge.Accessor, bridge.Function => {
|
||||
const cache = value.cache orelse continue;
|
||||
if (cache != .internal) {
|
||||
continue;
|
||||
}
|
||||
// We assert that they are declared in-order. This isn't necessary
|
||||
// but I don't want to do anything fancy to look for gaps or
|
||||
// duplicates.
|
||||
const internal_id = cache.internal;
|
||||
if (internal_id != last_used_id + 1) {
|
||||
@compileError(@typeName(JsApi) ++ "." ++ name ++ " has a non-monotonic cache index");
|
||||
}
|
||||
last_used_id = internal_id;
|
||||
cache_count += 1; // this is just last_used, but it's more explicit this way
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
if (@hasDecl(JsApi.Meta, "empty_with_no_proto")) {
|
||||
return cache_count;
|
||||
}
|
||||
|
||||
// we need cache_count internal fields, + 1 for the TAO pointer (the v8 -> Zig)
|
||||
// mapping) itself.
|
||||
return cache_count + 1;
|
||||
}
|
||||
|
||||
// Attaches JsApi members to the prototype template (normal case)
|
||||
fn attachClass(comptime JsApi: type, isolate: *v8.Isolate, template: *v8.FunctionTemplate) void {
|
||||
const target = v8.v8__FunctionTemplate__PrototypeTemplate(template);
|
||||
const instance = v8.v8__FunctionTemplate__InstanceTemplate(template);
|
||||
const prototype = v8.v8__FunctionTemplate__PrototypeTemplate(template);
|
||||
|
||||
const declarations = @typeInfo(JsApi).@"struct".decls;
|
||||
var has_named_index_getter = false;
|
||||
|
||||
inline for (declarations) |d| {
|
||||
const name: [:0]const u8 = d.name;
|
||||
@@ -402,37 +497,37 @@ fn attachClass(comptime JsApi: type, isolate: *v8.Isolate, template: *v8.Functio
|
||||
switch (definition) {
|
||||
bridge.Accessor => {
|
||||
const js_name = v8.v8__String__NewFromUtf8(isolate, name.ptr, v8.kNormal, @intCast(name.len));
|
||||
const getter_callback = @constCast(v8.v8__FunctionTemplate__New__DEFAULT2(isolate, value.getter).?);
|
||||
const getter_callback = @constCast(v8.v8__FunctionTemplate__New__Config(isolate, &.{ .callback = value.getter }).?);
|
||||
if (value.setter == null) {
|
||||
if (value.static) {
|
||||
v8.v8__Template__SetAccessorProperty__DEFAULT(@ptrCast(template), js_name, getter_callback);
|
||||
} else {
|
||||
v8.v8__ObjectTemplate__SetAccessorProperty__DEFAULT(target, js_name, getter_callback);
|
||||
v8.v8__ObjectTemplate__SetAccessorProperty__DEFAULT(prototype, js_name, getter_callback);
|
||||
}
|
||||
} else {
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(value.static == false);
|
||||
}
|
||||
const setter_callback = @constCast(v8.v8__FunctionTemplate__New__DEFAULT2(isolate, value.setter.?).?);
|
||||
v8.v8__ObjectTemplate__SetAccessorProperty__DEFAULT2(target, js_name, getter_callback, setter_callback);
|
||||
const setter_callback = @constCast(v8.v8__FunctionTemplate__New__Config(isolate, &.{ .callback = value.setter.? }).?);
|
||||
v8.v8__ObjectTemplate__SetAccessorProperty__DEFAULT2(prototype, js_name, getter_callback, setter_callback);
|
||||
}
|
||||
},
|
||||
bridge.Function => {
|
||||
const function_template = @constCast(v8.v8__FunctionTemplate__New__DEFAULT2(isolate, value.func).?);
|
||||
const function_template = @constCast(v8.v8__FunctionTemplate__New__Config(isolate, &.{ .callback = value.func, .length = value.arity }).?);
|
||||
const js_name = v8.v8__String__NewFromUtf8(isolate, name.ptr, v8.kNormal, @intCast(name.len));
|
||||
if (value.static) {
|
||||
v8.v8__Template__Set(@ptrCast(template), js_name, @ptrCast(function_template), v8.None);
|
||||
} else {
|
||||
v8.v8__Template__Set(@ptrCast(target), js_name, @ptrCast(function_template), v8.None);
|
||||
v8.v8__Template__Set(@ptrCast(prototype), js_name, @ptrCast(function_template), v8.None);
|
||||
}
|
||||
},
|
||||
bridge.Indexed => {
|
||||
var configuration: v8.IndexedPropertyHandlerConfiguration = .{
|
||||
.getter = value.getter,
|
||||
.enumerator = value.enumerator,
|
||||
.setter = null,
|
||||
.query = null,
|
||||
.deleter = null,
|
||||
.enumerator = null,
|
||||
.definer = null,
|
||||
.descriptor = null,
|
||||
.data = null,
|
||||
@@ -453,27 +548,32 @@ fn attachClass(comptime JsApi: type, isolate: *v8.Isolate, template: *v8.Functio
|
||||
.flags = v8.kOnlyInterceptStrings | v8.kNonMasking,
|
||||
};
|
||||
v8.v8__ObjectTemplate__SetNamedHandler(instance, &configuration);
|
||||
has_named_index_getter = true;
|
||||
},
|
||||
bridge.Iterator => {
|
||||
const function_template = @constCast(v8.v8__FunctionTemplate__New__DEFAULT2(isolate, value.func).?);
|
||||
const function_template = @constCast(v8.v8__FunctionTemplate__New__Config(isolate, &.{ .callback = value.func }).?);
|
||||
const js_name = if (value.async)
|
||||
v8.v8__Symbol__GetAsyncIterator(isolate)
|
||||
else
|
||||
v8.v8__Symbol__GetIterator(isolate);
|
||||
v8.v8__Template__Set(@ptrCast(target), js_name, @ptrCast(function_template), v8.None);
|
||||
v8.v8__Template__Set(@ptrCast(prototype), js_name, @ptrCast(function_template), v8.None);
|
||||
},
|
||||
bridge.Property => {
|
||||
// simpleZigValueToJs now returns raw handle directly
|
||||
const js_value = switch (value) {
|
||||
.int => |v| js.simpleZigValueToJs(.{ .handle = isolate }, v, true, false),
|
||||
const js_value = switch (value.value) {
|
||||
.null => js.simpleZigValueToJs(.{ .handle = isolate }, null, true, false),
|
||||
inline .bool, .int, .float, .string => |v| js.simpleZigValueToJs(.{ .handle = isolate }, v, true, false),
|
||||
};
|
||||
|
||||
const js_name = v8.v8__String__NewFromUtf8(isolate, name.ptr, v8.kNormal, @intCast(name.len));
|
||||
// apply it both to the type itself
|
||||
v8.v8__Template__Set(@ptrCast(template), js_name, js_value, v8.ReadOnly + v8.DontDelete);
|
||||
|
||||
// and to instances of the type
|
||||
v8.v8__Template__Set(@ptrCast(target), js_name, js_value, v8.ReadOnly + v8.DontDelete);
|
||||
{
|
||||
const flags = if (value.readonly) v8.ReadOnly + v8.DontDelete else 0;
|
||||
v8.v8__Template__Set(@ptrCast(prototype), js_name, js_value, flags);
|
||||
}
|
||||
|
||||
if (value.template) {
|
||||
// apply it both to the type itself (e.g. Node.Elem)
|
||||
v8.v8__Template__Set(@ptrCast(template), js_name, js_value, v8.ReadOnly + v8.DontDelete);
|
||||
}
|
||||
},
|
||||
bridge.Constructor => {}, // already handled in generateConstructor
|
||||
else => {},
|
||||
@@ -490,6 +590,23 @@ fn attachClass(comptime JsApi: type, isolate: *v8.Isolate, template: *v8.Functio
|
||||
const js_value = v8.v8__String__NewFromUtf8(isolate, JsApi.Meta.name.ptr, v8.kNormal, @intCast(JsApi.Meta.name.len));
|
||||
v8.v8__Template__Set(@ptrCast(instance), js_name, js_value, v8.ReadOnly + v8.DontDelete);
|
||||
}
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
if (!has_named_index_getter) {
|
||||
var configuration: v8.NamedPropertyHandlerConfiguration = .{
|
||||
.getter = bridge.unknownObjectPropertyCallback(JsApi),
|
||||
.setter = null,
|
||||
.query = null,
|
||||
.deleter = null,
|
||||
.enumerator = null,
|
||||
.definer = null,
|
||||
.descriptor = null,
|
||||
.data = null,
|
||||
.flags = v8.kOnlyInterceptStrings | v8.kNonMasking,
|
||||
};
|
||||
v8.v8__ObjectTemplate__SetNamedHandler(instance, &configuration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn protoIndexLookup(comptime JsApi: type) ?bridge.JsApiLookup.BackingInt {
|
||||
|
||||
@@ -18,8 +18,10 @@
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const SSO = @import("../../string.zig").String;
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
const v8 = js.v8;
|
||||
|
||||
@@ -28,26 +30,82 @@ const String = @This();
|
||||
local: *const js.Local,
|
||||
handle: *const v8.String,
|
||||
|
||||
pub const ToZigOpts = struct {
|
||||
allocator: ?Allocator = null,
|
||||
};
|
||||
|
||||
pub fn toZig(self: String, opts: ToZigOpts) ![]u8 {
|
||||
return self._toZig(false, opts);
|
||||
pub fn toSlice(self: String) ![]u8 {
|
||||
return self._toSlice(false, self.local.call_arena);
|
||||
}
|
||||
|
||||
pub fn toZigZ(self: String, opts: ToZigOpts) ![:0]u8 {
|
||||
return self._toZig(true, opts);
|
||||
pub fn toSliceZ(self: String) ![:0]u8 {
|
||||
return self._toSlice(true, self.local.call_arena);
|
||||
}
|
||||
pub fn toSliceWithAlloc(self: String, allocator: Allocator) ![]u8 {
|
||||
return self._toSlice(false, allocator);
|
||||
}
|
||||
fn _toSlice(self: String, comptime null_terminate: bool, allocator: Allocator) !(if (null_terminate) [:0]u8 else []u8) {
|
||||
const local = self.local;
|
||||
const handle = self.handle;
|
||||
const isolate = local.isolate.handle;
|
||||
|
||||
fn _toZig(self: String, comptime null_terminate: bool, opts: ToZigOpts) !(if (null_terminate) [:0]u8 else []u8) {
|
||||
const isolate = self.local.isolate.handle;
|
||||
const allocator = opts.allocator orelse self.local.ctx.call_arena;
|
||||
const len: u32 = @intCast(v8.v8__String__Utf8Length(self.handle, isolate));
|
||||
const buf = if (null_terminate) try allocator.allocSentinel(u8, len, 0) else try allocator.alloc(u8, len);
|
||||
const len = v8.v8__String__Utf8Length(handle, isolate);
|
||||
const buf = try (if (comptime null_terminate) allocator.allocSentinel(u8, @intCast(len), 0) else allocator.alloc(u8, @intCast(len)));
|
||||
const n = v8.v8__String__WriteUtf8(handle, isolate, buf.ptr, buf.len, v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8);
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(n == len);
|
||||
}
|
||||
|
||||
const options = v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8;
|
||||
const n = v8.v8__String__WriteUtf8(self.handle, isolate, buf.ptr, buf.len, options);
|
||||
std.debug.assert(n == len);
|
||||
return buf;
|
||||
}
|
||||
|
||||
pub fn toSSO(self: String, comptime global: bool) !(if (global) SSO.Global else SSO) {
|
||||
if (comptime global) {
|
||||
return .{ .str = try self.toSSOWithAlloc(self.local.ctx.arena) };
|
||||
}
|
||||
return self.toSSOWithAlloc(self.local.call_arena);
|
||||
}
|
||||
pub fn toSSOWithAlloc(self: String, allocator: Allocator) !SSO {
|
||||
const handle = self.handle;
|
||||
const isolate = self.local.isolate.handle;
|
||||
|
||||
const len: usize = @intCast(v8.v8__String__Utf8Length(handle, isolate));
|
||||
|
||||
if (len <= 12) {
|
||||
var content: [12]u8 = undefined;
|
||||
const n = v8.v8__String__WriteUtf8(handle, isolate, &content[0], content.len, v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8);
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(n == len);
|
||||
}
|
||||
// Weird that we do this _after_, but we have to..I've seen weird issues
|
||||
// in ReleaseMode where v8 won't write to content if it starts off zero
|
||||
// initiated
|
||||
@memset(content[len..], 0);
|
||||
return .{ .len = @intCast(len), .payload = .{ .content = content } };
|
||||
}
|
||||
|
||||
const buf = try allocator.alloc(u8, len);
|
||||
const n = v8.v8__String__WriteUtf8(handle, isolate, buf.ptr, buf.len, v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8);
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(n == len);
|
||||
}
|
||||
|
||||
var prefix: [4]u8 = @splat(0);
|
||||
@memcpy(&prefix, buf[0..4]);
|
||||
|
||||
return .{
|
||||
.len = @intCast(len),
|
||||
.payload = .{ .heap = .{
|
||||
.prefix = prefix,
|
||||
.ptr = buf.ptr,
|
||||
} },
|
||||
};
|
||||
}
|
||||
|
||||
pub fn format(self: String, writer: *std.Io.Writer) !void {
|
||||
const local = self.local;
|
||||
const handle = self.handle;
|
||||
const isolate = local.isolate.handle;
|
||||
|
||||
var small: [1024]u8 = undefined;
|
||||
const len = v8.v8__String__Utf8Length(handle, isolate);
|
||||
var buf = if (len < 1024) &small else local.call_arena.alloc(u8, @intCast(len)) catch return error.WriteFailed;
|
||||
|
||||
const n = v8.v8__String__WriteUtf8(handle, isolate, buf.ptr, buf.len, v8.NO_NULL_TERMINATION | v8.REPLACE_INVALID_UTF8);
|
||||
return writer.writeAll(buf[0..n]);
|
||||
}
|
||||
|
||||
@@ -95,33 +95,6 @@ pub fn fromJS(comptime R: type, js_obj_handle: *const v8.Object) !R {
|
||||
}
|
||||
|
||||
const internal_field_count = v8.v8__Object__InternalFieldCount(js_obj_handle);
|
||||
// Special case for Window: the global object doesn't have internal fields
|
||||
// Window instance is stored in context.page.window instead
|
||||
if (internal_field_count == 0) {
|
||||
// Normally, this would be an error. All JsObject that map to a Zig type
|
||||
// are either `empty_with_no_proto` (handled above) or have an
|
||||
// interalFieldCount. The only exception to that is the Window...
|
||||
const isolate = v8.v8__Object__GetIsolate(js_obj_handle).?;
|
||||
const context = js.Context.fromIsolate(.{ .handle = isolate });
|
||||
|
||||
const Window = @import("../webapi/Window.zig");
|
||||
if (T == Window) {
|
||||
return context.page.window;
|
||||
}
|
||||
|
||||
// ... Or the window's prototype.
|
||||
// We could make this all comptime-fancy, but it's easier to hard-code
|
||||
// the EventTarget
|
||||
|
||||
const EventTarget = @import("../webapi/EventTarget.zig");
|
||||
if (T == EventTarget) {
|
||||
return context.page.window._proto;
|
||||
}
|
||||
|
||||
// Type not found in Window's prototype chain
|
||||
return error.InvalidArgument;
|
||||
}
|
||||
|
||||
// if it isn't an empty struct, then the v8.Object should have an
|
||||
// InternalFieldCount > 0, since our toa pointer should be embedded
|
||||
// at index 0 of the internal field count.
|
||||
@@ -133,8 +106,8 @@ pub fn fromJS(comptime R: type, js_obj_handle: *const v8.Object) !R {
|
||||
@compileError("unknown Zig type: " ++ @typeName(R));
|
||||
}
|
||||
|
||||
const internal_field_handle = v8.v8__Object__GetInternalField(js_obj_handle, 0).?;
|
||||
const tao: *TaggedOpaque = @ptrCast(@alignCast(v8.v8__External__Value(internal_field_handle)));
|
||||
const tao_ptr = v8.v8__Object__GetAlignedPointerFromInternalField(js_obj_handle, 0).?;
|
||||
const tao: *TaggedOpaque = @ptrCast(@alignCast(tao_ptr));
|
||||
const expected_type_index = bridge.JsApiLookup.getId(JsApi);
|
||||
|
||||
const prototype_chain = tao.prototype_chain[0..tao.prototype_len];
|
||||
|
||||
@@ -20,6 +20,8 @@ const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const v8 = js.v8;
|
||||
|
||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
const TryCatch = @This();
|
||||
@@ -32,8 +34,19 @@ pub fn init(self: *TryCatch, l: *const js.Local) void {
|
||||
v8.v8__TryCatch__CONSTRUCT(&self.handle, l.isolate.handle);
|
||||
}
|
||||
|
||||
pub fn hasCaught(self: TryCatch) bool {
|
||||
return v8.v8__TryCatch__HasCaught(&self.handle);
|
||||
}
|
||||
|
||||
pub fn rethrow(self: *TryCatch) void {
|
||||
if (comptime IS_DEBUG) {
|
||||
std.debug.assert(self.hasCaught());
|
||||
}
|
||||
_ = v8.v8__TryCatch__ReThrow(&self.handle);
|
||||
}
|
||||
|
||||
pub fn caught(self: TryCatch, allocator: Allocator) ?Caught {
|
||||
if (!v8.v8__TryCatch__HasCaught(&self.handle)) {
|
||||
if (self.hasCaught() == false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -46,12 +59,38 @@ pub fn caught(self: TryCatch, allocator: Allocator) ?Caught {
|
||||
|
||||
const exception: ?[]const u8 = blk: {
|
||||
const handle = v8.v8__TryCatch__Exception(&self.handle) orelse break :blk null;
|
||||
break :blk l.valueHandleToString(@ptrCast(handle), .{ .allocator = allocator }) catch |err| @errorName(err);
|
||||
var js_val = js.Value{ .local = l, .handle = handle };
|
||||
|
||||
// If it's an Error object, try to get the message property
|
||||
if (js_val.isObject()) {
|
||||
const js_obj = js_val.toObject();
|
||||
if (js_obj.has("message")) {
|
||||
js_val = js_obj.get("message") catch break :blk null;
|
||||
}
|
||||
}
|
||||
|
||||
if (js_val.isString()) |js_str| {
|
||||
break :blk js_str.toSliceWithAlloc(allocator) catch |err| @errorName(err);
|
||||
}
|
||||
break :blk null;
|
||||
};
|
||||
|
||||
const stack: ?[]const u8 = blk: {
|
||||
const handle = v8.v8__TryCatch__StackTrace(&self.handle, l.handle) orelse break :blk null;
|
||||
break :blk l.valueHandleToString(@ptrCast(handle), .{ .allocator = allocator }) catch |err| @errorName(err);
|
||||
var js_val = js.Value{ .local = l, .handle = handle };
|
||||
|
||||
// If it's an Error object, try to get the stack property
|
||||
if (js_val.isObject()) {
|
||||
const js_obj = js_val.toObject();
|
||||
if (js_obj.has("stack")) {
|
||||
js_val = js_obj.get("stack") catch break :blk null;
|
||||
}
|
||||
}
|
||||
|
||||
if (js_val.isString()) |js_str| {
|
||||
break :blk js_str.toSliceWithAlloc(allocator) catch |err| @errorName(err);
|
||||
}
|
||||
break :blk null;
|
||||
};
|
||||
|
||||
return .{
|
||||
@@ -95,4 +134,17 @@ pub const Caught = struct {
|
||||
try writer.write(prefix ++ ".line", self.line);
|
||||
try writer.write(prefix ++ ".caught", self.caught);
|
||||
}
|
||||
|
||||
pub fn jsonStringify(self: Caught, jw: anytype) !void {
|
||||
try jw.beginObject();
|
||||
try jw.objectField("exception");
|
||||
try jw.write(self.exception);
|
||||
try jw.objectField("stack");
|
||||
try jw.write(self.stack);
|
||||
try jw.objectField("line");
|
||||
try jw.write(self.line);
|
||||
try jw.objectField("caught");
|
||||
try jw.write(self.caught);
|
||||
try jw.endObject();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
const std = @import("std");
|
||||
const js = @import("js.zig");
|
||||
const SSO = @import("../../string.zig").String;
|
||||
|
||||
const v8 = js.v8;
|
||||
|
||||
@@ -34,8 +35,12 @@ pub fn isObject(self: Value) bool {
|
||||
return v8.v8__Value__IsObject(self.handle);
|
||||
}
|
||||
|
||||
pub fn isString(self: Value) bool {
|
||||
return v8.v8__Value__IsString(self.handle);
|
||||
pub fn isString(self: Value) ?js.String {
|
||||
const handle = self.handle;
|
||||
if (!v8.v8__Value__IsString(handle)) {
|
||||
return null;
|
||||
}
|
||||
return .{ .local = self.local, .handle = @ptrCast(handle) };
|
||||
}
|
||||
|
||||
pub fn isArray(self: Value) bool {
|
||||
@@ -204,35 +209,40 @@ pub fn toPromise(self: Value) js.Promise {
|
||||
};
|
||||
}
|
||||
|
||||
pub fn toString(self: Value, opts: js.String.ToZigOpts) ![]u8 {
|
||||
return self._toString(false, opts);
|
||||
pub fn toString(self: Value) !js.String {
|
||||
const l = self.local;
|
||||
const value_handle: *const v8.Value = blk: {
|
||||
if (self.isSymbol()) {
|
||||
break :blk @ptrCast(v8.v8__Symbol__Description(@ptrCast(self.handle), l.isolate.handle).?);
|
||||
}
|
||||
break :blk self.handle;
|
||||
};
|
||||
|
||||
const str_handle = v8.v8__Value__ToString(value_handle, l.handle) orelse return error.JsException;
|
||||
return .{ .local = self.local, .handle = str_handle };
|
||||
}
|
||||
pub fn toStringZ(self: Value, opts: js.String.ToZigOpts) ![:0]u8 {
|
||||
return self._toString(true, opts);
|
||||
|
||||
pub fn toSSO(self: Value, comptime global: bool) !(if (global) SSO.Global else SSO) {
|
||||
return (try self.toString()).toSSO(global);
|
||||
}
|
||||
pub fn toSSOWithAlloc(self: Value, allocator: Allocator) !SSO {
|
||||
return (try self.toString()).toSSOWithAlloc(allocator);
|
||||
}
|
||||
|
||||
pub fn toStringSlice(self: Value) ![]u8 {
|
||||
return (try self.toString()).toSlice();
|
||||
}
|
||||
pub fn toStringSliceZ(self: Value) ![:0]u8 {
|
||||
return (try self.toString()).toSliceZ();
|
||||
}
|
||||
pub fn toStringSliceWithAlloc(self: Value, allocator: Allocator) ![]u8 {
|
||||
return (try self.toString()).toSliceWithAlloc(allocator);
|
||||
}
|
||||
|
||||
pub fn toJson(self: Value, allocator: Allocator) ![]u8 {
|
||||
const json_str_handle = v8.v8__JSON__Stringify(self.local.handle, self.handle, null) orelse return error.JsException;
|
||||
return self.local.jsStringToZig(json_str_handle, .{ .allocator = allocator });
|
||||
}
|
||||
|
||||
fn _toString(self: Value, comptime null_terminate: bool, opts: js.String.ToZigOpts) !(if (null_terminate) [:0]u8 else []u8) {
|
||||
const l = self.local;
|
||||
|
||||
if (self.isSymbol()) {
|
||||
const sym_handle = v8.v8__Symbol__Description(@ptrCast(self.handle), l.isolate.handle).?;
|
||||
return _toString(.{ .handle = @ptrCast(sym_handle), .local = l }, null_terminate, opts);
|
||||
}
|
||||
|
||||
const str_handle = v8.v8__Value__ToString(self.handle, l.handle) orelse {
|
||||
return error.JsException;
|
||||
};
|
||||
|
||||
const str = js.String{ .local = l, .handle = str_handle };
|
||||
if (comptime null_terminate) {
|
||||
return js.String.toZigZ(str, opts);
|
||||
}
|
||||
return js.String.toZig(str, opts);
|
||||
const local = self.local;
|
||||
const str_handle = v8.v8__JSON__Stringify(local.handle, self.handle, null) orelse return error.JsException;
|
||||
return js.String.toSliceWithAlloc(.{ .local = local, .handle = str_handle }, allocator);
|
||||
}
|
||||
|
||||
pub fn persist(self: Value) !Global {
|
||||
@@ -296,8 +306,8 @@ pub fn format(self: Value, writer: *std.Io.Writer) !void {
|
||||
if (comptime IS_DEBUG) {
|
||||
return self.local.debugValue(self, writer);
|
||||
}
|
||||
const str = self.toString(.{}) catch return error.WriteFailed;
|
||||
return writer.writeAll(str);
|
||||
const js_str = self.toString() catch return error.WriteFailed;
|
||||
return js_str.format(writer);
|
||||
}
|
||||
|
||||
pub const Temp = G(0);
|
||||
|
||||
@@ -38,16 +38,16 @@ pub fn Builder(comptime T: type) type {
|
||||
return Constructor.init(T, func, opts);
|
||||
}
|
||||
|
||||
pub fn accessor(comptime getter: anytype, comptime setter: anytype, comptime opts: Accessor.Opts) Accessor {
|
||||
pub fn accessor(comptime getter: anytype, comptime setter: anytype, comptime opts: Caller.Function.Opts) Accessor {
|
||||
return Accessor.init(T, getter, setter, opts);
|
||||
}
|
||||
|
||||
pub fn function(comptime func: anytype, comptime opts: Function.Opts) Function {
|
||||
pub fn function(comptime func: anytype, comptime opts: Caller.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 indexed(comptime getter_func: anytype, comptime enumerator_func: anytype, comptime opts: Indexed.Opts) Indexed {
|
||||
return Indexed.init(T, getter_func, enumerator_func, opts);
|
||||
}
|
||||
|
||||
pub fn namedIndexed(comptime getter_func: anytype, setter_func: anytype, deleter_func: anytype, comptime opts: NamedIndexed.Opts) NamedIndexed {
|
||||
@@ -62,9 +62,21 @@ pub fn Builder(comptime T: type) type {
|
||||
return Callable.init(T, func, opts);
|
||||
}
|
||||
|
||||
pub fn property(value: anytype) Property {
|
||||
pub fn property(value: anytype, opts: Property.Opts) Property {
|
||||
switch (@typeInfo(@TypeOf(value))) {
|
||||
.comptime_int, .int => return .{ .int = value },
|
||||
.bool => return Property.init(.{ .bool = value }, opts),
|
||||
.null => return Property.init(.null, opts),
|
||||
.comptime_int, .int => return Property.init(.{ .int = value }, opts),
|
||||
.comptime_float, .float => return Property.init(.{ .float = value }, opts),
|
||||
.pointer => |ptr| switch (ptr.size) {
|
||||
.one => {
|
||||
const one_info = @typeInfo(ptr.child);
|
||||
if (one_info == .array and one_info.array.child == u8) {
|
||||
return Property.init(.{ .string = value }, opts);
|
||||
}
|
||||
},
|
||||
else => {},
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
@compileError("Property for " ++ @typeName(@TypeOf(value)) ++ " hasn't been defined yet");
|
||||
@@ -92,31 +104,29 @@ pub fn Builder(comptime T: type) type {
|
||||
return entries;
|
||||
}
|
||||
|
||||
pub fn finalizer(comptime func: *const fn (self: *T, shutdown: bool) void) Finalizer {
|
||||
pub fn finalizer(comptime func: *const fn (self: *T, shutdown: bool, page: *Page) void) Finalizer {
|
||||
return .{
|
||||
.from_zig = struct {
|
||||
fn wrap(ptr: *anyopaque) void {
|
||||
func(@ptrCast(@alignCast(ptr)), true);
|
||||
fn wrap(ptr: *anyopaque, page: *Page) void {
|
||||
func(@ptrCast(@alignCast(ptr)), true, page);
|
||||
}
|
||||
}.wrap,
|
||||
|
||||
.from_v8 = struct {
|
||||
fn wrap(handle: ?*const v8.WeakCallbackInfo) callconv(.c) void {
|
||||
const ptr = v8.v8__WeakCallbackInfo__GetParameter(handle.?).?;
|
||||
const self: *T = @ptrCast(@alignCast(ptr));
|
||||
// This is simply a requirement of any type that Finalizes:
|
||||
// It must have a _page: *Page field. We need it because
|
||||
// we need to check the item has already been cleared
|
||||
// (There are all types of weird timing issues that seem
|
||||
// to be possible between finalization and context shutdown,
|
||||
// we need to be defensive).
|
||||
// There _ARE_ alternatives to this. But this is simple.
|
||||
const ctx = self._page.js;
|
||||
if (!ctx.identity_map.contains(@intFromPtr(ptr))) {
|
||||
return;
|
||||
const fc: *Context.FinalizerCallback = @ptrCast(@alignCast(ptr));
|
||||
|
||||
const ctx = fc.ctx;
|
||||
const value_ptr = fc.ptr;
|
||||
if (ctx.finalizer_callbacks.contains(@intFromPtr(value_ptr))) {
|
||||
func(@ptrCast(@alignCast(value_ptr)), false, ctx.page);
|
||||
ctx.release(value_ptr);
|
||||
} else {
|
||||
// A bit weird, but v8 _requires_ that we release it
|
||||
// If we don't. We'll 100% crash.
|
||||
v8.v8__Global__Reset(&fc.global);
|
||||
}
|
||||
func(self, false);
|
||||
ctx.release(ptr);
|
||||
}
|
||||
}.wrap,
|
||||
};
|
||||
@@ -149,82 +159,59 @@ pub const Constructor = struct {
|
||||
|
||||
pub const Function = struct {
|
||||
static: bool,
|
||||
arity: usize,
|
||||
noop: bool = false,
|
||||
cache: ?Caller.Function.Opts.Caching = null,
|
||||
func: *const fn (?*const v8.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 {
|
||||
fn init(comptime T: type, comptime func: anytype, comptime opts: Caller.Function.Opts) Function {
|
||||
return .{
|
||||
.cache = opts.cache,
|
||||
.static = opts.static,
|
||||
.func = struct {
|
||||
.arity = getArity(@TypeOf(func)),
|
||||
.func = if (opts.noop) noopFunction else struct {
|
||||
fn wrap(handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
const v8_isolate = v8.v8__FunctionCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
|
||||
if (comptime opts.static) {
|
||||
caller.function(T, func, handle.?, .{
|
||||
.dom_exception = opts.dom_exception,
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
} else {
|
||||
caller.method(T, func, handle.?, .{
|
||||
.dom_exception = opts.dom_exception,
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
Caller.Function.call(T, handle.?, func, opts);
|
||||
}
|
||||
}.wrap,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn noopFunction(_: ?*const v8.FunctionCallbackInfo) callconv(.c) void {}
|
||||
|
||||
fn getArity(comptime T: type) usize {
|
||||
var count: usize = 0;
|
||||
var params = @typeInfo(T).@"fn".params;
|
||||
for (params[1..]) |p| { // start at 1, skip self
|
||||
const PT = p.type.?;
|
||||
if (PT == *Page or PT == *const Page) {
|
||||
break;
|
||||
}
|
||||
if (@typeInfo(PT) == .optional) {
|
||||
break;
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
};
|
||||
|
||||
pub const Accessor = struct {
|
||||
static: bool = false,
|
||||
cache: ?Caller.Function.Opts.Caching = null,
|
||||
getter: ?*const fn (?*const v8.FunctionCallbackInfo) callconv(.c) void = null,
|
||||
setter: ?*const fn (?*const v8.FunctionCallbackInfo) callconv(.c) void = null,
|
||||
|
||||
const Opts = struct {
|
||||
static: bool = false,
|
||||
cache: ?[]const u8 = null,
|
||||
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 {
|
||||
fn init(comptime T: type, comptime getter: anytype, comptime setter: anytype, comptime opts: Caller.Function.Opts) Accessor {
|
||||
var accessor = Accessor{
|
||||
.cache = opts.cache,
|
||||
.static = opts.static,
|
||||
};
|
||||
|
||||
if (@typeInfo(@TypeOf(getter)) != .null) {
|
||||
accessor.getter = struct {
|
||||
fn wrap(handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
const v8_isolate = v8.v8__FunctionCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
|
||||
if (comptime opts.static) {
|
||||
caller.function(T, getter, handle.?, .{
|
||||
.cache = opts.cache,
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
} else {
|
||||
caller.method(T, getter, handle.?, .{
|
||||
.cache = opts.cache,
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
Caller.Function.call(T, handle.?, getter, opts);
|
||||
}
|
||||
}.wrap;
|
||||
}
|
||||
@@ -232,15 +219,7 @@ pub const Accessor = struct {
|
||||
if (@typeInfo(@TypeOf(setter)) != .null) {
|
||||
accessor.setter = struct {
|
||||
fn wrap(handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
const v8_isolate = v8.v8__FunctionCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
|
||||
caller.method(T, setter, handle.?, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
Caller.Function.call(T, handle.?, setter, opts);
|
||||
}
|
||||
}.wrap;
|
||||
}
|
||||
@@ -251,26 +230,44 @@ pub const Accessor = struct {
|
||||
|
||||
pub const Indexed = struct {
|
||||
getter: *const fn (idx: u32, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8,
|
||||
enumerator: ?*const fn (handle: ?*const v8.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, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const v8_isolate = v8.v8__PropertyCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
fn init(comptime T: type, comptime getter: anytype, comptime enumerator: anytype, comptime opts: Opts) Indexed {
|
||||
var indexed = Indexed{
|
||||
.enumerator = null,
|
||||
.getter = struct {
|
||||
fn wrap(idx: u32, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const v8_isolate = v8.v8__PropertyCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
|
||||
return caller.getIndex(T, getter, idx, handle.?, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap };
|
||||
return caller.getIndex(T, getter, idx, handle.?, .{
|
||||
.as_typed_array = opts.as_typed_array,
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap,
|
||||
};
|
||||
|
||||
if (@typeInfo(@TypeOf(enumerator)) != .null) {
|
||||
indexed.enumerator = struct {
|
||||
fn wrap(handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const v8_isolate = v8.v8__PropertyCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
return caller.getEnumerator(T, enumerator, handle.?, .{});
|
||||
}
|
||||
}.wrap;
|
||||
}
|
||||
|
||||
return indexed;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -361,11 +358,9 @@ pub const Iterator = struct {
|
||||
.async = opts.async,
|
||||
.func = struct {
|
||||
fn wrap(handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
const v8_isolate = v8.v8__FunctionCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
caller.method(T, struct_or_func, handle.?, .{});
|
||||
return Caller.Function.call(T, handle.?, struct_or_func, .{
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
}.wrap,
|
||||
};
|
||||
@@ -382,12 +377,7 @@ pub const Callable = struct {
|
||||
fn init(comptime T: type, comptime func: anytype, comptime opts: Opts) Callable {
|
||||
return .{ .func = struct {
|
||||
fn wrap(handle: ?*const v8.FunctionCallbackInfo) callconv(.c) void {
|
||||
const v8_isolate = v8.v8__FunctionCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
|
||||
caller.method(T, func, handle.?, .{
|
||||
Caller.Function.call(T, handle.?, func, .{
|
||||
.null_as_undefined = opts.null_as_undefined,
|
||||
});
|
||||
}
|
||||
@@ -395,14 +385,37 @@ pub const Callable = struct {
|
||||
}
|
||||
};
|
||||
|
||||
pub const Property = union(enum) {
|
||||
int: i64,
|
||||
pub const Property = struct {
|
||||
value: Value,
|
||||
template: bool,
|
||||
readonly: bool,
|
||||
|
||||
const Value = union(enum) {
|
||||
null,
|
||||
int: i64,
|
||||
float: f64,
|
||||
bool: bool,
|
||||
string: []const u8,
|
||||
};
|
||||
|
||||
const Opts = struct {
|
||||
template: bool,
|
||||
readonly: bool = true,
|
||||
};
|
||||
|
||||
fn init(value: Value, opts: Opts) Property {
|
||||
return .{
|
||||
.value = value,
|
||||
.template = opts.template,
|
||||
.readonly = opts.readonly,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const Finalizer = struct {
|
||||
// The finalizer wrapper when called fro Zig. This is only called on
|
||||
// Context.deinit
|
||||
from_zig: *const fn (ctx: *anyopaque) void,
|
||||
from_zig: *const fn (ctx: *anyopaque, page: *Page) void,
|
||||
|
||||
// The finalizer wrapper when called from V8. This may never be called
|
||||
// (hence why we fallback to calling in Context.denit). If it is called,
|
||||
@@ -410,7 +423,7 @@ const Finalizer = struct {
|
||||
from_v8: *const fn (?*const v8.WeakCallbackInfo) callconv(.c) void,
|
||||
};
|
||||
|
||||
pub fn unknownPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||
pub fn unknownWindowPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const v8_isolate = v8.v8__PropertyCallbackInfo__GetIsolate(handle).?;
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
@@ -422,7 +435,7 @@ pub fn unknownPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8.Prope
|
||||
hs.init(local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const property: []const u8 = local.valueHandleToString(@ptrCast(c_name.?), .{}) catch {
|
||||
const property: []const u8 = js.String.toSlice(.{ .local = local, .handle = @ptrCast(c_name.?) }) catch {
|
||||
return 0;
|
||||
};
|
||||
|
||||
@@ -437,11 +450,21 @@ pub fn unknownPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8.Prope
|
||||
}
|
||||
|
||||
if (comptime IS_DEBUG) {
|
||||
if (std.mem.startsWith(u8, property, "__")) {
|
||||
// some frameworks will extend built-in types using a __ prefix
|
||||
// these should always be safe to ignore.
|
||||
return 0;
|
||||
}
|
||||
|
||||
const ignored = std.StaticStringMap(void).initComptime(.{
|
||||
.{ "Deno", {} },
|
||||
.{ "process", {} },
|
||||
.{ "ShadyDOM", {} },
|
||||
.{ "ShadyCSS", {} },
|
||||
|
||||
// a lot of sites seem to like having their own window.config.
|
||||
.{ "config", {} },
|
||||
|
||||
.{ "litNonce", {} },
|
||||
.{ "litHtmlVersions", {} },
|
||||
.{ "litElementVersions", {} },
|
||||
@@ -457,13 +480,12 @@ pub fn unknownPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8.Prope
|
||||
.{ "__google_recaptcha_client", {} },
|
||||
|
||||
.{ "CLOSURE_FLAGS", {} },
|
||||
.{ "__REACT_DEVTOOLS_GLOBAL_HOOK__", {} },
|
||||
.{ "ApplePaySession", {} },
|
||||
});
|
||||
if (!ignored.has(property)) {
|
||||
log.debug(.unknown_prop, "unknown global property", .{
|
||||
.info = "but the property can exist in pure JS",
|
||||
.stack = local.stackTrace() catch "???",
|
||||
.property = property,
|
||||
});
|
||||
const key = std.fmt.bufPrint(&local.ctx.page.buf, "Window:{s}", .{property}) catch return 0;
|
||||
logUnknownProperty(local, key) catch return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -471,6 +493,83 @@ pub fn unknownPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8.Prope
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Only used for debugging
|
||||
pub fn unknownObjectPropertyCallback(comptime JsApi: type) *const fn (?*const v8.Name, ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||
if (comptime !IS_DEBUG) {
|
||||
@compileError("unknownObjectPropertyCallback should only be used in debug builds");
|
||||
}
|
||||
|
||||
return struct {
|
||||
fn wrap(c_name: ?*const v8.Name, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||
const v8_isolate = v8.v8__PropertyCallbackInfo__GetIsolate(handle).?;
|
||||
|
||||
var caller: Caller = undefined;
|
||||
caller.init(v8_isolate);
|
||||
defer caller.deinit();
|
||||
|
||||
const local = &caller.local;
|
||||
|
||||
var hs: js.HandleScope = undefined;
|
||||
hs.init(local.isolate);
|
||||
defer hs.deinit();
|
||||
|
||||
const property: []const u8 = js.String.toSlice(.{ .local = local, .handle = @ptrCast(c_name.?) }) catch {
|
||||
return 0;
|
||||
};
|
||||
|
||||
if (std.mem.startsWith(u8, property, "__")) {
|
||||
// some frameworks will extend built-in types using a __ prefix
|
||||
// these should always be safe to ignore.
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (std.mem.startsWith(u8, property, "jQuery")) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (JsApi == @import("../webapi/cdata/Text.zig").JsApi or JsApi == @import("../webapi/cdata/Comment.zig").JsApi) {
|
||||
if (std.mem.eql(u8, property, "tagName")) {
|
||||
// knockout does this, a lot.
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (JsApi == @import("../webapi/element/Html.zig").JsApi or JsApi == @import("../webapi/Element.zig").JsApi or JsApi == @import("../webapi/element/html/Custom.zig").JsApi) {
|
||||
// react ?
|
||||
if (std.mem.eql(u8, property, "props")) return 0;
|
||||
if (std.mem.eql(u8, property, "hydrated")) return 0;
|
||||
if (std.mem.eql(u8, property, "isHydrated")) return 0;
|
||||
}
|
||||
|
||||
if (JsApi == @import("../webapi/Console.zig").JsApi) {
|
||||
if (std.mem.eql(u8, property, "firebug")) return 0;
|
||||
}
|
||||
|
||||
const ignored = std.StaticStringMap(void).initComptime(.{});
|
||||
if (!ignored.has(property)) {
|
||||
const key = std.fmt.bufPrint(&local.ctx.page.buf, "{s}:{s}", .{ if (@hasDecl(JsApi.Meta, "name")) JsApi.Meta.name else @typeName(JsApi), property }) catch return 0;
|
||||
logUnknownProperty(local, key) catch return 0;
|
||||
}
|
||||
// not intercepted
|
||||
return 0;
|
||||
}
|
||||
}.wrap;
|
||||
}
|
||||
|
||||
fn logUnknownProperty(local: *const js.Local, key: []const u8) !void {
|
||||
const ctx = local.ctx;
|
||||
const gop = try ctx.unknown_properties.getOrPut(ctx.arena, key);
|
||||
if (gop.found_existing) {
|
||||
gop.value_ptr.count += 1;
|
||||
} else {
|
||||
gop.key_ptr.* = try ctx.arena.dupe(u8, key);
|
||||
gop.value_ptr.* = .{
|
||||
.count = 1,
|
||||
.first_stack = try ctx.arena.dupe(u8, (try local.stackTrace()) orelse "???"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Given a Type, returns the length of the prototype chain, including self
|
||||
fn prototypeChainLength(comptime T: type) usize {
|
||||
var l: usize = 1;
|
||||
@@ -631,6 +730,7 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/css/CSSStyleRule.zig"),
|
||||
@import("../webapi/css/CSSStyleSheet.zig"),
|
||||
@import("../webapi/css/CSSStyleProperties.zig"),
|
||||
@import("../webapi/css/FontFaceSet.zig"),
|
||||
@import("../webapi/css/MediaQueryList.zig"),
|
||||
@import("../webapi/css/StyleSheetList.zig"),
|
||||
@import("../webapi/Document.zig"),
|
||||
@@ -667,8 +767,10 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/element/html/Custom.zig"),
|
||||
@import("../webapi/element/html/Data.zig"),
|
||||
@import("../webapi/element/html/DataList.zig"),
|
||||
@import("../webapi/element/html/Details.zig"),
|
||||
@import("../webapi/element/html/Dialog.zig"),
|
||||
@import("../webapi/element/html/Directory.zig"),
|
||||
@import("../webapi/element/html/DList.zig"),
|
||||
@import("../webapi/element/html/Div.zig"),
|
||||
@import("../webapi/element/html/Embed.zig"),
|
||||
@import("../webapi/element/html/FieldSet.zig"),
|
||||
@@ -696,6 +798,7 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/element/html/Option.zig"),
|
||||
@import("../webapi/element/html/Output.zig"),
|
||||
@import("../webapi/element/html/Paragraph.zig"),
|
||||
@import("../webapi/element/html/Picture.zig"),
|
||||
@import("../webapi/element/html/Param.zig"),
|
||||
@import("../webapi/element/html/Pre.zig"),
|
||||
@import("../webapi/element/html/Progress.zig"),
|
||||
@@ -724,6 +827,8 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/element/svg/Generic.zig"),
|
||||
@import("../webapi/encoding/TextDecoder.zig"),
|
||||
@import("../webapi/encoding/TextEncoder.zig"),
|
||||
@import("../webapi/encoding/TextEncoderStream.zig"),
|
||||
@import("../webapi/encoding/TextDecoderStream.zig"),
|
||||
@import("../webapi/Event.zig"),
|
||||
@import("../webapi/event/CompositionEvent.zig"),
|
||||
@import("../webapi/event/CustomEvent.zig"),
|
||||
@@ -737,6 +842,10 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/event/MouseEvent.zig"),
|
||||
@import("../webapi/event/PointerEvent.zig"),
|
||||
@import("../webapi/event/KeyboardEvent.zig"),
|
||||
@import("../webapi/event/FocusEvent.zig"),
|
||||
@import("../webapi/event/WheelEvent.zig"),
|
||||
@import("../webapi/event/TextEvent.zig"),
|
||||
@import("../webapi/event/PromiseRejectionEvent.zig"),
|
||||
@import("../webapi/MessageChannel.zig"),
|
||||
@import("../webapi/MessagePort.zig"),
|
||||
@import("../webapi/media/MediaError.zig"),
|
||||
@@ -756,11 +865,16 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/streams/ReadableStream.zig"),
|
||||
@import("../webapi/streams/ReadableStreamDefaultReader.zig"),
|
||||
@import("../webapi/streams/ReadableStreamDefaultController.zig"),
|
||||
@import("../webapi/streams/WritableStream.zig"),
|
||||
@import("../webapi/streams/WritableStreamDefaultWriter.zig"),
|
||||
@import("../webapi/streams/WritableStreamDefaultController.zig"),
|
||||
@import("../webapi/streams/TransformStream.zig"),
|
||||
@import("../webapi/Node.zig"),
|
||||
@import("../webapi/storage/storage.zig"),
|
||||
@import("../webapi/URL.zig"),
|
||||
@import("../webapi/Window.zig"),
|
||||
@import("../webapi/Performance.zig"),
|
||||
@import("../webapi/PluginArray.zig"),
|
||||
@import("../webapi/MutationObserver.zig"),
|
||||
@import("../webapi/IntersectionObserver.zig"),
|
||||
@import("../webapi/CustomElementRegistry.zig"),
|
||||
@@ -768,14 +882,18 @@ pub const JsApis = flattenTypes(&.{
|
||||
@import("../webapi/IdleDeadline.zig"),
|
||||
@import("../webapi/Blob.zig"),
|
||||
@import("../webapi/File.zig"),
|
||||
@import("../webapi/FileReader.zig"),
|
||||
@import("../webapi/Screen.zig"),
|
||||
@import("../webapi/VisualViewport.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"),
|
||||
@import("../webapi/canvas/CanvasRenderingContext2D.zig"),
|
||||
@import("../webapi/canvas/WebGLRenderingContext.zig"),
|
||||
@import("../webapi/canvas/OffscreenCanvas.zig"),
|
||||
@import("../webapi/canvas/OffscreenCanvasRenderingContext2D.zig"),
|
||||
@import("../webapi/SubtleCrypto.zig"),
|
||||
@import("../webapi/Selection.zig"),
|
||||
@import("../webapi/ImageData.zig"),
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
@@ -19,12 +19,10 @@
|
||||
const std = @import("std");
|
||||
pub const v8 = @import("v8").c;
|
||||
|
||||
const log = @import("../../log.zig");
|
||||
const string = @import("../../string.zig");
|
||||
|
||||
pub const Env = @import("Env.zig");
|
||||
pub const bridge = @import("bridge.zig");
|
||||
pub const ExecutionWorld = @import("ExecutionWorld.zig");
|
||||
pub const Caller = @import("Caller.zig");
|
||||
pub const Context = @import("Context.zig");
|
||||
pub const Local = @import("Local.zig");
|
||||
@@ -34,7 +32,6 @@ pub const Platform = @import("Platform.zig");
|
||||
pub const Isolate = @import("Isolate.zig");
|
||||
pub const HandleScope = @import("HandleScope.zig");
|
||||
|
||||
pub const Name = @import("Name.zig");
|
||||
pub const Value = @import("Value.zig");
|
||||
pub const Array = @import("Array.zig");
|
||||
pub const String = @import("String.zig");
|
||||
@@ -47,6 +44,7 @@ pub const BigInt = @import("BigInt.zig");
|
||||
pub const Number = @import("Number.zig");
|
||||
pub const Integer = @import("Integer.zig");
|
||||
pub const PromiseResolver = @import("PromiseResolver.zig");
|
||||
pub const PromiseRejection = @import("PromiseRejection.zig");
|
||||
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
@@ -79,6 +77,107 @@ pub const ArrayBuffer = struct {
|
||||
}
|
||||
};
|
||||
|
||||
pub const ArrayType = enum(u8) {
|
||||
int8,
|
||||
uint8,
|
||||
uint8_clamped,
|
||||
int16,
|
||||
uint16,
|
||||
int32,
|
||||
uint32,
|
||||
float16,
|
||||
float32,
|
||||
float64,
|
||||
};
|
||||
|
||||
pub fn ArrayBufferRef(comptime kind: ArrayType) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
const BackingInt = switch (kind) {
|
||||
.int8 => i8,
|
||||
.uint8, .uint8_clamped => u8,
|
||||
.int16 => i16,
|
||||
.uint16 => u16,
|
||||
.int32 => i32,
|
||||
.uint32 => u32,
|
||||
.float16 => f16,
|
||||
.float32 => f32,
|
||||
.float64 => f64,
|
||||
};
|
||||
|
||||
local: *const Local,
|
||||
handle: *const v8.Value,
|
||||
|
||||
/// Persisted typed array.
|
||||
pub const Global = struct {
|
||||
handle: v8.Global,
|
||||
|
||||
pub fn deinit(self: *Global) void {
|
||||
v8.v8__Global__Reset(&self.handle);
|
||||
}
|
||||
|
||||
pub fn local(self: *const Global, l: *const Local) Self {
|
||||
return .{ .local = l, .handle = v8.v8__Global__Get(&self.handle, l.isolate.handle).? };
|
||||
}
|
||||
};
|
||||
|
||||
pub fn init(local: *const Local, size: usize) Self {
|
||||
const ctx = local.ctx;
|
||||
const isolate = ctx.isolate;
|
||||
const bits = switch (@typeInfo(BackingInt)) {
|
||||
.int => |n| n.bits,
|
||||
.float => |f| f.bits,
|
||||
else => unreachable,
|
||||
};
|
||||
|
||||
var array_buffer: *const v8.ArrayBuffer = undefined;
|
||||
if (size == 0) {
|
||||
array_buffer = v8.v8__ArrayBuffer__New(isolate.handle, 0).?;
|
||||
} else {
|
||||
const buffer_len = size * bits / 8;
|
||||
const backing_store = v8.v8__ArrayBuffer__NewBackingStore(isolate.handle, buffer_len).?;
|
||||
const backing_store_ptr = v8.v8__BackingStore__TO_SHARED_PTR(backing_store);
|
||||
array_buffer = v8.v8__ArrayBuffer__New2(isolate.handle, &backing_store_ptr).?;
|
||||
}
|
||||
|
||||
const handle: *const v8.Value = switch (comptime kind) {
|
||||
.int8 => @ptrCast(v8.v8__Int8Array__New(array_buffer, 0, size).?),
|
||||
.uint8 => @ptrCast(v8.v8__Uint8Array__New(array_buffer, 0, size).?),
|
||||
.uint8_clamped => @ptrCast(v8.v8__Uint8ClampedArray__New(array_buffer, 0, size).?),
|
||||
.int16 => @ptrCast(v8.v8__Int16Array__New(array_buffer, 0, size).?),
|
||||
.uint16 => @ptrCast(v8.v8__Uint16Array__New(array_buffer, 0, size).?),
|
||||
.int32 => @ptrCast(v8.v8__Int32Array__New(array_buffer, 0, size).?),
|
||||
.uint32 => @ptrCast(v8.v8__Uint32Array__New(array_buffer, 0, size).?),
|
||||
.float16 => @ptrCast(v8.v8__Float16Array__New(array_buffer, 0, size).?),
|
||||
.float32 => @ptrCast(v8.v8__Float32Array__New(array_buffer, 0, size).?),
|
||||
.float64 => @ptrCast(v8.v8__Float64Array__New(array_buffer, 0, size).?),
|
||||
};
|
||||
|
||||
return .{ .local = local, .handle = handle };
|
||||
}
|
||||
|
||||
pub fn persist(self: *const Self) !Global {
|
||||
var ctx = self.local.ctx;
|
||||
var global: v8.Global = undefined;
|
||||
v8.v8__Global__New(ctx.isolate.handle, self.handle, &global);
|
||||
try ctx.global_values.append(ctx.arena, global);
|
||||
|
||||
return .{ .handle = global };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// If a WebAPI takes a []const u8, then we'll coerce any JS value to that string
|
||||
// so null -> "null". But if a WebAPI takes an optional string, ?[]const u8,
|
||||
// how should we handle null? If the parameter _isn't_ passed, then it's obvious
|
||||
// that it should be null, but what if `null` is passed? It's ambiguous, should
|
||||
// that be null, or "null"? It could depend on the api. So, `null` passed to
|
||||
// ?[]const u8 will be `null`. If you want it to be "null", use a `.js.NullableString`.
|
||||
pub const NullableString = struct {
|
||||
value: []const u8,
|
||||
};
|
||||
|
||||
pub const Exception = struct {
|
||||
local: *const Local,
|
||||
handle: *const v8.Value,
|
||||
@@ -136,8 +235,10 @@ pub fn simpleZigValueToJs(isolate: Isolate, value: anytype, comptime fail: bool,
|
||||
const values = value.values;
|
||||
const len = values.len;
|
||||
const backing_store = v8.v8__ArrayBuffer__NewBackingStore(isolate.handle, len);
|
||||
const data: [*]u8 = @ptrCast(@alignCast(v8.v8__BackingStore__Data(backing_store)));
|
||||
@memcpy(data[0..len], @as([]const u8, @ptrCast(values))[0..len]);
|
||||
if (len > 0) {
|
||||
const data: [*]u8 = @ptrCast(@alignCast(v8.v8__BackingStore__Data(backing_store)));
|
||||
@memcpy(data[0..len], @as([]const u8, @ptrCast(values))[0..len]);
|
||||
}
|
||||
const backing_store_ptr = v8.v8__BackingStore__TO_SHARED_PTR(backing_store);
|
||||
return @ptrCast(v8.v8__ArrayBuffer__New2(isolate.handle, &backing_store_ptr).?);
|
||||
},
|
||||
|
||||
607
src/browser/markdown.zig
Normal file
607
src/browser/markdown.zig
Normal file
@@ -0,0 +1,607 @@
|
||||
// Copyright (C) 2023-2026 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 Page = @import("Page.zig");
|
||||
const CData = @import("webapi/CData.zig");
|
||||
const Element = @import("webapi/Element.zig");
|
||||
const Node = @import("webapi/Node.zig");
|
||||
|
||||
pub const Opts = struct {
|
||||
// Options for future customization (e.g., dialect)
|
||||
};
|
||||
|
||||
const State = struct {
|
||||
const ListType = enum { ordered, unordered };
|
||||
const ListState = struct {
|
||||
type: ListType,
|
||||
index: usize,
|
||||
};
|
||||
|
||||
list_depth: usize = 0,
|
||||
list_stack: [32]ListState = undefined,
|
||||
pre_node: ?*Node = null,
|
||||
in_code: bool = false,
|
||||
in_table: bool = false,
|
||||
table_row_index: usize = 0,
|
||||
table_col_count: usize = 0,
|
||||
last_char_was_newline: bool = true,
|
||||
};
|
||||
|
||||
fn isBlock(tag: Element.Tag) bool {
|
||||
return switch (tag) {
|
||||
.p, .div, .section, .article, .main, .header, .footer, .nav, .aside, .h1, .h2, .h3, .h4, .h5, .h6, .ul, .ol, .blockquote, .pre, .table, .hr => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn shouldAddSpacing(tag: Element.Tag) bool {
|
||||
return switch (tag) {
|
||||
.p, .h1, .h2, .h3, .h4, .h5, .h6, .blockquote, .pre, .table => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn isLayoutBlock(tag: Element.Tag) bool {
|
||||
return switch (tag) {
|
||||
.main, .section, .article, .nav, .aside, .header, .footer, .div, .ul, .ol => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
fn isStandaloneAnchor(el: *Element) bool {
|
||||
const node = el.asNode();
|
||||
const parent = node.parentNode() orelse return false;
|
||||
const parent_el = parent.is(Element) orelse return false;
|
||||
|
||||
if (!isLayoutBlock(parent_el.getTag())) return false;
|
||||
|
||||
var prev = node.previousSibling();
|
||||
while (prev) |p| : (prev = p.previousSibling()) {
|
||||
if (isSignificantText(p)) return false;
|
||||
if (p.is(Element)) |pe| {
|
||||
if (isVisibleElement(pe)) break;
|
||||
}
|
||||
}
|
||||
|
||||
var next = node.nextSibling();
|
||||
while (next) |n| : (next = n.nextSibling()) {
|
||||
if (isSignificantText(n)) return false;
|
||||
if (n.is(Element)) |ne| {
|
||||
if (isVisibleElement(ne)) break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
fn isSignificantText(node: *Node) bool {
|
||||
const text = node.is(Node.CData.Text) orelse return false;
|
||||
return !isAllWhitespace(text.getWholeText());
|
||||
}
|
||||
|
||||
fn isVisibleElement(el: *Element) bool {
|
||||
return switch (el.getTag()) {
|
||||
.script, .style, .noscript, .template, .head, .meta, .link, .title, .svg => false,
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
|
||||
fn isAllWhitespace(text: []const u8) bool {
|
||||
return for (text) |c| {
|
||||
if (!std.ascii.isWhitespace(c)) break false;
|
||||
} else true;
|
||||
}
|
||||
|
||||
fn hasBlockDescendant(node: *Node) bool {
|
||||
var it = node.childrenIterator();
|
||||
return while (it.next()) |child| {
|
||||
if (child.is(Element)) |el| {
|
||||
if (isBlock(el.getTag())) break true;
|
||||
if (hasBlockDescendant(child)) break true;
|
||||
}
|
||||
} else false;
|
||||
}
|
||||
|
||||
fn ensureNewline(state: *State, writer: *std.Io.Writer) !void {
|
||||
if (!state.last_char_was_newline) {
|
||||
try writer.writeByte('\n');
|
||||
state.last_char_was_newline = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dump(node: *Node, opts: Opts, writer: *std.Io.Writer, page: *Page) !void {
|
||||
_ = opts;
|
||||
var state = State{};
|
||||
try render(node, &state, writer, page);
|
||||
if (!state.last_char_was_newline) {
|
||||
try writer.writeByte('\n');
|
||||
}
|
||||
}
|
||||
|
||||
fn render(node: *Node, state: *State, writer: *std.Io.Writer, page: *Page) error{WriteFailed}!void {
|
||||
switch (node._type) {
|
||||
.document, .document_fragment => {
|
||||
try renderChildren(node, state, writer, page);
|
||||
},
|
||||
.element => |el| {
|
||||
try renderElement(el, state, writer, page);
|
||||
},
|
||||
.cdata => |cd| {
|
||||
if (node.is(Node.CData.Text)) |_| {
|
||||
var text = cd.getData().str();
|
||||
if (state.pre_node) |pre| {
|
||||
if (node.parentNode() == pre and node.nextSibling() == null) {
|
||||
text = std.mem.trimRight(u8, text, " \t\r\n");
|
||||
}
|
||||
}
|
||||
try renderText(text, state, writer);
|
||||
}
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
fn renderChildren(parent: *Node, state: *State, writer: *std.Io.Writer, page: *Page) !void {
|
||||
var it = parent.childrenIterator();
|
||||
while (it.next()) |child| {
|
||||
try render(child, state, writer, page);
|
||||
}
|
||||
}
|
||||
|
||||
fn renderElement(el: *Element, state: *State, writer: *std.Io.Writer, page: *Page) !void {
|
||||
const tag = el.getTag();
|
||||
|
||||
if (!isVisibleElement(el)) return;
|
||||
|
||||
// --- Opening Tag Logic ---
|
||||
|
||||
// Ensure block elements start on a new line (double newline for paragraphs etc)
|
||||
if (isBlock(tag) and !state.in_table) {
|
||||
try ensureNewline(state, writer);
|
||||
if (shouldAddSpacing(tag)) {
|
||||
try writer.writeByte('\n');
|
||||
}
|
||||
} else if (tag == .li or tag == .tr) {
|
||||
try ensureNewline(state, writer);
|
||||
}
|
||||
|
||||
// Prefixes
|
||||
switch (tag) {
|
||||
.h1 => try writer.writeAll("# "),
|
||||
.h2 => try writer.writeAll("## "),
|
||||
.h3 => try writer.writeAll("### "),
|
||||
.h4 => try writer.writeAll("#### "),
|
||||
.h5 => try writer.writeAll("##### "),
|
||||
.h6 => try writer.writeAll("###### "),
|
||||
.ul => {
|
||||
if (state.list_depth < state.list_stack.len) {
|
||||
state.list_stack[state.list_depth] = .{ .type = .unordered, .index = 0 };
|
||||
state.list_depth += 1;
|
||||
}
|
||||
},
|
||||
.ol => {
|
||||
if (state.list_depth < state.list_stack.len) {
|
||||
state.list_stack[state.list_depth] = .{ .type = .ordered, .index = 1 };
|
||||
state.list_depth += 1;
|
||||
}
|
||||
},
|
||||
.li => {
|
||||
const indent = if (state.list_depth > 0) state.list_depth - 1 else 0;
|
||||
for (0..indent) |_| try writer.writeAll(" ");
|
||||
|
||||
if (state.list_depth > 0 and state.list_stack[state.list_depth - 1].type == .ordered) {
|
||||
const current_list = &state.list_stack[state.list_depth - 1];
|
||||
try writer.print("{d}. ", .{current_list.index});
|
||||
current_list.index += 1;
|
||||
} else {
|
||||
try writer.writeAll("- ");
|
||||
}
|
||||
state.last_char_was_newline = false;
|
||||
},
|
||||
.table => {
|
||||
state.in_table = true;
|
||||
state.table_row_index = 0;
|
||||
state.table_col_count = 0;
|
||||
},
|
||||
.tr => {
|
||||
state.table_col_count = 0;
|
||||
try writer.writeByte('|');
|
||||
},
|
||||
.td, .th => {
|
||||
// Note: leading pipe handled by previous cell closing or tr opening
|
||||
state.last_char_was_newline = false;
|
||||
try writer.writeByte(' ');
|
||||
},
|
||||
.blockquote => {
|
||||
try writer.writeAll("> ");
|
||||
state.last_char_was_newline = false;
|
||||
},
|
||||
.pre => {
|
||||
try writer.writeAll("```\n");
|
||||
state.pre_node = el.asNode();
|
||||
state.last_char_was_newline = true;
|
||||
},
|
||||
.code => {
|
||||
if (state.pre_node == null) {
|
||||
try writer.writeByte('`');
|
||||
state.in_code = true;
|
||||
state.last_char_was_newline = false;
|
||||
}
|
||||
},
|
||||
.b, .strong => {
|
||||
try writer.writeAll("**");
|
||||
state.last_char_was_newline = false;
|
||||
},
|
||||
.i, .em => {
|
||||
try writer.writeAll("*");
|
||||
state.last_char_was_newline = false;
|
||||
},
|
||||
.s, .del => {
|
||||
try writer.writeAll("~~");
|
||||
state.last_char_was_newline = false;
|
||||
},
|
||||
.hr => {
|
||||
try writer.writeAll("---\n");
|
||||
state.last_char_was_newline = true;
|
||||
return;
|
||||
},
|
||||
.br => {
|
||||
if (state.in_table) {
|
||||
try writer.writeByte(' ');
|
||||
} else {
|
||||
try writer.writeByte('\n');
|
||||
state.last_char_was_newline = true;
|
||||
}
|
||||
return;
|
||||
},
|
||||
.img => {
|
||||
try writer.writeAll(";
|
||||
if (el.getAttributeSafe(comptime .wrap("src"))) |src| {
|
||||
try writer.writeAll(src);
|
||||
}
|
||||
try writer.writeAll(")");
|
||||
state.last_char_was_newline = false;
|
||||
return;
|
||||
},
|
||||
.anchor => {
|
||||
const has_block = hasBlockDescendant(el.asNode());
|
||||
if (has_block) {
|
||||
try renderChildren(el.asNode(), state, writer, page);
|
||||
if (el.getAttributeSafe(comptime .wrap("href"))) |href| {
|
||||
if (!state.last_char_was_newline) try writer.writeByte('\n');
|
||||
try writer.writeAll("([Link](");
|
||||
try writer.writeAll(href);
|
||||
try writer.writeAll("))\n");
|
||||
state.last_char_was_newline = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isStandaloneAnchor(el)) {
|
||||
if (!state.last_char_was_newline) try writer.writeByte('\n');
|
||||
try writer.writeByte('[');
|
||||
try renderChildren(el.asNode(), state, writer, page);
|
||||
try writer.writeAll("](");
|
||||
if (el.getAttributeSafe(comptime .wrap("href"))) |href| {
|
||||
try writer.writeAll(href);
|
||||
}
|
||||
try writer.writeAll(")\n");
|
||||
state.last_char_was_newline = true;
|
||||
return;
|
||||
}
|
||||
|
||||
try writer.writeByte('[');
|
||||
try renderChildren(el.asNode(), state, writer, page);
|
||||
try writer.writeAll("](");
|
||||
if (el.getAttributeSafe(comptime .wrap("href"))) |href| {
|
||||
try writer.writeAll(href);
|
||||
}
|
||||
try writer.writeByte(')');
|
||||
state.last_char_was_newline = false;
|
||||
return;
|
||||
},
|
||||
.input => {
|
||||
const type_attr = el.getAttributeSafe(comptime .wrap("type")) orelse return;
|
||||
if (std.ascii.eqlIgnoreCase(type_attr, "checkbox")) {
|
||||
const checked = el.getAttributeSafe(comptime .wrap("checked")) != null;
|
||||
try writer.writeAll(if (checked) "[x] " else "[ ] ");
|
||||
state.last_char_was_newline = false;
|
||||
}
|
||||
return;
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
|
||||
// --- Render Children ---
|
||||
try renderChildren(el.asNode(), state, writer, page);
|
||||
|
||||
// --- Closing Tag Logic ---
|
||||
|
||||
// Suffixes
|
||||
switch (tag) {
|
||||
.pre => {
|
||||
if (!state.last_char_was_newline) {
|
||||
try writer.writeByte('\n');
|
||||
}
|
||||
try writer.writeAll("```\n");
|
||||
state.pre_node = null;
|
||||
state.last_char_was_newline = true;
|
||||
},
|
||||
.code => {
|
||||
if (state.pre_node == null) {
|
||||
try writer.writeByte('`');
|
||||
state.in_code = false;
|
||||
state.last_char_was_newline = false;
|
||||
}
|
||||
},
|
||||
.b, .strong => {
|
||||
try writer.writeAll("**");
|
||||
state.last_char_was_newline = false;
|
||||
},
|
||||
.i, .em => {
|
||||
try writer.writeAll("*");
|
||||
state.last_char_was_newline = false;
|
||||
},
|
||||
.s, .del => {
|
||||
try writer.writeAll("~~");
|
||||
state.last_char_was_newline = false;
|
||||
},
|
||||
.blockquote => {},
|
||||
.ul, .ol => {
|
||||
if (state.list_depth > 0) state.list_depth -= 1;
|
||||
},
|
||||
.table => {
|
||||
state.in_table = false;
|
||||
},
|
||||
.tr => {
|
||||
try writer.writeByte('\n');
|
||||
if (state.table_row_index == 0) {
|
||||
try writer.writeByte('|');
|
||||
for (0..state.table_col_count) |_| {
|
||||
try writer.writeAll("---|");
|
||||
}
|
||||
try writer.writeByte('\n');
|
||||
}
|
||||
state.table_row_index += 1;
|
||||
state.last_char_was_newline = true;
|
||||
},
|
||||
.td, .th => {
|
||||
try writer.writeAll(" |");
|
||||
state.table_col_count += 1;
|
||||
state.last_char_was_newline = false;
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
|
||||
// Post-block newlines
|
||||
if (isBlock(tag) and !state.in_table) {
|
||||
try ensureNewline(state, writer);
|
||||
}
|
||||
}
|
||||
|
||||
fn renderText(text: []const u8, state: *State, writer: *std.Io.Writer) !void {
|
||||
if (text.len == 0) return;
|
||||
|
||||
if (state.pre_node) |_| {
|
||||
try writer.writeAll(text);
|
||||
state.last_char_was_newline = text[text.len - 1] == '\n';
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for pure whitespace
|
||||
if (isAllWhitespace(text)) {
|
||||
if (!state.last_char_was_newline) {
|
||||
try writer.writeByte(' ');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Collapse whitespace
|
||||
var it = std.mem.tokenizeAny(u8, text, " \t\n\r");
|
||||
var first = true;
|
||||
while (it.next()) |word| {
|
||||
if (!first or (!state.last_char_was_newline and std.ascii.isWhitespace(text[0]))) {
|
||||
try writer.writeByte(' ');
|
||||
}
|
||||
|
||||
try escapeMarkdown(writer, word);
|
||||
state.last_char_was_newline = false;
|
||||
first = false;
|
||||
}
|
||||
|
||||
// Handle trailing whitespace from the original text
|
||||
if (!first and !state.last_char_was_newline and std.ascii.isWhitespace(text[text.len - 1])) {
|
||||
try writer.writeByte(' ');
|
||||
}
|
||||
}
|
||||
|
||||
fn escapeMarkdown(writer: *std.Io.Writer, text: []const u8) !void {
|
||||
for (text) |c| {
|
||||
switch (c) {
|
||||
'\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '#', '+', '-', '!', '|' => {
|
||||
try writer.writeByte('\\');
|
||||
try writer.writeByte(c);
|
||||
},
|
||||
else => try writer.writeByte(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn testMarkdownHTML(html: []const u8, expected: []const u8) !void {
|
||||
const testing = @import("../testing.zig");
|
||||
const page = try testing.test_session.createPage();
|
||||
defer testing.test_session.removePage();
|
||||
const doc = page.window._document;
|
||||
|
||||
const div = try doc.createElement("div", null, page);
|
||||
try page.parseHtmlAsChildren(div.asNode(), html);
|
||||
|
||||
var aw: std.Io.Writer.Allocating = .init(testing.allocator);
|
||||
defer aw.deinit();
|
||||
try dump(div.asNode(), .{}, &aw.writer, page);
|
||||
|
||||
try testing.expectString(expected, aw.written());
|
||||
}
|
||||
|
||||
test "browser.markdown: basic" {
|
||||
try testMarkdownHTML("Hello world", "Hello world\n");
|
||||
}
|
||||
|
||||
test "browser.markdown: whitespace" {
|
||||
try testMarkdownHTML("<span>A</span> <span>B</span>", "A B\n");
|
||||
}
|
||||
|
||||
test "browser.markdown: escaping" {
|
||||
try testMarkdownHTML("<p># Not a header</p>", "\n\\# Not a header\n");
|
||||
}
|
||||
|
||||
test "browser.markdown: strikethrough" {
|
||||
try testMarkdownHTML("<s>deleted</s>", "~~deleted~~\n");
|
||||
}
|
||||
|
||||
test "browser.markdown: task list" {
|
||||
try testMarkdownHTML(
|
||||
\\<input type="checkbox" checked><input type="checkbox">
|
||||
, "[x] [ ] \n");
|
||||
}
|
||||
|
||||
test "browser.markdown: ordered list" {
|
||||
try testMarkdownHTML(
|
||||
\\<ol><li>First</li><li>Second</li></ol>
|
||||
, "1. First\n2. Second\n");
|
||||
}
|
||||
|
||||
test "browser.markdown: table" {
|
||||
try testMarkdownHTML(
|
||||
\\<table><thead><tr><th>Head 1</th><th>Head 2</th></tr></thead>
|
||||
\\<tbody><tr><td>Cell 1</td><td>Cell 2</td></tr></tbody></table>
|
||||
,
|
||||
\\
|
||||
\\| Head 1 | Head 2 |
|
||||
\\|---|---|
|
||||
\\| Cell 1 | Cell 2 |
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: nested lists" {
|
||||
try testMarkdownHTML(
|
||||
\\<ul><li>Parent<ul><li>Child</li></ul></li></ul>
|
||||
,
|
||||
\\- Parent
|
||||
\\ - Child
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: blockquote" {
|
||||
try testMarkdownHTML("<blockquote>Hello world</blockquote>", "\n> Hello world\n");
|
||||
}
|
||||
|
||||
test "browser.markdown: links" {
|
||||
try testMarkdownHTML("<a href=\"https://lightpanda.io\">Lightpanda</a>", "[Lightpanda](https://lightpanda.io)\n");
|
||||
}
|
||||
|
||||
test "browser.markdown: images" {
|
||||
try testMarkdownHTML("<img src=\"logo.png\" alt=\"Logo\">", "\n");
|
||||
}
|
||||
|
||||
test "browser.markdown: headings" {
|
||||
try testMarkdownHTML("<h1>Title</h1><h2>Subtitle</h2>",
|
||||
\\
|
||||
\\# Title
|
||||
\\
|
||||
\\## Subtitle
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: code" {
|
||||
try testMarkdownHTML(
|
||||
\\<p>Use git push</p>
|
||||
\\<pre><code>line 1
|
||||
\\line 2</code></pre>
|
||||
,
|
||||
\\
|
||||
\\Use git push
|
||||
\\
|
||||
\\```
|
||||
\\line 1
|
||||
\\line 2
|
||||
\\```
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: block link" {
|
||||
try testMarkdownHTML(
|
||||
\\<a href="https://example.com">
|
||||
\\ <h3>Title</h3>
|
||||
\\ <p>Description</p>
|
||||
\\</a>
|
||||
,
|
||||
\\
|
||||
\\### Title
|
||||
\\
|
||||
\\Description
|
||||
\\([Link](https://example.com))
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: inline link" {
|
||||
try testMarkdownHTML(
|
||||
\\<p>Visit <a href="https://example.com">Example</a>.</p>
|
||||
,
|
||||
\\
|
||||
\\Visit [Example](https://example.com).
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: standalone anchors" {
|
||||
// Inside main, with whitespace between anchors -> treated as blocks
|
||||
try testMarkdownHTML(
|
||||
\\<main>
|
||||
\\ <a href="1">Link 1</a>
|
||||
\\ <a href="2">Link 2</a>
|
||||
\\</main>
|
||||
,
|
||||
\\[Link 1](1)
|
||||
\\[Link 2](2)
|
||||
\\
|
||||
);
|
||||
}
|
||||
|
||||
test "browser.markdown: mixed anchors in main" {
|
||||
// Anchors surrounded by text should remain inline
|
||||
try testMarkdownHTML(
|
||||
\\<main>
|
||||
\\ Welcome <a href="1">Link 1</a>.
|
||||
\\</main>
|
||||
,
|
||||
\\Welcome [Link 1](1).
|
||||
\\
|
||||
);
|
||||
}
|
||||
@@ -421,7 +421,16 @@ fn appendBeforeSiblingCallback(ctx: *anyopaque, sibling_ref: *anyopaque, node_or
|
||||
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),
|
||||
.node => |cpn| blk: {
|
||||
const child = getNode(cpn);
|
||||
if (child._parent) |previous_parent| {
|
||||
// A custom element constructor may have inserted the node into the
|
||||
// DOM before the parser officially places it (e.g. via foster
|
||||
// parenting). Detach it first so insertNodeRelative's assertion holds.
|
||||
self.page.removeNode(previous_parent, child, .{ .will_be_reconnected = parent.isConnected() });
|
||||
}
|
||||
break :blk child;
|
||||
},
|
||||
.text => |txt| try self.page.createTextNode(txt),
|
||||
};
|
||||
try self.page.insertNodeRelative(parent, node, .{ .before = sibling }, .{});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
|
||||
//
|
||||
// Francis Bouvier <francis@lightpanda.io>
|
||||
// Pierre Tachoire <pierre@lightpanda.io>
|
||||
@@ -16,8 +16,6 @@
|
||||
// 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 {
|
||||
@@ -28,37 +26,3 @@ pub fn Struct(comptime T: type) type {
|
||||
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,
|
||||
} });
|
||||
}
|
||||
|
||||
@@ -3,13 +3,67 @@
|
||||
|
||||
<script id=animation>
|
||||
let a1 = document.createElement('div').animate(null, null);
|
||||
testing.expectEqual('finished', a1.playState);
|
||||
testing.expectEqual('idle', a1.playState);
|
||||
|
||||
let cb = [];
|
||||
a1.ready.then(() => { cb.push('ready') });
|
||||
a1.finished.then((x) => {
|
||||
cb.push('finished');
|
||||
cb.push(a1.playState);
|
||||
cb.push(x == a1);
|
||||
});
|
||||
testing.eventually(() => testing.expectEqual(['finished', true], cb));
|
||||
a1.ready.then(() => {
|
||||
cb.push(a1.playState);
|
||||
a1.play();
|
||||
cb.push(a1.playState);
|
||||
});
|
||||
testing.eventually(() => testing.expectEqual(['idle', 'running', 'finished', true], cb));
|
||||
</script>
|
||||
|
||||
<script id=startTime>
|
||||
let a2 = document.createElement('div').animate(null, null);
|
||||
// startTime defaults to null
|
||||
testing.expectEqual(null, a2.startTime);
|
||||
// startTime is settable
|
||||
a2.startTime = 42.5;
|
||||
testing.expectEqual(42.5, a2.startTime);
|
||||
// startTime can be reset to null
|
||||
a2.startTime = null;
|
||||
testing.expectEqual(null, a2.startTime);
|
||||
</script>
|
||||
|
||||
<script id=onfinish>
|
||||
let a3 = document.createElement('div').animate(null, null);
|
||||
// onfinish defaults to null
|
||||
testing.expectEqual(null, a3.onfinish);
|
||||
|
||||
let calls = [];
|
||||
// onfinish callback should be scheduled and called asynchronously
|
||||
a3.onfinish = function() { calls.push('finish'); };
|
||||
a3.play();
|
||||
testing.eventually(() => testing.expectEqual(['finish'], calls));
|
||||
</script>
|
||||
|
||||
<script id=pause>
|
||||
let a4 = document.createElement('div').animate(null, null);
|
||||
let cb4 = [];
|
||||
a4.finished.then((x) => { cb4.push(a4.playState) });
|
||||
a4.ready.then(() => {
|
||||
a4.play();
|
||||
cb4.push(a4.playState)
|
||||
a4.pause();
|
||||
cb4.push(a4.playState)
|
||||
});
|
||||
testing.eventually(() => testing.expectEqual(['running', 'paused'], cb4));
|
||||
</script>
|
||||
|
||||
<script id=finish>
|
||||
let a5 = document.createElement('div').animate(null, null);
|
||||
testing.expectEqual('idle', a5.playState);
|
||||
|
||||
let cb5 = [];
|
||||
a5.finished.then((x) => { cb5.push(a5.playState) });
|
||||
a5.ready.then(() => {
|
||||
cb5.push(a5.playState);
|
||||
a5.play();
|
||||
});
|
||||
testing.eventually(() => testing.expectEqual(['idle', 'finished'], cb5));
|
||||
</script>
|
||||
|
||||
@@ -33,3 +33,70 @@
|
||||
testing.expectEqual(ctx.fillStyle, "rgba(255, 0, 0, 0.06)");
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CanvasRenderingContext2D#createImageData(width, height)">
|
||||
{
|
||||
const element = document.createElement("canvas");
|
||||
const ctx = element.getContext("2d");
|
||||
|
||||
const imageData = ctx.createImageData(100, 200);
|
||||
testing.expectEqual(true, imageData instanceof ImageData);
|
||||
testing.expectEqual(imageData.width, 100);
|
||||
testing.expectEqual(imageData.height, 200);
|
||||
testing.expectEqual(imageData.data.length, 100 * 200 * 4);
|
||||
testing.expectEqual(true, imageData.data instanceof Uint8ClampedArray);
|
||||
|
||||
// All pixels should be initialized to 0.
|
||||
testing.expectEqual(imageData.data[0], 0);
|
||||
testing.expectEqual(imageData.data[1], 0);
|
||||
testing.expectEqual(imageData.data[2], 0);
|
||||
testing.expectEqual(imageData.data[3], 0);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CanvasRenderingContext2D#createImageData(imageData)">
|
||||
{
|
||||
const element = document.createElement("canvas");
|
||||
const ctx = element.getContext("2d");
|
||||
|
||||
const source = ctx.createImageData(50, 75);
|
||||
const imageData = ctx.createImageData(source);
|
||||
testing.expectEqual(true, imageData instanceof ImageData);
|
||||
testing.expectEqual(imageData.width, 50);
|
||||
testing.expectEqual(imageData.height, 75);
|
||||
testing.expectEqual(imageData.data.length, 50 * 75 * 4);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CanvasRenderingContext2D#putImageData">
|
||||
{
|
||||
const element = document.createElement("canvas");
|
||||
const ctx = element.getContext("2d");
|
||||
|
||||
const imageData = ctx.createImageData(10, 10);
|
||||
testing.expectEqual(true, imageData instanceof ImageData);
|
||||
// Modify some pixel data.
|
||||
imageData.data[0] = 255;
|
||||
imageData.data[1] = 0;
|
||||
imageData.data[2] = 0;
|
||||
imageData.data[3] = 255;
|
||||
|
||||
// putImageData should not throw.
|
||||
ctx.putImageData(imageData, 0, 0);
|
||||
ctx.putImageData(imageData, 10, 20);
|
||||
// With dirty rect parameters.
|
||||
ctx.putImageData(imageData, 0, 0, 0, 0, 5, 5);
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
<script id="getter">
|
||||
{
|
||||
const element = document.createElement("canvas");
|
||||
const ctx = element.getContext("2d");
|
||||
testing.expectEqual('10px sans-serif', ctx.font);
|
||||
ctx.font = 'bold 48px serif'
|
||||
testing.expectEqual('bold 48px serif', ctx.font);
|
||||
|
||||
}
|
||||
</script>
|
||||
|
||||
64
src/browser/tests/canvas/offscreen_canvas.html
Normal file
64
src/browser/tests/canvas/offscreen_canvas.html
Normal file
@@ -0,0 +1,64 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id=OffscreenCanvas>
|
||||
{
|
||||
const canvas = new OffscreenCanvas(256, 256);
|
||||
testing.expectEqual(true, canvas instanceof OffscreenCanvas);
|
||||
testing.expectEqual(canvas.width, 256);
|
||||
testing.expectEqual(canvas.height, 256);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=OffscreenCanvas#width>
|
||||
{
|
||||
const canvas = new OffscreenCanvas(100, 200);
|
||||
testing.expectEqual(canvas.width, 100);
|
||||
canvas.width = 300;
|
||||
testing.expectEqual(canvas.width, 300);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=OffscreenCanvas#height>
|
||||
{
|
||||
const canvas = new OffscreenCanvas(100, 200);
|
||||
testing.expectEqual(canvas.height, 200);
|
||||
canvas.height = 400;
|
||||
testing.expectEqual(canvas.height, 400);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=OffscreenCanvas#getContext>
|
||||
{
|
||||
const canvas = new OffscreenCanvas(64, 64);
|
||||
const ctx = canvas.getContext("2d");
|
||||
testing.expectEqual(true, ctx instanceof OffscreenCanvasRenderingContext2D);
|
||||
// We can't really test rendering but let's try to call it at least.
|
||||
ctx.fillRect(0, 0, 10, 10);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=OffscreenCanvas#convertToBlob>
|
||||
{
|
||||
const canvas = new OffscreenCanvas(64, 64);
|
||||
const promise = canvas.convertToBlob();
|
||||
testing.expectEqual(true, promise instanceof Promise);
|
||||
// The promise should resolve to a Blob (even if empty)
|
||||
promise.then(blob => {
|
||||
testing.expectEqual(true, blob instanceof Blob);
|
||||
testing.expectEqual(blob.size, 0); // Empty since no rendering
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=HTMLCanvasElement#transferControlToOffscreen>
|
||||
{
|
||||
const htmlCanvas = document.createElement("canvas");
|
||||
htmlCanvas.width = 128;
|
||||
htmlCanvas.height = 96;
|
||||
const offscreen = htmlCanvas.transferControlToOffscreen();
|
||||
testing.expectEqual(true, offscreen instanceof OffscreenCanvas);
|
||||
testing.expectEqual(offscreen.width, 128);
|
||||
testing.expectEqual(offscreen.height, 96);
|
||||
}
|
||||
</script>
|
||||
@@ -4,4 +4,6 @@
|
||||
<script id=comment>
|
||||
testing.expectEqual('', new Comment().data);
|
||||
testing.expectEqual('over 9000! ', new Comment('over 9000! ').data);
|
||||
|
||||
testing.expectEqual('null', new Comment(null).data);
|
||||
</script>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<!DOCTYPE html>
|
||||
<a id="link" href="foo" class="ok">OK</a>
|
||||
|
||||
<script src="../../testing.js"></script>
|
||||
<script src="../testing.js"></script>
|
||||
<script id=text>
|
||||
let t = new Text('foo');
|
||||
testing.expectEqual('foo', t.data);
|
||||
@@ -16,4 +16,7 @@
|
||||
let split = text.splitText('OK'.length);
|
||||
testing.expectEqual(' modified', split.data);
|
||||
testing.expectEqual('OK', text.data);
|
||||
|
||||
let x = new Text(null);
|
||||
testing.expectEqual("null", x.data);
|
||||
</script>
|
||||
28
src/browser/tests/console/console.html
Normal file
28
src/browser/tests/console/console.html
Normal file
@@ -0,0 +1,28 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id="time">
|
||||
// should not crash
|
||||
console.time();
|
||||
console.timeLog();
|
||||
console.timeEnd();
|
||||
|
||||
console.time("test");
|
||||
console.timeLog("test");
|
||||
console.timeEnd("test");
|
||||
|
||||
testing.expectEqual(true, true);
|
||||
</script>
|
||||
|
||||
<script id="count">
|
||||
// should not crash
|
||||
console.count();
|
||||
console.count();
|
||||
console.countReset();
|
||||
|
||||
console.count("test");
|
||||
console.count("test");
|
||||
console.countReset("test");
|
||||
|
||||
testing.expectEqual(true, true);
|
||||
</script>
|
||||
@@ -16,44 +16,44 @@
|
||||
isRandom(ti8a)
|
||||
}
|
||||
|
||||
// {
|
||||
// let tu16a = new Uint16Array(100)
|
||||
// testing.expectEqual(tu16a, crypto.getRandomValues(tu16a))
|
||||
// isRandom(tu16a)
|
||||
{
|
||||
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 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 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 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 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)
|
||||
// }
|
||||
let ti64a = new BigInt64Array(100)
|
||||
testing.expectEqual(ti64a, crypto.getRandomValues(ti64a))
|
||||
isRandom(ti64a)
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- <script id="randomUUID">
|
||||
<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> -->
|
||||
</script>
|
||||
|
||||
<script id=SubtleCrypto>
|
||||
testing.expectEqual(true, crypto.subtle instanceof SubtleCrypto);
|
||||
@@ -119,3 +119,16 @@
|
||||
testing.expectEqual(16, sharedKey.byteLength);
|
||||
});
|
||||
</script>
|
||||
|
||||
<script id="digest">
|
||||
testing.async(async () => {
|
||||
async function hash(algo, data) {
|
||||
const buffer = await window.crypto.subtle.digest(algo, new TextEncoder().encode(data));
|
||||
return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
testing.expectEqual("a6a1e3375239f215f09a156df29c17c7d1ac6722", await hash('sha-1', 'over 9000'));
|
||||
testing.expectEqual("1bc375bb92459685194dda18a4b835f4e2972ec1bde6d9ab3db53fcc584a6580", await hash('sha-256', 'over 9000'));
|
||||
testing.expectEqual("a4260d64c2eea9fd30c1f895c5e48a26d817e19d3a700b61b3ce665864ff4b8e012bd357d345aa614c5f642dab865ea1", await hash('sha-384', 'over 9000'));
|
||||
testing.expectEqual("6cad17e6f3f76680d6dd18ed043b75b4f6e1aa1d08b917294942e882fb6466c3510948c34af8b903ed0725b582b3b39c0e485ae2c1b7dfdb192ee38b79c782b6", await hash('sha-512', 'over 9000'));
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -20,8 +20,10 @@
|
||||
{
|
||||
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'));
|
||||
testing.expectEqual('\\-', CSS.escape('-'));
|
||||
testing.expectEqual('-test', CSS.escape('-test'));
|
||||
testing.expectEqual('--test', CSS.escape('--test'));
|
||||
testing.expectEqual('-\\33 ', CSS.escape('-3'));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -67,3 +69,11 @@
|
||||
testing.expectEqual(true, CSS.supports('z-index', '10'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="escape_null_character">
|
||||
{
|
||||
testing.expectEqual('\uFFFD', CSS.escape('\x00'));
|
||||
testing.expectEqual('test\uFFFDvalue', CSS.escape('test\x00value'));
|
||||
testing.expectEqual('\uFFFDabc', CSS.escape('\x00abc'));
|
||||
}
|
||||
</script>
|
||||
|
||||
58
src/browser/tests/css/font_face_set.html
Normal file
58
src/browser/tests/css/font_face_set.html
Normal file
@@ -0,0 +1,58 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<script id="document_fonts_exists">
|
||||
{
|
||||
testing.expectTrue(document.fonts !== undefined);
|
||||
testing.expectTrue(document.fonts !== null);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_same_instance">
|
||||
{
|
||||
// Should return same instance each time
|
||||
const f1 = document.fonts;
|
||||
const f2 = document.fonts;
|
||||
testing.expectTrue(f1 === f2);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_status">
|
||||
{
|
||||
testing.expectEqual('loaded', document.fonts.status);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_size">
|
||||
{
|
||||
testing.expectEqual(0, document.fonts.size);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_ready_is_promise">
|
||||
{
|
||||
const ready = document.fonts.ready;
|
||||
testing.expectTrue(ready instanceof Promise);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_ready_resolves">
|
||||
{
|
||||
let resolved = false;
|
||||
document.fonts.ready.then(() => { resolved = true; });
|
||||
// Promise resolution is async; just confirm .then() does not throw
|
||||
testing.expectTrue(typeof document.fonts.ready.then === 'function');
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_check">
|
||||
{
|
||||
testing.expectTrue(document.fonts.check('16px sans-serif'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="document_fonts_constructor_name">
|
||||
{
|
||||
testing.expectEqual('FontFaceSet', document.fonts.constructor.name);
|
||||
}
|
||||
</script>
|
||||
@@ -205,3 +205,73 @@
|
||||
testing.expectEqual('', style.getPropertyPriority('content'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_style_syncs_to_attribute">
|
||||
{
|
||||
// JS style modifications must be reflected in getAttribute.
|
||||
const div = document.createElement('div');
|
||||
|
||||
// Named property assignment (element.style.X = ...)
|
||||
div.style.opacity = '0';
|
||||
testing.expectEqual('opacity: 0;', div.getAttribute('style'));
|
||||
|
||||
// Update existing property
|
||||
div.style.opacity = '1';
|
||||
testing.expectEqual('opacity: 1;', div.getAttribute('style'));
|
||||
|
||||
// Add a second property
|
||||
div.style.color = 'red';
|
||||
testing.expectTrue(div.getAttribute('style').includes('opacity: 1'));
|
||||
testing.expectTrue(div.getAttribute('style').includes('color: red'));
|
||||
|
||||
// removeProperty syncs back
|
||||
div.style.removeProperty('opacity');
|
||||
testing.expectTrue(!div.getAttribute('style').includes('opacity'));
|
||||
testing.expectTrue(div.getAttribute('style').includes('color: red'));
|
||||
|
||||
// setCssText syncs back
|
||||
div.style.cssText = 'filter: blur(0px)';
|
||||
testing.expectEqual('filter: blur(0px);', div.getAttribute('style'));
|
||||
|
||||
// setCssText with empty string clears attribute
|
||||
div.style.cssText = '';
|
||||
testing.expectEqual('', div.getAttribute('style'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_outerHTML_reflects_style_changes">
|
||||
{
|
||||
// outerHTML must reflect JS-modified styles (regression test for
|
||||
// DOM serialization reading stale HTML-parsed attribute values).
|
||||
const div = document.createElement('div');
|
||||
div.setAttribute('style', 'filter:blur(10px);opacity:0');
|
||||
|
||||
div.style.filter = 'blur(0px)';
|
||||
div.style.opacity = '1';
|
||||
|
||||
const html = div.outerHTML;
|
||||
testing.expectTrue(html.includes('filter: blur(0px)'));
|
||||
testing.expectTrue(html.includes('opacity: 1'));
|
||||
testing.expectTrue(!html.includes('blur(10px)'));
|
||||
testing.expectTrue(!html.includes('opacity:0'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="CSSStyleDeclaration_non_ascii_custom_property">
|
||||
{
|
||||
// Regression test: accessing element.style must not crash when the inline
|
||||
// style attribute contains CSS custom properties with non-ASCII (UTF-8
|
||||
// multibyte) names, such as French accented characters.
|
||||
// The CSS Tokenizer's consumeName() must advance over whole UTF-8 sequences
|
||||
// rather than byte-by-byte to avoid landing on a continuation byte.
|
||||
const div = document.createElement('div');
|
||||
div.setAttribute('style',
|
||||
'--color-store-bulles-\u00e9t\u00e9-fg: #6a818f;' +
|
||||
'--color-store-soir\u00e9es-odl-fg: #56b3b3;' +
|
||||
'color: red;'
|
||||
);
|
||||
|
||||
// Must not crash, and ASCII properties that follow non-ASCII ones must be readable.
|
||||
testing.expectEqual('red', div.style.getPropertyValue('color'));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -53,3 +53,22 @@
|
||||
testing.expectEqual('NO-CONSTRUCTOR-ELEMENT', el.tagName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div id=clone_container></div>
|
||||
|
||||
<script id=clone>
|
||||
{
|
||||
let calls = 0;
|
||||
class MyCloneElementA extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
calls += 1;
|
||||
$('#clone_container').appendChild(this);
|
||||
}
|
||||
}
|
||||
customElements.define('my-clone_element_a', MyCloneElementA);
|
||||
const original = document.createElement('my-clone_element_a');
|
||||
$('#clone_container').cloneNode(true);
|
||||
testing.expectEqual(2, calls);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -119,3 +119,33 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="constructor_self_insert_foster_parent">
|
||||
{
|
||||
// Regression: custom element constructor inserting itself (via appendChild) during
|
||||
// innerHTML parsing. When the element is not valid table content, the HTML5 parser
|
||||
// foster-parents it before the <table> via appendBeforeSiblingCallback. That callback
|
||||
// previously didn't check for an existing _parent before calling insertNodeRelative,
|
||||
// causing the "Page.insertNodeRelative parent" assertion to fire.
|
||||
let constructorCalled = 0;
|
||||
let container;
|
||||
|
||||
class CtorSelfInsert extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
constructorCalled++;
|
||||
// Insert self into container so _parent is set before the parser
|
||||
// officially places this element via appendBeforeSiblingCallback.
|
||||
if (container) container.appendChild(this);
|
||||
}
|
||||
}
|
||||
customElements.define('ctor-self-insert', CtorSelfInsert);
|
||||
|
||||
container = document.createElement('div');
|
||||
// ctor-self-insert is not valid table content; the parser foster-parents it
|
||||
// before the <table>, calling appendBeforeSiblingCallback(sibling=table, node=element).
|
||||
// At that point the element already has _parent=container from the constructor.
|
||||
container.innerHTML = '<table><ctor-self-insert></ctor-self-insert></table>';
|
||||
|
||||
testing.expectEqual(1, constructorCalled);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -2,12 +2,18 @@
|
||||
<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(1, document.createElement.length);
|
||||
|
||||
const div1 = document.createElement('div');
|
||||
testing.expectEqual(true, div1 instanceof HTMLDivElement);
|
||||
testing.expectEqual("DIV", div1.tagName);
|
||||
div1.id = "hello";
|
||||
testing.expectEqual(null, $('#hello'));
|
||||
|
||||
document.getElementsByTagName('body')[0].appendChild(div);
|
||||
testing.expectEqual(div, $('#hello'));
|
||||
const div2 = document.createElement('DIV');
|
||||
testing.expectEqual(true, div2 instanceof HTMLDivElement);
|
||||
|
||||
document.getElementsByTagName('body')[0].appendChild(div1);
|
||||
testing.expectEqual(div1, $('#hello'));
|
||||
</script>
|
||||
|
||||
|
||||
@@ -2,9 +2,17 @@
|
||||
<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 htmlDiv1 = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
|
||||
testing.expectEqual('DIV', htmlDiv1.tagName);
|
||||
testing.expectEqual(true, htmlDiv1 instanceof HTMLDivElement);
|
||||
testing.expectEqual('http://www.w3.org/1999/xhtml', htmlDiv1.namespaceURI);
|
||||
|
||||
// Per spec, createElementNS does NOT lowercase — 'DIV' != 'div', so this
|
||||
// creates an HTMLUnknownElement, not an HTMLDivElement.
|
||||
const htmlDiv2 = document.createElementNS('http://www.w3.org/1999/xhtml', 'DIV');
|
||||
testing.expectEqual('DIV', htmlDiv2.tagName);
|
||||
testing.expectEqual(false, htmlDiv2 instanceof HTMLDivElement);
|
||||
testing.expectEqual('http://www.w3.org/1999/xhtml', htmlDiv2.namespaceURI);
|
||||
|
||||
const svgRect = document.createElementNS('http://www.w3.org/2000/svg', 'RecT');
|
||||
testing.expectEqual('RecT', svgRect.tagName);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<!DOCTYPE html>
|
||||
<head id="the_head">
|
||||
<meta charset="UTF-8">
|
||||
<title>Test Document Title</title>
|
||||
<script src="../testing.js"></script>
|
||||
</head>
|
||||
@@ -11,8 +12,12 @@
|
||||
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(testing.BASE_URL + 'document/document.html', document.URL);
|
||||
testing.expectEqual(window, document.defaultView);
|
||||
testing.expectEqual(false, document.hidden);
|
||||
testing.expectEqual("visible", document.visibilityState);
|
||||
testing.expectEqual(false, document.prerendering);
|
||||
testing.expectEqual(undefined, Document.prerendering);
|
||||
</script>
|
||||
|
||||
<script id=headAndbody>
|
||||
@@ -22,6 +27,7 @@
|
||||
|
||||
<script id=documentElement>
|
||||
testing.expectEqual($('#the_body').parentNode, document.documentElement);
|
||||
testing.expectEqual(document.documentElement, document.scrollingElement);
|
||||
</script>
|
||||
|
||||
<script id=title>
|
||||
@@ -51,7 +57,7 @@
|
||||
testing.expectEqual('CSS1Compat', document.compatMode);
|
||||
testing.expectEqual(document.URL, document.documentURI);
|
||||
testing.expectEqual('', document.referrer);
|
||||
testing.expectEqual('127.0.0.1', document.domain);
|
||||
testing.expectEqual(testing.HOST, document.domain);
|
||||
</script>
|
||||
|
||||
<script id=programmatic_document_metadata>
|
||||
@@ -64,7 +70,7 @@
|
||||
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);
|
||||
testing.expectEqual(testing.HOST, doc.domain);
|
||||
</script>
|
||||
|
||||
<!-- Test anchors and links -->
|
||||
@@ -171,15 +177,111 @@
|
||||
testing.expectEqual(initialLength, anchors.length);
|
||||
</script>
|
||||
|
||||
<script id=cookie>
|
||||
testing.expectEqual('', document.cookie);
|
||||
document.cookie = 'name=Oeschger;';
|
||||
document.cookie = 'favorite_food=tripe;';
|
||||
<script id=cookie_basic>
|
||||
// Basic cookie operations
|
||||
document.cookie = 'testbasic1=Oeschger';
|
||||
testing.expectEqual(true, document.cookie.includes('testbasic1=Oeschger'));
|
||||
|
||||
testing.expectEqual('name=Oeschger; favorite_food=tripe', document.cookie);
|
||||
// "" should be returned, but the framework overrules it atm
|
||||
document.cookie = 'testbasic2=tripe';
|
||||
testing.expectEqual(true, document.cookie.includes('testbasic1=Oeschger'));
|
||||
testing.expectEqual(true, document.cookie.includes('testbasic2=tripe'));
|
||||
|
||||
// HttpOnly should be ignored from JavaScript
|
||||
const beforeHttp = document.cookie;
|
||||
document.cookie = 'IgnoreMy=Ghost; HttpOnly';
|
||||
testing.expectEqual('name=Oeschger; favorite_food=tripe', document.cookie);
|
||||
testing.expectEqual(false, document.cookie.includes('IgnoreMy=Ghost'));
|
||||
|
||||
// Clean up
|
||||
document.cookie = 'testbasic1=; Max-Age=0';
|
||||
document.cookie = 'testbasic2=; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_special_chars>
|
||||
// Test special characters in cookie values
|
||||
document.cookie = 'testspaces=hello world';
|
||||
testing.expectEqual(true, document.cookie.includes('testspaces=hello world'));
|
||||
document.cookie = 'testspaces=; Max-Age=0';
|
||||
|
||||
// Test various allowed special characters
|
||||
document.cookie = 'testspecial=!#$%&\'()*+-./';
|
||||
testing.expectEqual(true, document.cookie.includes('testspecial='));
|
||||
document.cookie = 'testspecial=; Max-Age=0';
|
||||
|
||||
// Semicolon terminates the cookie value
|
||||
document.cookie = 'testsemi=before;after';
|
||||
testing.expectEqual(true, document.cookie.includes('testsemi=before'));
|
||||
testing.expectEqual(false, document.cookie.includes('after'));
|
||||
document.cookie = 'testsemi=; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_empty_name>
|
||||
// Cookie with empty name (just a value)
|
||||
document.cookie = 'teststandalone';
|
||||
testing.expectEqual(true, document.cookie.includes('teststandalone'));
|
||||
document.cookie = 'teststandalone; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_whitespace>
|
||||
// Names and values should be trimmed
|
||||
document.cookie = ' testtrim = trimmed_value ';
|
||||
testing.expectEqual(true, document.cookie.includes('testtrim=trimmed_value'));
|
||||
document.cookie = 'testtrim=; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_max_age>
|
||||
// Max-Age=0 should immediately delete
|
||||
document.cookie = 'testtemp0=value; Max-Age=0';
|
||||
testing.expectEqual(false, document.cookie.includes('testtemp0=value'));
|
||||
|
||||
// Negative Max-Age should also delete
|
||||
document.cookie = 'testinstant=value';
|
||||
testing.expectEqual(true, document.cookie.includes('testinstant=value'));
|
||||
document.cookie = 'testinstant=value; Max-Age=-1';
|
||||
testing.expectEqual(false, document.cookie.includes('testinstant=value'));
|
||||
|
||||
// Positive Max-Age should keep cookie
|
||||
document.cookie = 'testkept=value; Max-Age=3600';
|
||||
testing.expectEqual(true, document.cookie.includes('testkept=value'));
|
||||
document.cookie = 'testkept=; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_overwrite>
|
||||
// Setting a cookie with the same name should overwrite
|
||||
document.cookie = 'testoverwrite=first';
|
||||
testing.expectEqual(true, document.cookie.includes('testoverwrite=first'));
|
||||
|
||||
document.cookie = 'testoverwrite=second';
|
||||
testing.expectEqual(true, document.cookie.includes('testoverwrite=second'));
|
||||
testing.expectEqual(false, document.cookie.includes('testoverwrite=first'));
|
||||
|
||||
document.cookie = 'testoverwrite=; Max-Age=0';
|
||||
</script>
|
||||
|
||||
<script id=cookie_path>
|
||||
// Path attribute
|
||||
document.cookie = 'testpath1=value; Path=/';
|
||||
testing.expectEqual(true, document.cookie.includes('testpath1=value'));
|
||||
|
||||
// Different path cookie should coexist
|
||||
document.cookie = 'testpath2=value2; Path=/src';
|
||||
testing.expectEqual(true, document.cookie.includes('testpath1=value'));
|
||||
|
||||
document.cookie = 'testpath1=; Max-Age=0; Path=/';
|
||||
document.cookie = 'testpath2=; Max-Age=0; Path=/src';
|
||||
</script>
|
||||
|
||||
<script id=cookie_invalid_chars>
|
||||
// Control characters (< 32 or > 126) should be rejected
|
||||
const beforeBad = document.cookie;
|
||||
|
||||
document.cookie = 'testbad1\x00=value';
|
||||
testing.expectEqual(false, document.cookie.includes('testbad1'));
|
||||
|
||||
document.cookie = 'testbad2\x1F=value';
|
||||
testing.expectEqual(false, document.cookie.includes('testbad2'));
|
||||
|
||||
document.cookie = 'testbad3=val\x7F';
|
||||
testing.expectEqual(false, document.cookie.includes('testbad3'));
|
||||
</script>
|
||||
|
||||
<script id=createAttribute>
|
||||
|
||||
@@ -81,6 +81,172 @@
|
||||
</script>
|
||||
|
||||
|
||||
<script id="focusin_focusout_events">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
const input2 = $('#input2');
|
||||
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
let events = [];
|
||||
|
||||
input1.addEventListener('focus', () => events.push('focus1'));
|
||||
input1.addEventListener('focusin', () => events.push('focusin1'));
|
||||
input1.addEventListener('blur', () => events.push('blur1'));
|
||||
input1.addEventListener('focusout', () => events.push('focusout1'));
|
||||
input2.addEventListener('focus', () => events.push('focus2'));
|
||||
input2.addEventListener('focusin', () => events.push('focusin2'));
|
||||
|
||||
// Focus input1 — should fire focus then focusin
|
||||
input1.focus();
|
||||
testing.expectEqual('focus1,focusin1', events.join(','));
|
||||
|
||||
// Focus input2 — should fire blur, focusout on input1, then focus, focusin on input2
|
||||
events = [];
|
||||
input2.focus();
|
||||
testing.expectEqual('blur1,focusout1,focus2,focusin2', events.join(','));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="focusin_bubbles">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
let bodyFocusin = 0;
|
||||
let bodyFocus = 0;
|
||||
|
||||
document.body.addEventListener('focusin', () => bodyFocusin++);
|
||||
document.body.addEventListener('focus', () => bodyFocus++);
|
||||
|
||||
input1.focus();
|
||||
|
||||
// focusin should bubble to body, focus should not
|
||||
testing.expectEqual(1, bodyFocusin);
|
||||
testing.expectEqual(0, bodyFocus);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="focusout_bubbles">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
|
||||
input1.focus();
|
||||
|
||||
let bodyFocusout = 0;
|
||||
let bodyBlur = 0;
|
||||
|
||||
document.body.addEventListener('focusout', () => bodyFocusout++);
|
||||
document.body.addEventListener('blur', () => bodyBlur++);
|
||||
|
||||
input1.blur();
|
||||
|
||||
// focusout should bubble to body, blur should not
|
||||
testing.expectEqual(1, bodyFocusout);
|
||||
testing.expectEqual(0, bodyBlur);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="focus_relatedTarget">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
const input2 = $('#input2');
|
||||
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
let focusRelated = null;
|
||||
let blurRelated = null;
|
||||
let focusinRelated = null;
|
||||
let focusoutRelated = null;
|
||||
|
||||
input1.addEventListener('blur', (e) => { blurRelated = e.relatedTarget; });
|
||||
input1.addEventListener('focusout', (e) => { focusoutRelated = e.relatedTarget; });
|
||||
input2.addEventListener('focus', (e) => { focusRelated = e.relatedTarget; });
|
||||
input2.addEventListener('focusin', (e) => { focusinRelated = e.relatedTarget; });
|
||||
|
||||
input1.focus();
|
||||
input2.focus();
|
||||
|
||||
// blur/focusout on input1 should have relatedTarget = input2 (gaining focus)
|
||||
testing.expectEqual(input2, blurRelated);
|
||||
testing.expectEqual(input2, focusoutRelated);
|
||||
|
||||
// focus/focusin on input2 should have relatedTarget = input1 (losing focus)
|
||||
testing.expectEqual(input1, focusRelated);
|
||||
testing.expectEqual(input1, focusinRelated);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="blur_relatedTarget_null">
|
||||
{
|
||||
const btn = $('#btn1');
|
||||
|
||||
btn.focus();
|
||||
|
||||
let blurRelated = 'not_set';
|
||||
btn.addEventListener('blur', (e) => { blurRelated = e.relatedTarget; });
|
||||
btn.blur();
|
||||
|
||||
// blur without moving to another element should have relatedTarget = null
|
||||
testing.expectEqual(null, blurRelated);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="focus_event_properties">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
const input2 = $('#input2');
|
||||
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
let focusEvent = null;
|
||||
let focusinEvent = null;
|
||||
let blurEvent = null;
|
||||
let focusoutEvent = null;
|
||||
|
||||
input1.addEventListener('blur', (e) => { blurEvent = e; });
|
||||
input1.addEventListener('focusout', (e) => { focusoutEvent = e; });
|
||||
input2.addEventListener('focus', (e) => { focusEvent = e; });
|
||||
input2.addEventListener('focusin', (e) => { focusinEvent = e; });
|
||||
|
||||
input1.focus();
|
||||
input2.focus();
|
||||
|
||||
// All four should be FocusEvent instances
|
||||
testing.expectEqual(true, blurEvent instanceof FocusEvent);
|
||||
testing.expectEqual(true, focusoutEvent instanceof FocusEvent);
|
||||
testing.expectEqual(true, focusEvent instanceof FocusEvent);
|
||||
testing.expectEqual(true, focusinEvent instanceof FocusEvent);
|
||||
|
||||
// All four should be composed per spec
|
||||
testing.expectEqual(true, blurEvent.composed);
|
||||
testing.expectEqual(true, focusoutEvent.composed);
|
||||
testing.expectEqual(true, focusEvent.composed);
|
||||
testing.expectEqual(true, focusinEvent.composed);
|
||||
|
||||
// None should be cancelable
|
||||
testing.expectEqual(false, blurEvent.cancelable);
|
||||
testing.expectEqual(false, focusoutEvent.cancelable);
|
||||
testing.expectEqual(false, focusEvent.cancelable);
|
||||
testing.expectEqual(false, focusinEvent.cancelable);
|
||||
|
||||
// blur/focus don't bubble, focusin/focusout do
|
||||
testing.expectEqual(false, blurEvent.bubbles);
|
||||
testing.expectEqual(true, focusoutEvent.bubbles);
|
||||
testing.expectEqual(false, focusEvent.bubbles);
|
||||
testing.expectEqual(true, focusinEvent.bubbles);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="focus_disconnected">
|
||||
{
|
||||
const focused = document.activeElement;
|
||||
@@ -88,3 +254,68 @@
|
||||
testing.expectEqual(focused, document.activeElement);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="click_focuses_element">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
const input2 = $('#input2');
|
||||
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
let focusCount = 0;
|
||||
let blurCount = 0;
|
||||
|
||||
input1.addEventListener('focus', () => focusCount++);
|
||||
input1.addEventListener('blur', () => blurCount++);
|
||||
input2.addEventListener('focus', () => focusCount++);
|
||||
|
||||
// Click input1 — should focus it and fire focus event
|
||||
input1.click();
|
||||
testing.expectEqual(input1, document.activeElement);
|
||||
testing.expectEqual(1, focusCount);
|
||||
testing.expectEqual(0, blurCount);
|
||||
|
||||
// Click input2 — should move focus, fire blur on input1 and focus on input2
|
||||
input2.click();
|
||||
testing.expectEqual(input2, document.activeElement);
|
||||
testing.expectEqual(2, focusCount);
|
||||
testing.expectEqual(1, blurCount);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="click_focuses_button">
|
||||
{
|
||||
const btn = $('#btn1');
|
||||
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
btn.click();
|
||||
testing.expectEqual(btn, document.activeElement);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="focus_disconnected_no_blur">
|
||||
{
|
||||
const input1 = $('#input1');
|
||||
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
input1.focus();
|
||||
testing.expectEqual(input1, document.activeElement);
|
||||
|
||||
let blurCount = 0;
|
||||
input1.addEventListener('blur', () => { blurCount++ });
|
||||
|
||||
// Focusing a disconnected element should be a no-op:
|
||||
// blur must not fire on the currently focused element
|
||||
document.createElement('a').focus();
|
||||
testing.expectEqual(input1, document.activeElement);
|
||||
testing.expectEqual(0, blurCount);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
<main>Main content</main>
|
||||
|
||||
<script id=byId name="test1">
|
||||
testing.expectEqual(1, document.querySelector.length);
|
||||
testing.expectError("SyntaxError: Syntax Error", () => document.querySelector(''));
|
||||
testing.withError((err) => {
|
||||
testing.expectEqual(12, err.code);
|
||||
@@ -269,3 +270,36 @@
|
||||
testing.expectEqual('rect', document.querySelector('svg g rect').tagName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=special>
|
||||
testing.expectEqual(null, document.querySelector('\\'));
|
||||
|
||||
testing.expectEqual(null, document.querySelector('div\\'));
|
||||
testing.expectEqual(null, document.querySelector('.test-class\\'));
|
||||
testing.expectEqual(null, document.querySelector('#byId\\'));
|
||||
</script>
|
||||
|
||||
<div class="café">Non-ASCII class 1</div>
|
||||
<div class="日本語">Non-ASCII class 2</div>
|
||||
<span id="niño">Non-ASCII ID 1</span>
|
||||
<p id="🎨">Non-ASCII ID 2</p>
|
||||
|
||||
<script id=nonAsciiSelectors>
|
||||
testing.expectEqual('Non-ASCII class 1', document.querySelector('.café').textContent);
|
||||
testing.expectEqual('Non-ASCII class 2', document.querySelector('.日本語').textContent);
|
||||
|
||||
testing.expectEqual('Non-ASCII ID 1', document.querySelector('#niño').textContent);
|
||||
testing.expectEqual('Non-ASCII ID 2', document.querySelector('#🎨').textContent);
|
||||
|
||||
testing.expectEqual('Non-ASCII class 1', document.querySelector('div.café').textContent);
|
||||
testing.expectEqual('Non-ASCII ID 1', document.querySelector('span#niño').textContent);
|
||||
</script>
|
||||
|
||||
<span id=".,:!">Punctuation test</span>
|
||||
|
||||
<script id=escapedPunctuation>
|
||||
{
|
||||
// Test escaped punctuation in ID selectors
|
||||
testing.expectEqual('Punctuation test', document.querySelector('#\\.\\,\\:\\!').textContent);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -27,7 +27,9 @@
|
||||
testing.expectEqual(expected.length, result.length);
|
||||
testing.expectEqual(expected, Array.from(result).map((e) => e.textContent));
|
||||
testing.expectEqual(expected, Array.from(result.values()).map((e) => e.textContent));
|
||||
|
||||
testing.expectEqual(expected.map((e, i) => i), Array.from(result.keys()));
|
||||
testing.expectEqual(expected.map((e, i) => i.toString()), Object.keys(result));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -376,3 +378,93 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<form id="form-validity-test">
|
||||
<input id="vi-required-empty" type="text" required>
|
||||
<input id="vi-optional" type="text">
|
||||
<input id="vi-hidden-required" type="hidden" required>
|
||||
<fieldset id="vi-fieldset">
|
||||
<input id="vi-nested-required" type="text" required>
|
||||
<select id="vi-select-required" required>
|
||||
<option value="">Pick one</option>
|
||||
<option value="a">A</option>
|
||||
</select>
|
||||
</fieldset>
|
||||
</form>
|
||||
<input id="vi-checkbox" type="checkbox">
|
||||
|
||||
<script id=invalidPseudo>
|
||||
{
|
||||
// Inputs with required + empty value are :invalid
|
||||
testing.expectEqual(true, document.getElementById('vi-required-empty').matches(':invalid'));
|
||||
testing.expectEqual(false, document.getElementById('vi-required-empty').matches(':valid'));
|
||||
|
||||
// Inputs without required are :valid
|
||||
testing.expectEqual(false, document.getElementById('vi-optional').matches(':invalid'));
|
||||
testing.expectEqual(true, document.getElementById('vi-optional').matches(':valid'));
|
||||
|
||||
// hidden inputs are not candidates for constraint validation
|
||||
testing.expectEqual(false, document.getElementById('vi-hidden-required').matches(':invalid'));
|
||||
testing.expectEqual(false, document.getElementById('vi-hidden-required').matches(':valid'));
|
||||
|
||||
// select with required and empty selected value is :invalid
|
||||
testing.expectEqual(true, document.getElementById('vi-select-required').matches(':invalid'));
|
||||
testing.expectEqual(false, document.getElementById('vi-select-required').matches(':valid'));
|
||||
|
||||
// fieldset containing invalid controls is :invalid
|
||||
testing.expectEqual(true, document.getElementById('vi-fieldset').matches(':invalid'));
|
||||
testing.expectEqual(false, document.getElementById('vi-fieldset').matches(':valid'));
|
||||
|
||||
// form containing invalid controls is :invalid
|
||||
testing.expectEqual(true, document.getElementById('form-validity-test').matches(':invalid'));
|
||||
testing.expectEqual(false, document.getElementById('form-validity-test').matches(':valid'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=validAfterValueSet>
|
||||
{
|
||||
// After setting a value, a required input becomes :valid
|
||||
const input = document.getElementById('vi-required-empty');
|
||||
input.value = 'hello';
|
||||
testing.expectEqual(false, input.matches(':invalid'));
|
||||
testing.expectEqual(true, input.matches(':valid'));
|
||||
input.value = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=indeterminatePseudo>
|
||||
{
|
||||
const cb = document.getElementById('vi-checkbox');
|
||||
testing.expectEqual(false, cb.matches(':indeterminate'));
|
||||
cb.indeterminate = true;
|
||||
testing.expectEqual(true, cb.matches(':indeterminate'));
|
||||
cb.indeterminate = false;
|
||||
testing.expectEqual(false, cb.matches(':indeterminate'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=iterator_list_lifetime>
|
||||
// This test is intended to ensure that a list remains alive as long as it
|
||||
// must, i.e. as long as any iterator referencing the list is alive.
|
||||
// This test depends on being able to force the v8 GC to cleanup, which
|
||||
// we have no way of controlling. At worst, the test will pass without
|
||||
// actually testing correct lifetime. But it was at least manually verified
|
||||
// for me that this triggers plenty of GCs.
|
||||
const expected = Array.from(document.querySelectorAll('*')).length;
|
||||
{
|
||||
let keys = [];
|
||||
|
||||
// Phase 1: Create many lists+iterators to fill up the arena pool
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
let list = document.querySelectorAll('*');
|
||||
keys.push(list.keys());
|
||||
|
||||
// Create an Event every iteration to compete for arenas
|
||||
new Event('arena_compete');
|
||||
}
|
||||
|
||||
for (let k of keys) {
|
||||
const result = Array.from(k);
|
||||
testing.expectEqual(expected, result.length);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -111,3 +111,15 @@
|
||||
const containerDataTest = document.querySelector('#container [data-test]');
|
||||
testing.expectEqual('First', containerDataTest.innerText);
|
||||
</script>
|
||||
|
||||
<link rel="preload" as="image" imagesrcset="url1.png 1x, url2.png 2x" id="preload-link">
|
||||
|
||||
<script id="commaInAttrValue">
|
||||
// Commas inside quoted attribute values must not be treated as selector separators
|
||||
const el = document.querySelector('link[rel="preload"][as="image"][imagesrcset="url1.png 1x, url2.png 2x"]');
|
||||
testing.expectEqual('preload-link', el.id);
|
||||
|
||||
// Also test with single quotes inside selector
|
||||
const el2 = document.querySelector("link[imagesrcset='url1.png 1x, url2.png 2x']");
|
||||
testing.expectEqual('preload-link', el2.id);
|
||||
</script>
|
||||
|
||||
@@ -108,6 +108,20 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=createHTMLDocument_nulll_title>
|
||||
{
|
||||
const impl = document.implementation;
|
||||
const doc = impl.createHTMLDocument(null);
|
||||
|
||||
testing.expectEqual('null', doc.title);
|
||||
|
||||
// Should have title element in head
|
||||
const titleElement = doc.head.querySelector('title');
|
||||
testing.expectEqual(true, titleElement !== null);
|
||||
testing.expectEqual('null', titleElement.textContent);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=createHTMLDocument_structure>
|
||||
{
|
||||
const impl = document.implementation;
|
||||
|
||||
@@ -248,7 +248,7 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<div id=legacy></a>
|
||||
<a id=legacy></a>
|
||||
<script id=legacy>
|
||||
{
|
||||
let a = document.getElementById('legacy').attributes;
|
||||
@@ -266,3 +266,19 @@
|
||||
testing.expectEqual('abc123', a[0].value);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div id="nsa"></div>
|
||||
<script id=non-string-attr>
|
||||
{
|
||||
let nsa = document.getElementById('nsa');
|
||||
|
||||
nsa.setAttribute('int', 1);
|
||||
testing.expectEqual('1', nsa.getAttribute('int'));
|
||||
|
||||
nsa.setAttribute('obj', {});
|
||||
testing.expectEqual('[object Object]', nsa.getAttribute('obj'));
|
||||
|
||||
nsa.setAttribute('arr', []);
|
||||
testing.expectEqual('', nsa.getAttribute('arr'));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -93,6 +93,29 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=replace_errors>
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
div.className = 'foo bar';
|
||||
|
||||
testing.withError((err) => {
|
||||
testing.expectEqual('SyntaxError', err.name);
|
||||
}, () => div.classList.replace('', 'baz'));
|
||||
|
||||
testing.withError((err) => {
|
||||
testing.expectEqual('SyntaxError', err.name);
|
||||
}, () => div.classList.replace('foo', ''));
|
||||
|
||||
testing.withError((err) => {
|
||||
testing.expectEqual('InvalidCharacterError', err.name);
|
||||
}, () => div.classList.replace('foo bar', 'baz'));
|
||||
|
||||
testing.withError((err) => {
|
||||
testing.expectEqual('InvalidCharacterError', err.name);
|
||||
}, () => div.classList.replace('foo', 'bar baz'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=item>
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
@@ -166,6 +189,29 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=classList_assignment>
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
|
||||
// Direct assignment should work (equivalent to classList.value = ...)
|
||||
div.classList = 'foo bar baz';
|
||||
testing.expectEqual('foo bar baz', div.className);
|
||||
testing.expectEqual(3, div.classList.length);
|
||||
testing.expectEqual(true, div.classList.contains('foo'));
|
||||
|
||||
// Assigning again should replace
|
||||
div.classList = 'qux';
|
||||
testing.expectEqual('qux', div.className);
|
||||
testing.expectEqual(1, div.classList.length);
|
||||
testing.expectEqual(false, div.classList.contains('foo'));
|
||||
|
||||
// Empty assignment
|
||||
div.classList = '';
|
||||
testing.expectEqual('', div.className);
|
||||
testing.expectEqual(0, div.classList.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=errors>
|
||||
{
|
||||
const div = document.createElement('div');
|
||||
|
||||
@@ -121,6 +121,29 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="propertyAssignment">
|
||||
{
|
||||
const div = $('#test-div');
|
||||
div.style.cssText = '';
|
||||
|
||||
// camelCase assignment
|
||||
div.style.opacity = '0.5';
|
||||
testing.expectEqual('0.5', div.style.opacity);
|
||||
|
||||
// bracket notation assignment
|
||||
div.style['filter'] = 'blur(5px)';
|
||||
testing.expectEqual('blur(5px)', div.style.filter);
|
||||
|
||||
// numeric value coerced to string
|
||||
div.style.opacity = 1;
|
||||
testing.expectEqual('1', div.style.opacity);
|
||||
|
||||
// assigning method names should be ignored (not intercepted)
|
||||
div.style.setProperty('color', 'blue');
|
||||
testing.expectEqual('blue', div.style.color);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="prototypeChainCheck">
|
||||
{
|
||||
const div = $('#test-div');
|
||||
@@ -131,3 +154,11 @@
|
||||
testing.expectEqual(true, typeof div.style.getPropertyPriority === 'function');
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
<div id=crash1 style="background-position: 5% .1em"></div>
|
||||
<script id="crash_case_1">
|
||||
{
|
||||
testing.expectEqual('5% .1em', $('#crash1').style.backgroundPosition);
|
||||
}
|
||||
</script>
|
||||
|
||||
123
src/browser/tests/element/get_elements_by_tag_name_ns.html
Normal file
123
src/browser/tests/element/get_elements_by_tag_name_ns.html
Normal file
@@ -0,0 +1,123 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../testing.js"></script>
|
||||
|
||||
<div id="container" xmlns="http://www.w3.org/1999/xhtml">
|
||||
<div id="div1">div1</div>
|
||||
<p id="p1">p1</p>
|
||||
<div id="div2">div2</div>
|
||||
</div>
|
||||
|
||||
<svg id="svgContainer" xmlns="http://www.w3.org/2000/svg" width="100" height="100">
|
||||
<circle id="circle1" cx="50" cy="50" r="40"/>
|
||||
<rect id="rect1" x="10" y="10" width="30" height="30"/>
|
||||
<circle id="circle2" cx="25" cy="25" r="10"/>
|
||||
</svg>
|
||||
|
||||
<div id="mixed">
|
||||
<div id="htmlDiv" xmlns="http://www.w3.org/1999/xhtml">HTML div</div>
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<circle id="svgCircle" cx="10" cy="10" r="5"/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<script id=basic>
|
||||
{
|
||||
const htmlNS = "http://www.w3.org/1999/xhtml";
|
||||
const svgNS = "http://www.w3.org/2000/svg";
|
||||
|
||||
// Test HTML namespace
|
||||
const htmlDivs = document.getElementsByTagNameNS(htmlNS, 'div');
|
||||
testing.expectEqual(true, htmlDivs instanceof HTMLCollection);
|
||||
testing.expectEqual(5, htmlDivs.length); // container, div1, div2, mixed, htmlDiv
|
||||
|
||||
const htmlPs = document.getElementsByTagNameNS(htmlNS, 'p');
|
||||
testing.expectEqual(1, htmlPs.length);
|
||||
testing.expectEqual('p1', htmlPs[0].id);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=svgNamespace>
|
||||
{
|
||||
const svgNS = "http://www.w3.org/2000/svg";
|
||||
|
||||
const circles = document.getElementsByTagNameNS(svgNS, 'circle');
|
||||
testing.expectEqual(3, circles.length); // circle1, circle2, svgCircle
|
||||
testing.expectEqual('circle1', circles[0].id);
|
||||
testing.expectEqual('circle2', circles[1].id);
|
||||
testing.expectEqual('svgCircle', circles[2].id);
|
||||
|
||||
const rects = document.getElementsByTagNameNS(svgNS, 'rect');
|
||||
testing.expectEqual(1, rects.length);
|
||||
testing.expectEqual('rect1', rects[0].id);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=nullNamespace>
|
||||
{
|
||||
// Null namespace should match elements with null namespace
|
||||
const nullNsElements = document.getElementsByTagNameNS(null, 'div');
|
||||
testing.expectEqual(0, nullNsElements.length); // Our divs are in HTML namespace
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=wildcardNamespace>
|
||||
{
|
||||
// Wildcard namespace "*" should match all namespaces
|
||||
const allDivs = document.getElementsByTagNameNS('*', 'div');
|
||||
testing.expectEqual(5, allDivs.length); // All divs regardless of namespace
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=wildcardLocalName>
|
||||
{
|
||||
const htmlNS = "http://www.w3.org/1999/xhtml";
|
||||
|
||||
// Wildcard local name should match all elements in that namespace
|
||||
const allHtmlElements = document.getElementsByTagNameNS(htmlNS, '*');
|
||||
testing.expectEqual(true, allHtmlElements.length > 0);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=caseSensitive>
|
||||
{
|
||||
const htmlNS = "http://www.w3.org/1999/xhtml";
|
||||
|
||||
// getElementsByTagNameNS is case-sensitive for local names
|
||||
const lowerDivs = document.getElementsByTagNameNS(htmlNS, 'div');
|
||||
const upperDivs = document.getElementsByTagNameNS(htmlNS, 'DIV');
|
||||
|
||||
testing.expectEqual(5, lowerDivs.length);
|
||||
testing.expectEqual(0, upperDivs.length); // Should be 0 because it's case-sensitive
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=unknownNamespace>
|
||||
{
|
||||
// Unknown namespace should still work
|
||||
const unknownNs = document.getElementsByTagNameNS('http://example.com/unknown', 'div');
|
||||
testing.expectEqual(0, unknownNs.length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=emptyResult>
|
||||
{
|
||||
const htmlNS = "http://www.w3.org/1999/xhtml";
|
||||
const svgNS = "http://www.w3.org/2000/svg";
|
||||
|
||||
testing.expectEqual(0, document.getElementsByTagNameNS(htmlNS, 'nonexistent').length);
|
||||
testing.expectEqual(0, document.getElementsByTagNameNS(svgNS, 'nonexistent').length);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=elementMethod>
|
||||
{
|
||||
const htmlNS = "http://www.w3.org/1999/xhtml";
|
||||
const container = document.getElementById('container');
|
||||
|
||||
// getElementsByTagNameNS on element should only search descendants
|
||||
const divsInContainer = container.getElementsByTagNameNS(htmlNS, 'div');
|
||||
testing.expectEqual(2, divsInContainer.length); // div1, div2 (not container itself)
|
||||
testing.expectEqual('div1', divsInContainer[0].id);
|
||||
testing.expectEqual('div2', divsInContainer[1].id);
|
||||
}
|
||||
</script>
|
||||
@@ -11,11 +11,11 @@
|
||||
<script id=empty_href>
|
||||
testing.expectEqual('', $('#a0').href);
|
||||
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/anchor1.html', $('#a1').href);
|
||||
testing.expectEqual('http://127.0.0.1:9582/hello/world/anchor2.html', $('#a2').href);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/anchor1.html', $('#a1').href);
|
||||
testing.expectEqual(testing.ORIGIN + 'hello/world/anchor2.html', $('#a2').href);
|
||||
testing.expectEqual('https://www.openmymind.net/Elixirs-With-Statement/', $('#a3').href);
|
||||
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/foo', $('#link').href);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/foo', $('#link').href);
|
||||
</script>
|
||||
|
||||
<script id=dynamic_anchor_defaults>
|
||||
@@ -129,7 +129,7 @@
|
||||
testing.expectEqual('https://foo.bar/?q=bar#frag', link.href);
|
||||
|
||||
link.href = 'foo';
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/foo', link.href);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/foo', link.href);
|
||||
|
||||
testing.expectEqual('', link.type);
|
||||
link.type = 'text/html';
|
||||
@@ -245,3 +245,11 @@
|
||||
testing.expectEqual('', b.toString());
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=url_encode>
|
||||
{
|
||||
let a = document.createElement('a');
|
||||
a.href = 'over 9000!';
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/over%209000!', a.href);
|
||||
}
|
||||
</script>
|
||||
|
||||
63
src/browser/tests/element/html/details.html
Normal file
63
src/browser/tests/element/html/details.html
Normal file
@@ -0,0 +1,63 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<!-- Details elements -->
|
||||
<details id="details1">
|
||||
<summary>Summary</summary>
|
||||
Content
|
||||
</details>
|
||||
<details id="details2" open>
|
||||
<summary>Open Summary</summary>
|
||||
Content
|
||||
</details>
|
||||
|
||||
<script id="instanceof">
|
||||
{
|
||||
const details = document.createElement('details')
|
||||
testing.expectTrue(details instanceof HTMLDetailsElement)
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="open_initial">
|
||||
testing.expectEqual(false, $('#details1').open)
|
||||
testing.expectEqual(true, $('#details2').open)
|
||||
</script>
|
||||
|
||||
<script id="open_set">
|
||||
{
|
||||
$('#details1').open = true
|
||||
testing.expectEqual(true, $('#details1').open)
|
||||
|
||||
$('#details2').open = false
|
||||
testing.expectEqual(false, $('#details2').open)
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="open_reflects_attribute">
|
||||
{
|
||||
const details = document.createElement('details')
|
||||
testing.expectEqual(null, details.getAttribute('open'))
|
||||
|
||||
details.open = true
|
||||
testing.expectEqual('', details.getAttribute('open'))
|
||||
|
||||
details.open = false
|
||||
testing.expectEqual(null, details.getAttribute('open'))
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="name_initial">
|
||||
{
|
||||
const details = document.createElement('details')
|
||||
testing.expectEqual('', details.name)
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="name_set">
|
||||
{
|
||||
const details = document.createElement('details')
|
||||
details.name = 'group1'
|
||||
testing.expectEqual('group1', details.name)
|
||||
testing.expectEqual('group1', details.getAttribute('name'))
|
||||
}
|
||||
</script>
|
||||
@@ -143,6 +143,29 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="js_setter_null_clears_listener">
|
||||
{
|
||||
// Setting an event handler property to null must silently clear it (not throw).
|
||||
// Browsers also accept undefined and non-function values without throwing.
|
||||
const div = document.createElement('div');
|
||||
|
||||
div.onload = () => 42;
|
||||
testing.expectEqual('function', typeof div.onload);
|
||||
|
||||
// Setting to null removes the listener; getter returns null
|
||||
div.onload = null;
|
||||
testing.expectEqual(null, div.onload);
|
||||
|
||||
div.onerror = () => {};
|
||||
div.onerror = null;
|
||||
testing.expectEqual(null, div.onerror);
|
||||
|
||||
div.onclick = () => {};
|
||||
div.onclick = null;
|
||||
testing.expectEqual(null, div.onclick);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="different_event_types_independent">
|
||||
{
|
||||
// Test that different event types are stored independently
|
||||
@@ -488,3 +511,27 @@
|
||||
testing.expectEqual('function', typeof div.onratechange);
|
||||
}
|
||||
</script>
|
||||
|
||||
<img src="https://cdn.lightpanda.io/website/assets/images/docs/hn.png" />
|
||||
|
||||
<script id="document-element-load">
|
||||
{
|
||||
let asyncBlockDispatched = false;
|
||||
const docElement = document.documentElement;
|
||||
|
||||
testing.async(async () => {
|
||||
const result = await new Promise(resolve => {
|
||||
// We should get this fired at capturing phase when a resource loaded.
|
||||
docElement.addEventListener("load", e => {
|
||||
testing.expectEqual(e.eventPhase, Event.CAPTURING_PHASE);
|
||||
return resolve(true);
|
||||
}, true);
|
||||
});
|
||||
|
||||
asyncBlockDispatched = true;
|
||||
testing.expectEqual(true, result);
|
||||
});
|
||||
|
||||
testing.eventually(() => testing.expectEqual(true, asyncBlockDispatched));
|
||||
}
|
||||
</script>
|
||||
|
||||
35
src/browser/tests/element/html/fieldset.html
Normal file
35
src/browser/tests/element/html/fieldset.html
Normal file
@@ -0,0 +1,35 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<fieldset id="fs1" disabled name="group1">
|
||||
<input type="text">
|
||||
</fieldset>
|
||||
<fieldset id="fs2">
|
||||
<input type="text">
|
||||
</fieldset>
|
||||
|
||||
<script id="disabled">
|
||||
{
|
||||
const fs1 = document.getElementById('fs1');
|
||||
testing.expectEqual(true, fs1.disabled);
|
||||
|
||||
fs1.disabled = false;
|
||||
testing.expectEqual(false, fs1.disabled);
|
||||
|
||||
const fs2 = document.getElementById('fs2');
|
||||
testing.expectEqual(false, fs2.disabled);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="name">
|
||||
{
|
||||
const fs1 = document.getElementById('fs1');
|
||||
testing.expectEqual('group1', fs1.name);
|
||||
|
||||
fs1.name = 'updated';
|
||||
testing.expectEqual('updated', fs1.name);
|
||||
|
||||
const fs2 = document.getElementById('fs2');
|
||||
testing.expectEqual('', fs2.name);
|
||||
}
|
||||
</script>
|
||||
56
src/browser/tests/element/html/htmlelement-props.html
Normal file
56
src/browser/tests/element/html/htmlelement-props.html
Normal file
@@ -0,0 +1,56 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<div id="d1" hidden>Hidden div</div>
|
||||
<div id="d2">Visible div</div>
|
||||
<input id="i1" tabindex="5">
|
||||
<div id="d3">No tabindex</div>
|
||||
|
||||
<script id="hidden">
|
||||
{
|
||||
const d1 = document.getElementById('d1');
|
||||
testing.expectEqual(true, d1.hidden);
|
||||
|
||||
d1.hidden = false;
|
||||
testing.expectEqual(false, d1.hidden);
|
||||
|
||||
const d2 = document.getElementById('d2');
|
||||
testing.expectEqual(false, d2.hidden);
|
||||
|
||||
d2.hidden = true;
|
||||
testing.expectEqual(true, d2.hidden);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="tabIndex">
|
||||
{
|
||||
const i1 = document.getElementById('i1');
|
||||
testing.expectEqual(5, i1.tabIndex);
|
||||
|
||||
i1.tabIndex = 10;
|
||||
testing.expectEqual(10, i1.tabIndex);
|
||||
|
||||
// Non-interactive elements default to -1
|
||||
const d3 = document.getElementById('d3');
|
||||
testing.expectEqual(-1, d3.tabIndex);
|
||||
|
||||
d3.tabIndex = 0;
|
||||
testing.expectEqual(0, d3.tabIndex);
|
||||
|
||||
// Interactive elements default to 0 per spec
|
||||
const input = document.createElement('input');
|
||||
testing.expectEqual(0, input.tabIndex);
|
||||
|
||||
const button = document.createElement('button');
|
||||
testing.expectEqual(0, button.tabIndex);
|
||||
|
||||
const a = document.createElement('a');
|
||||
testing.expectEqual(0, a.tabIndex);
|
||||
|
||||
const select = document.createElement('select');
|
||||
testing.expectEqual(0, select.tabIndex);
|
||||
|
||||
const textarea = document.createElement('textarea');
|
||||
testing.expectEqual(0, textarea.tabIndex);
|
||||
}
|
||||
</script>
|
||||
@@ -32,12 +32,12 @@
|
||||
|
||||
img.src = 'test.png';
|
||||
// src property returns resolved absolute URL
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/test.png', img.src);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/test.png', img.src);
|
||||
// getAttribute returns the raw attribute value
|
||||
testing.expectEqual('test.png', img.getAttribute('src'));
|
||||
|
||||
img.src = '/absolute/path.png';
|
||||
testing.expectEqual('http://127.0.0.1:9582/absolute/path.png', img.src);
|
||||
testing.expectEqual(testing.ORIGIN + 'absolute/path.png', img.src);
|
||||
testing.expectEqual('/absolute/path.png', img.getAttribute('src'));
|
||||
|
||||
img.src = 'https://example.com/image.png';
|
||||
@@ -97,3 +97,79 @@
|
||||
testing.expectEqual('lazy', img.getAttribute('loading'));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="complete">
|
||||
{
|
||||
// Image with no src is complete per spec
|
||||
const img = document.createElement('img');
|
||||
testing.expectEqual(true, img.complete);
|
||||
|
||||
// Image with src is also complete (headless browser, no actual fetch)
|
||||
img.src = 'test.png';
|
||||
testing.expectEqual(true, img.complete);
|
||||
|
||||
// Image constructor also complete
|
||||
const img2 = new Image();
|
||||
testing.expectEqual(true, img2.complete);
|
||||
}
|
||||
</script>
|
||||
|
||||
<body></body>
|
||||
|
||||
<script id="img-load-event">
|
||||
{
|
||||
// An img fires a load event when src is set.
|
||||
const img = document.createElement("img");
|
||||
let result = false;
|
||||
testing.async(async () => {
|
||||
await new Promise(resolve => {
|
||||
img.addEventListener("load", ({ bubbles, cancelBubble, cancelable, composed, isTrusted, target }) => {
|
||||
testing.expectEqual(false, bubbles);
|
||||
testing.expectEqual(false, cancelBubble);
|
||||
testing.expectEqual(false, cancelable);
|
||||
testing.expectEqual(false, composed);
|
||||
testing.expectEqual(true, isTrusted);
|
||||
testing.expectEqual(img, target);
|
||||
result = true;
|
||||
return resolve();
|
||||
});
|
||||
img.src = "https://cdn.lightpanda.io/website/assets/images/docs/hn.png";
|
||||
});
|
||||
});
|
||||
|
||||
testing.eventually(() => testing.expectEqual(true, result));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="img-no-load-without-src">
|
||||
{
|
||||
// An img without src should not fire a load event.
|
||||
let fired = false;
|
||||
const img = document.createElement("img");
|
||||
img.addEventListener("load", () => { fired = true; });
|
||||
document.body.appendChild(img);
|
||||
testing.eventually(() => testing.expectEqual(false, fired));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="lazy-src-set">
|
||||
{
|
||||
// Append to DOM first, then set src — load should still fire.
|
||||
const img = document.createElement("img");
|
||||
let result = false;
|
||||
img.onload = () => result = true;
|
||||
document.body.appendChild(img);
|
||||
img.src = "https://cdn.lightpanda.io/website/assets/images/docs/hn.png";
|
||||
|
||||
testing.eventually(() => testing.expectEqual(true, result));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id=url_encode>
|
||||
{
|
||||
let img = document.createElement('img');
|
||||
img.src = 'over 9000!?hello=world !';
|
||||
testing.expectEqual('over 9000!?hello=world !', img.getAttribute('src'));
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/over%209000!?hello=world%20!', img.src);
|
||||
}
|
||||
</script>
|
||||
|
||||
87
src/browser/tests/element/html/input-attrs.html
Normal file
87
src/browser/tests/element/html/input-attrs.html
Normal file
@@ -0,0 +1,87 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<input id="i1" placeholder="Enter name" min="0" max="100" step="5" autocomplete="email">
|
||||
<input id="i2" type="file" multiple>
|
||||
<input id="i3">
|
||||
|
||||
<script id="placeholder">
|
||||
{
|
||||
const i1 = document.getElementById('i1');
|
||||
testing.expectEqual('Enter name', i1.placeholder);
|
||||
|
||||
i1.placeholder = 'Updated';
|
||||
testing.expectEqual('Updated', i1.placeholder);
|
||||
|
||||
const i3 = document.getElementById('i3');
|
||||
testing.expectEqual('', i3.placeholder);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="min">
|
||||
{
|
||||
const i1 = document.getElementById('i1');
|
||||
testing.expectEqual('0', i1.min);
|
||||
|
||||
i1.min = '10';
|
||||
testing.expectEqual('10', i1.min);
|
||||
|
||||
const i3 = document.getElementById('i3');
|
||||
testing.expectEqual('', i3.min);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="max">
|
||||
{
|
||||
const i1 = document.getElementById('i1');
|
||||
testing.expectEqual('100', i1.max);
|
||||
|
||||
i1.max = '200';
|
||||
testing.expectEqual('200', i1.max);
|
||||
|
||||
const i3 = document.getElementById('i3');
|
||||
testing.expectEqual('', i3.max);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="step">
|
||||
{
|
||||
const i1 = document.getElementById('i1');
|
||||
testing.expectEqual('5', i1.step);
|
||||
|
||||
i1.step = '0.5';
|
||||
testing.expectEqual('0.5', i1.step);
|
||||
|
||||
const i3 = document.getElementById('i3');
|
||||
testing.expectEqual('', i3.step);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="multiple">
|
||||
{
|
||||
const i2 = document.getElementById('i2');
|
||||
testing.expectEqual(true, i2.multiple);
|
||||
|
||||
i2.multiple = false;
|
||||
testing.expectEqual(false, i2.multiple);
|
||||
|
||||
const i3 = document.getElementById('i3');
|
||||
testing.expectEqual(false, i3.multiple);
|
||||
|
||||
i3.multiple = true;
|
||||
testing.expectEqual(true, i3.multiple);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="autocomplete">
|
||||
{
|
||||
const i1 = document.getElementById('i1');
|
||||
testing.expectEqual('email', i1.autocomplete);
|
||||
|
||||
i1.autocomplete = 'off';
|
||||
testing.expectEqual('off', i1.autocomplete);
|
||||
|
||||
const i3 = document.getElementById('i3');
|
||||
testing.expectEqual('', i3.autocomplete);
|
||||
}
|
||||
</script>
|
||||
@@ -46,7 +46,7 @@
|
||||
testing.expectEqual(5, input.maxLength);
|
||||
input.maxLength = 'banana';
|
||||
testing.expectEqual(0, input.maxLength);
|
||||
testing.expectError('Error: NegativeValueNotAllowed', () => { input.maxLength = -45;});
|
||||
testing.expectError('IndexSizeError: Index or size is negative or greater than the allowed amount', () => { input.maxLength = -45;});
|
||||
|
||||
testing.expectEqual(20, input.size);
|
||||
input.size = 5;
|
||||
@@ -57,9 +57,9 @@
|
||||
|
||||
testing.expectEqual('', input.src);
|
||||
input.src = 'foo'
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/foo', input.src);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/foo', input.src);
|
||||
input.src = '-3'
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/-3', input.src);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/-3', input.src);
|
||||
input.src = ''
|
||||
}
|
||||
</script>
|
||||
@@ -183,7 +183,83 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- <script id="defaultChecked">
|
||||
<script id="selectionchange_event">
|
||||
{
|
||||
const input = document.createElement('input');
|
||||
input.value = 'Hello World';
|
||||
document.body.appendChild(input);
|
||||
|
||||
let eventCount = 0;
|
||||
let lastEvent = null;
|
||||
|
||||
input.addEventListener('selectionchange', (e) => {
|
||||
eventCount++;
|
||||
lastEvent = e;
|
||||
});
|
||||
|
||||
testing.expectEqual(0, eventCount);
|
||||
|
||||
input.setSelectionRange(0, 5);
|
||||
input.select();
|
||||
input.selectionStart = 3;
|
||||
input.selectionEnd = 8;
|
||||
|
||||
let bubbledToBody = false;
|
||||
document.body.addEventListener('selectionchange', () => {
|
||||
bubbledToBody = true;
|
||||
});
|
||||
input.setSelectionRange(1, 4);
|
||||
|
||||
testing.eventually(() => {
|
||||
testing.expectEqual(5, eventCount);
|
||||
testing.expectEqual('selectionchange', lastEvent.type);
|
||||
testing.expectEqual(input, lastEvent.target);
|
||||
testing.expectEqual(true, lastEvent.bubbles);
|
||||
testing.expectEqual(false, lastEvent.cancelable);
|
||||
testing.expectEqual(true, bubbledToBody);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="select_event">
|
||||
{
|
||||
const input = document.createElement('input');
|
||||
input.value = 'Hello World';
|
||||
document.body.appendChild(input);
|
||||
|
||||
let eventCount = 0;
|
||||
let lastEvent = null;
|
||||
|
||||
input.addEventListener('select', (e) => {
|
||||
eventCount++;
|
||||
lastEvent = e;
|
||||
});
|
||||
|
||||
let onselectFired = false;
|
||||
input.onselect = () => { onselectFired = true; };
|
||||
|
||||
let bubbledToBody = false;
|
||||
document.body.addEventListener('select', () => {
|
||||
bubbledToBody = true;
|
||||
});
|
||||
|
||||
testing.expectEqual(0, eventCount);
|
||||
|
||||
input.select();
|
||||
|
||||
testing.eventually(() => {
|
||||
testing.expectEqual(1, eventCount);
|
||||
testing.expectEqual('select', lastEvent.type);
|
||||
testing.expectEqual(input, lastEvent.target);
|
||||
testing.expectEqual(true, lastEvent.bubbles);
|
||||
testing.expectEqual(false, lastEvent.cancelable);
|
||||
testing.expectEqual(true, bubbledToBody);
|
||||
testing.expectEqual(true, onselectFired);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="defaultChecked">
|
||||
testing.expectEqual(true, $('#check1').defaultChecked)
|
||||
testing.expectEqual(false, $('#check2').defaultChecked)
|
||||
testing.expectEqual(true, $('#radio1').defaultChecked)
|
||||
@@ -455,4 +531,4 @@
|
||||
input_checked.defaultChecked = true;
|
||||
testing.expectEqual(false, input_checked.checked);
|
||||
}
|
||||
</script> -->
|
||||
</script>
|
||||
|
||||
283
src/browser/tests/element/html/input_click.html
Normal file
283
src/browser/tests/element/html/input_click.html
Normal file
@@ -0,0 +1,283 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<!-- Checkbox click tests -->
|
||||
<input id="checkbox1" type="checkbox">
|
||||
<input id="checkbox2" type="checkbox" checked>
|
||||
<input id="checkbox_disabled" type="checkbox" disabled>
|
||||
|
||||
<!-- Radio click tests -->
|
||||
<input id="radio1" type="radio" name="clickgroup" checked>
|
||||
<input id="radio2" type="radio" name="clickgroup">
|
||||
<input id="radio3" type="radio" name="clickgroup">
|
||||
<input id="radio_disabled" type="radio" name="clickgroup" disabled>
|
||||
|
||||
<script id="checkbox_click_toggles">
|
||||
{
|
||||
const cb = $('#checkbox1');
|
||||
testing.expectEqual(false, cb.checked);
|
||||
|
||||
cb.click();
|
||||
testing.expectEqual(true, cb.checked);
|
||||
|
||||
cb.click();
|
||||
testing.expectEqual(false, cb.checked);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="checkbox_click_preventDefault_reverts">
|
||||
{
|
||||
const cb = document.createElement('input');
|
||||
cb.type = 'checkbox';
|
||||
testing.expectEqual(false, cb.checked);
|
||||
|
||||
cb.addEventListener('click', (e) => {
|
||||
testing.expectEqual(true, cb.checked, 'checkbox should be checked during click handler');
|
||||
e.preventDefault();
|
||||
});
|
||||
|
||||
cb.click();
|
||||
testing.expectEqual(false, cb.checked, 'checkbox should revert after preventDefault');
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="checkbox_click_events_order">
|
||||
{
|
||||
const cb = document.createElement('input');
|
||||
cb.type = 'checkbox';
|
||||
document.body.appendChild(cb);
|
||||
|
||||
const events = [];
|
||||
|
||||
cb.addEventListener('click', () => events.push('click'));
|
||||
cb.addEventListener('input', () => events.push('input'));
|
||||
cb.addEventListener('change', () => events.push('change'));
|
||||
|
||||
cb.click();
|
||||
|
||||
testing.expectEqual(3, events.length);
|
||||
testing.expectEqual('click', events[0]);
|
||||
testing.expectEqual('input', events[1]);
|
||||
testing.expectEqual('change', events[2]);
|
||||
|
||||
document.body.removeChild(cb);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="checkbox_click_preventDefault_no_input_change">
|
||||
{
|
||||
const cb = document.createElement('input');
|
||||
cb.type = 'checkbox';
|
||||
document.body.appendChild(cb);
|
||||
|
||||
const events = [];
|
||||
|
||||
cb.addEventListener('click', (e) => {
|
||||
events.push('click');
|
||||
e.preventDefault();
|
||||
});
|
||||
cb.addEventListener('input', () => events.push('input'));
|
||||
cb.addEventListener('change', () => events.push('change'));
|
||||
|
||||
cb.click();
|
||||
|
||||
testing.expectEqual(1, events.length, 'only click event should fire');
|
||||
testing.expectEqual('click', events[0]);
|
||||
|
||||
document.body.removeChild(cb);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="checkbox_click_state_visible_in_handler">
|
||||
{
|
||||
const cb = document.createElement('input');
|
||||
cb.type = 'checkbox';
|
||||
cb.checked = true;
|
||||
|
||||
cb.addEventListener('click', (e) => {
|
||||
testing.expectEqual(false, cb.checked, 'should see toggled state in handler');
|
||||
e.preventDefault();
|
||||
testing.expectEqual(false, cb.checked, 'should still be toggled after preventDefault in handler');
|
||||
});
|
||||
|
||||
cb.click();
|
||||
testing.expectEqual(true, cb.checked, 'should revert to original state after handler completes');
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="radio_click_checks_clicked">
|
||||
{
|
||||
const r1 = $('#radio1');
|
||||
const r2 = $('#radio2');
|
||||
|
||||
testing.expectEqual(true, r1.checked);
|
||||
testing.expectEqual(false, r2.checked);
|
||||
|
||||
r2.click();
|
||||
testing.expectEqual(false, r1.checked);
|
||||
testing.expectEqual(true, r2.checked);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="radio_click_preventDefault_reverts">
|
||||
{
|
||||
const r1 = document.createElement('input');
|
||||
r1.type = 'radio';
|
||||
r1.name = 'testgroup';
|
||||
r1.checked = true;
|
||||
|
||||
const r2 = document.createElement('input');
|
||||
r2.type = 'radio';
|
||||
r2.name = 'testgroup';
|
||||
|
||||
document.body.appendChild(r1);
|
||||
document.body.appendChild(r2);
|
||||
|
||||
r2.addEventListener('click', (e) => {
|
||||
testing.expectEqual(false, r1.checked, 'r1 should be unchecked during click handler');
|
||||
testing.expectEqual(true, r2.checked, 'r2 should be checked during click handler');
|
||||
e.preventDefault();
|
||||
});
|
||||
|
||||
r2.click();
|
||||
|
||||
testing.expectEqual(true, r1.checked, 'r1 should be restored after preventDefault');
|
||||
testing.expectEqual(false, r2.checked, 'r2 should revert after preventDefault');
|
||||
|
||||
document.body.removeChild(r1);
|
||||
document.body.removeChild(r2);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="radio_click_events_order">
|
||||
{
|
||||
const r = document.createElement('input');
|
||||
r.type = 'radio';
|
||||
r.name = 'eventtest';
|
||||
document.body.appendChild(r);
|
||||
|
||||
const events = [];
|
||||
|
||||
r.addEventListener('click', () => events.push('click'));
|
||||
r.addEventListener('input', () => events.push('input'));
|
||||
r.addEventListener('change', () => events.push('change'));
|
||||
|
||||
r.click();
|
||||
|
||||
testing.expectEqual(3, events.length);
|
||||
testing.expectEqual('click', events[0]);
|
||||
testing.expectEqual('input', events[1]);
|
||||
testing.expectEqual('change', events[2]);
|
||||
|
||||
document.body.removeChild(r);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="radio_click_already_checked_no_events">
|
||||
{
|
||||
const r = document.createElement('input');
|
||||
r.type = 'radio';
|
||||
r.name = 'alreadytest';
|
||||
r.checked = true;
|
||||
document.body.appendChild(r);
|
||||
|
||||
const events = [];
|
||||
|
||||
r.addEventListener('click', () => events.push('click'));
|
||||
r.addEventListener('input', () => events.push('input'));
|
||||
r.addEventListener('change', () => events.push('change'));
|
||||
|
||||
r.click();
|
||||
|
||||
testing.expectEqual(1, events.length, 'only click event should fire for already-checked radio');
|
||||
testing.expectEqual('click', events[0]);
|
||||
|
||||
document.body.removeChild(r);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="disabled_checkbox_no_click">
|
||||
{
|
||||
const cb = $('#checkbox_disabled');
|
||||
const events = [];
|
||||
|
||||
cb.addEventListener('click', () => events.push('click'));
|
||||
cb.addEventListener('input', () => events.push('input'));
|
||||
cb.addEventListener('change', () => events.push('change'));
|
||||
|
||||
cb.click();
|
||||
|
||||
testing.expectEqual(0, events.length, 'disabled checkbox should not fire any events');
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="disabled_radio_no_click">
|
||||
{
|
||||
const r = $('#radio_disabled');
|
||||
const events = [];
|
||||
|
||||
r.addEventListener('click', () => events.push('click'));
|
||||
r.addEventListener('input', () => events.push('input'));
|
||||
r.addEventListener('change', () => events.push('change'));
|
||||
|
||||
r.click();
|
||||
|
||||
testing.expectEqual(0, events.length, 'disabled radio should not fire any events');
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="input_and_change_are_trusted">
|
||||
{
|
||||
const cb = document.createElement('input');
|
||||
cb.type = 'checkbox';
|
||||
document.body.appendChild(cb);
|
||||
|
||||
let inputEvent = null;
|
||||
let changeEvent = null;
|
||||
|
||||
cb.addEventListener('input', (e) => inputEvent = e);
|
||||
cb.addEventListener('change', (e) => changeEvent = e);
|
||||
|
||||
cb.click();
|
||||
|
||||
testing.expectEqual(true, inputEvent.isTrusted, 'input event should be trusted');
|
||||
testing.expectEqual(true, inputEvent.bubbles, 'input event should bubble');
|
||||
testing.expectEqual(false, inputEvent.cancelable, 'input event should not be cancelable');
|
||||
|
||||
testing.expectEqual(true, changeEvent.isTrusted, 'change event should be trusted');
|
||||
testing.expectEqual(true, changeEvent.bubbles, 'change event should bubble');
|
||||
testing.expectEqual(false, changeEvent.cancelable, 'change event should not be cancelable');
|
||||
|
||||
document.body.removeChild(cb);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="multiple_radios_click_sequence">
|
||||
{
|
||||
const r1 = $('#radio1');
|
||||
const r2 = $('#radio2');
|
||||
const r3 = $('#radio3');
|
||||
|
||||
// Reset to known state
|
||||
r1.checked = true;
|
||||
|
||||
testing.expectEqual(true, r1.checked);
|
||||
testing.expectEqual(false, r2.checked);
|
||||
testing.expectEqual(false, r3.checked);
|
||||
|
||||
r2.click();
|
||||
testing.expectEqual(false, r1.checked);
|
||||
testing.expectEqual(true, r2.checked);
|
||||
testing.expectEqual(false, r3.checked);
|
||||
|
||||
r3.click();
|
||||
testing.expectEqual(false, r1.checked);
|
||||
testing.expectEqual(false, r2.checked);
|
||||
testing.expectEqual(true, r3.checked);
|
||||
|
||||
r1.click();
|
||||
testing.expectEqual(true, r1.checked);
|
||||
testing.expectEqual(false, r2.checked);
|
||||
testing.expectEqual(false, r3.checked);
|
||||
}
|
||||
</script>
|
||||
74
src/browser/tests/element/html/label.html
Normal file
74
src/browser/tests/element/html/label.html
Normal file
@@ -0,0 +1,74 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<label id="l1" for="input1">Name</label>
|
||||
<input id="input1">
|
||||
|
||||
<script id="htmlFor">
|
||||
{
|
||||
const l1 = document.getElementById('l1');
|
||||
testing.expectEqual('input1', l1.htmlFor);
|
||||
|
||||
l1.htmlFor = 'input2';
|
||||
testing.expectEqual('input2', l1.htmlFor);
|
||||
|
||||
const l2 = document.createElement('label');
|
||||
testing.expectEqual('', l2.htmlFor);
|
||||
}
|
||||
</script>
|
||||
|
||||
<label id="l2" for="input1"><span>Name</span></label>
|
||||
<input id="input2" type="text">
|
||||
<input id="input-hidden" type="hidden">
|
||||
<select id="sel1"><option>a</option></select>
|
||||
<button id="btn1">Click</button>
|
||||
<label id="l3"><input id="input3"><span>desc</span></label>
|
||||
<label id="l4"><span>no control here</span></label>
|
||||
<label id="l5"><label id="l5-inner"><input id="input5"></label></label>
|
||||
|
||||
<script id="control">
|
||||
{
|
||||
// for attribute pointing to a text input
|
||||
const l2 = document.getElementById('l2');
|
||||
testing.expectEqual('input1', l2.control.id);
|
||||
|
||||
// for attribute pointing to a non-existent id
|
||||
const lMissing = document.createElement('label');
|
||||
lMissing.htmlFor = 'does-not-exist';
|
||||
testing.expectEqual(null, lMissing.control);
|
||||
|
||||
// for attribute pointing to a hidden input -> not labelable, returns null
|
||||
const lHidden = document.createElement('label');
|
||||
lHidden.htmlFor = 'input-hidden';
|
||||
document.body.appendChild(lHidden);
|
||||
testing.expectEqual(null, lHidden.control);
|
||||
|
||||
// for attribute pointing to a select
|
||||
const lSel = document.createElement('label');
|
||||
lSel.htmlFor = 'sel1';
|
||||
document.body.appendChild(lSel);
|
||||
testing.expectEqual('sel1', lSel.control.id);
|
||||
|
||||
// for attribute pointing to a button
|
||||
const lBtn = document.createElement('label');
|
||||
lBtn.htmlFor = 'btn1';
|
||||
document.body.appendChild(lBtn);
|
||||
testing.expectEqual('btn1', lBtn.control.id);
|
||||
|
||||
// no for attribute: first labelable descendant
|
||||
const l3 = document.getElementById('l3');
|
||||
testing.expectEqual('input3', l3.control.id);
|
||||
|
||||
// no for attribute: no labelable descendant -> null
|
||||
const l4 = document.getElementById('l4');
|
||||
testing.expectEqual(null, l4.control);
|
||||
|
||||
// no for attribute: nested labels, first labelable in tree order
|
||||
const l5 = document.getElementById('l5');
|
||||
testing.expectEqual('input5', l5.control.id);
|
||||
|
||||
// label with no for and not in document -> null
|
||||
const lDetached = document.createElement('label');
|
||||
testing.expectEqual(null, lDetached.control);
|
||||
}
|
||||
</script>
|
||||
23
src/browser/tests/element/html/li.html
Normal file
23
src/browser/tests/element/html/li.html
Normal file
@@ -0,0 +1,23 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<ol>
|
||||
<li id="li1" value="5">Item</li>
|
||||
<li id="li2">Item</li>
|
||||
</ol>
|
||||
|
||||
<script id="value">
|
||||
{
|
||||
const li1 = document.getElementById('li1');
|
||||
testing.expectEqual(5, li1.value);
|
||||
|
||||
li1.value = 10;
|
||||
testing.expectEqual(10, li1.value);
|
||||
|
||||
const li2 = document.getElementById('li2');
|
||||
testing.expectEqual(0, li2.value);
|
||||
|
||||
li2.value = -3;
|
||||
testing.expectEqual(-3, li2.value);
|
||||
}
|
||||
</script>
|
||||
@@ -8,5 +8,79 @@
|
||||
testing.expectEqual('https://lightpanda.io/opensource-browser/15', l2.href);
|
||||
|
||||
l2.href = '/over/9000';
|
||||
testing.expectEqual('http://127.0.0.1:9582/over/9000', l2.href);
|
||||
testing.expectEqual(testing.ORIGIN + 'over/9000', l2.href);
|
||||
|
||||
l2.crossOrigin = 'nope';
|
||||
testing.expectEqual('anonymous', l2.crossOrigin);
|
||||
|
||||
l2.crossOrigin = 'use-Credentials';
|
||||
testing.expectEqual('use-credentials', l2.crossOrigin);
|
||||
|
||||
l2.crossOrigin = '';
|
||||
testing.expectEqual('anonymous', l2.crossOrigin);
|
||||
</script>
|
||||
|
||||
<script id="link-load-event">
|
||||
{
|
||||
// A link with rel=stylesheet and a non-empty href fires a load event when appended to the DOM
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.href = 'https://lightpanda.io/opensource-browser/15';
|
||||
|
||||
testing.async(async () => {
|
||||
const result = await new Promise(resolve => {
|
||||
link.addEventListener('load', ({ bubbles, cancelBubble, cancelable, composed, isTrusted, target }) => {
|
||||
testing.expectEqual(false, bubbles);
|
||||
testing.expectEqual(false, cancelBubble);
|
||||
testing.expectEqual(false, cancelable);
|
||||
testing.expectEqual(false, composed);
|
||||
testing.expectEqual(true, isTrusted);
|
||||
testing.expectEqual(link, target);
|
||||
resolve(true);
|
||||
});
|
||||
document.head.appendChild(link);
|
||||
});
|
||||
testing.expectEqual(true, result);
|
||||
});
|
||||
testing.expectEqual(true, true);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="link-no-load-without-href">
|
||||
{
|
||||
// A link with rel=stylesheet but no href should not fire a load event
|
||||
let fired = false;
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.addEventListener('load', () => { fired = true; });
|
||||
document.head.appendChild(link);
|
||||
testing.eventually(() => testing.expectEqual(false, fired));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="link-no-load-wrong-rel">
|
||||
{
|
||||
// A link without rel=stylesheet should not fire a load event
|
||||
let fired = false;
|
||||
const link = document.createElement('link');
|
||||
link.href = 'https://lightpanda.io/opensource-browser/15';
|
||||
link.addEventListener('load', () => { fired = true; });
|
||||
document.head.appendChild(link);
|
||||
testing.eventually(() => testing.expectEqual(false, fired));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="lazy-href-set">
|
||||
{
|
||||
let result = false;
|
||||
const link = document.createElement("link");
|
||||
link.rel = "stylesheet";
|
||||
link.onload = () => result = true;
|
||||
// Append to DOM,
|
||||
document.head.appendChild(link);
|
||||
// then set href.
|
||||
link.href = 'https://lightpanda.io/opensource-browser/15';
|
||||
|
||||
testing.eventually(() => testing.expectEqual(true, result));
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -50,6 +50,50 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="play_pause_events">
|
||||
{
|
||||
const audio = document.createElement('audio');
|
||||
const events = [];
|
||||
|
||||
audio.addEventListener('play', () => events.push('play'));
|
||||
audio.addEventListener('playing', () => events.push('playing'));
|
||||
audio.addEventListener('pause', () => events.push('pause'));
|
||||
audio.addEventListener('emptied', () => events.push('emptied'));
|
||||
|
||||
// First play: paused -> playing, fires play + playing
|
||||
audio.play();
|
||||
testing.expectEqual('play,playing', events.join(','));
|
||||
|
||||
// Second play: already playing, no events
|
||||
audio.play();
|
||||
testing.expectEqual('play,playing', events.join(','));
|
||||
|
||||
// Pause: playing -> paused, fires pause
|
||||
audio.pause();
|
||||
testing.expectEqual('play,playing,pause', events.join(','));
|
||||
|
||||
// Second pause: already paused, no event
|
||||
audio.pause();
|
||||
testing.expectEqual('play,playing,pause', events.join(','));
|
||||
|
||||
// Third play: resume from pause, fires play + playing (verified in Chrome)
|
||||
audio.play();
|
||||
testing.expectEqual('play,playing,pause,play,playing', events.join(','));
|
||||
|
||||
// Pause again
|
||||
audio.pause();
|
||||
testing.expectEqual('play,playing,pause,play,playing,pause', events.join(','));
|
||||
|
||||
// Load: resets state, fires emptied
|
||||
audio.load();
|
||||
testing.expectEqual('play,playing,pause,play,playing,pause,emptied', events.join(','));
|
||||
|
||||
// Play after load: fires play + playing
|
||||
audio.play();
|
||||
testing.expectEqual('play,playing,pause,play,playing,pause,emptied,play,playing', events.join(','));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="volume_muted">
|
||||
{
|
||||
const audio = document.getElementById('audio1');
|
||||
@@ -194,7 +238,7 @@
|
||||
testing.expectEqual('', audio.src);
|
||||
|
||||
audio.src = 'test.mp3';
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/test.mp3', audio.src);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/test.mp3', audio.src);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -204,7 +248,7 @@
|
||||
testing.expectEqual('', video.poster);
|
||||
|
||||
video.poster = 'poster.jpg';
|
||||
testing.expectEqual('http://127.0.0.1:9582/src/browser/tests/element/html/poster.jpg', video.poster);
|
||||
testing.expectEqual(testing.BASE_URL + 'element/html/poster.jpg', video.poster);
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
51
src/browser/tests/element/html/ol.html
Normal file
51
src/browser/tests/element/html/ol.html
Normal file
@@ -0,0 +1,51 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<ol id="ol1" start="5" reversed type="a">
|
||||
<li>Item</li>
|
||||
</ol>
|
||||
<ol id="ol2">
|
||||
<li>Item</li>
|
||||
</ol>
|
||||
|
||||
<script id="start">
|
||||
{
|
||||
const ol1 = document.getElementById('ol1');
|
||||
testing.expectEqual(5, ol1.start);
|
||||
|
||||
ol1.start = 10;
|
||||
testing.expectEqual(10, ol1.start);
|
||||
|
||||
const ol2 = document.getElementById('ol2');
|
||||
testing.expectEqual(1, ol2.start);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="reversed">
|
||||
{
|
||||
const ol1 = document.getElementById('ol1');
|
||||
testing.expectEqual(true, ol1.reversed);
|
||||
|
||||
ol1.reversed = false;
|
||||
testing.expectEqual(false, ol1.reversed);
|
||||
|
||||
const ol2 = document.getElementById('ol2');
|
||||
testing.expectEqual(false, ol2.reversed);
|
||||
|
||||
ol2.reversed = true;
|
||||
testing.expectEqual(true, ol2.reversed);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="type">
|
||||
{
|
||||
const ol1 = document.getElementById('ol1');
|
||||
testing.expectEqual('a', ol1.type);
|
||||
|
||||
ol1.type = '1';
|
||||
testing.expectEqual('1', ol1.type);
|
||||
|
||||
const ol2 = document.getElementById('ol2');
|
||||
testing.expectEqual('1', ol2.type);
|
||||
}
|
||||
</script>
|
||||
40
src/browser/tests/element/html/optgroup.html
Normal file
40
src/browser/tests/element/html/optgroup.html
Normal file
@@ -0,0 +1,40 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<select>
|
||||
<optgroup id="og1" label="Group 1" disabled>
|
||||
<option>A</option>
|
||||
</optgroup>
|
||||
<optgroup id="og2" label="Group 2">
|
||||
<option>B</option>
|
||||
</optgroup>
|
||||
</select>
|
||||
|
||||
<script id="disabled">
|
||||
{
|
||||
const og1 = document.getElementById('og1');
|
||||
testing.expectEqual(true, og1.disabled);
|
||||
|
||||
og1.disabled = false;
|
||||
testing.expectEqual(false, og1.disabled);
|
||||
|
||||
const og2 = document.getElementById('og2');
|
||||
testing.expectEqual(false, og2.disabled);
|
||||
|
||||
og2.disabled = true;
|
||||
testing.expectEqual(true, og2.disabled);
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="label">
|
||||
{
|
||||
const og1 = document.getElementById('og1');
|
||||
testing.expectEqual('Group 1', og1.label);
|
||||
|
||||
og1.label = 'Updated';
|
||||
testing.expectEqual('Updated', og1.label);
|
||||
|
||||
const og = document.createElement('optgroup');
|
||||
testing.expectEqual('', og.label);
|
||||
}
|
||||
</script>
|
||||
@@ -29,6 +29,12 @@
|
||||
testing.expectEqual('Text 3', $('#opt3').text)
|
||||
</script>
|
||||
|
||||
<script id="text_set">
|
||||
$('#opt1').text = 'New Text 1'
|
||||
testing.expectEqual('New Text 1', $('#opt1').text)
|
||||
testing.expectEqual('New Text 1', $('#opt1').textContent)
|
||||
</script>
|
||||
|
||||
<script id="selected">
|
||||
testing.expectEqual(false, $('#opt1').selected)
|
||||
testing.expectEqual(true, $('#opt2').selected)
|
||||
|
||||
55
src/browser/tests/element/html/picture.html
Normal file
55
src/browser/tests/element/html/picture.html
Normal file
@@ -0,0 +1,55 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<!-- <script id="createElement">
|
||||
{
|
||||
const picture = document.createElement('picture');
|
||||
testing.expectEqual('PICTURE', picture.tagName);
|
||||
testing.expectEqual('[object HTMLPictureElement]', Object.prototype.toString.call(picture));
|
||||
}
|
||||
</script>
|
||||
|
||||
<script id="constructor_type">
|
||||
{
|
||||
const picture = document.createElement('picture');
|
||||
testing.expectEqual(true, picture instanceof HTMLElement);
|
||||
testing.expectEqual(true, picture instanceof Element);
|
||||
testing.expectEqual(true, picture instanceof Node);
|
||||
}
|
||||
</script> -->
|
||||
|
||||
<picture id="inline-picture">
|
||||
<source media="(min-width: 800px)" srcset="large.jpg">
|
||||
<source media="(min-width: 400px)" srcset="medium.jpg">
|
||||
<img src="small.jpg" alt="Test image">
|
||||
</picture>
|
||||
|
||||
<script id="inline_picture">
|
||||
{
|
||||
const picture = document.getElementById('inline-picture');
|
||||
testing.expectEqual('PICTURE', picture.tagName);
|
||||
testing.expectEqual(3, picture.children.length);
|
||||
|
||||
const sources = picture.querySelectorAll('source');
|
||||
testing.expectEqual(2, sources.length);
|
||||
|
||||
// const img = picture.querySelector('img');
|
||||
// testing.expectEqual('IMG', img.tagName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- <script id="appendChild">
|
||||
{
|
||||
const picture = document.createElement('picture');
|
||||
const source = document.createElement('source');
|
||||
const img = document.createElement('img');
|
||||
|
||||
picture.appendChild(source);
|
||||
picture.appendChild(img);
|
||||
|
||||
testing.expectEqual(2, picture.children.length);
|
||||
testing.expectEqual('SOURCE', picture.children[0].tagName);
|
||||
testing.expectEqual('IMG', picture.children[1].tagName);
|
||||
}
|
||||
</script>
|
||||
-->
|
||||
17
src/browser/tests/element/html/quote.html
Normal file
17
src/browser/tests/element/html/quote.html
Normal file
@@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<script src="../../testing.js"></script>
|
||||
|
||||
<blockquote id="q1" cite="https://example.com/source">Quote</blockquote>
|
||||
|
||||
<script id="cite">
|
||||
{
|
||||
const q1 = document.getElementById('q1');
|
||||
testing.expectEqual('https://example.com/source', q1.cite);
|
||||
|
||||
q1.cite = 'https://example.com/other';
|
||||
testing.expectEqual('https://example.com/other', q1.cite);
|
||||
|
||||
const q2 = document.createElement('blockquote');
|
||||
testing.expectEqual('', q2.cite);
|
||||
}
|
||||
</script>
|
||||
0
src/browser/tests/element/html/script/empty.js
Normal file
0
src/browser/tests/element/html/script/empty.js
Normal file
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user