Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
029f3f6c58 | ||
|
|
1f685296de | ||
|
|
e0accea7ab | ||
|
|
c768f5fbe6 | ||
|
|
2db50808d5 | ||
|
|
b7a55f7fd7 | ||
|
|
7fb9d765be | ||
|
|
1f570a0d8f | ||
|
|
d2a8ee36f7 | ||
|
|
f148bee88b | ||
|
|
199043e4bc | ||
|
|
4f73d99f64 | ||
|
|
3050e93555 | ||
|
|
fcc2b9902a | ||
|
|
30ead01178 | ||
|
|
393ed3ebca | ||
|
|
870b7ffb93 | ||
|
|
e2f816b6c1 | ||
|
|
c22332a7ce | ||
|
|
8199ca5a18 | ||
|
|
dc549e64bd | ||
|
|
e88b8c90d9 | ||
|
|
766aea14b9 | ||
|
|
653a7c0f0c | ||
|
|
42637458c9 | ||
|
|
a6caf93e8b | ||
|
|
b55fd857e1 | ||
|
|
65c51e865a | ||
|
|
8ecf460140 | ||
|
|
8ee4efdee3 | ||
|
|
5ac5fcc212 | ||
|
|
58c24f615d | ||
|
|
d1cbcda5d5 | ||
|
|
c30ed35c67 | ||
|
|
dea364c2a6 | ||
|
|
eabba1ecec | ||
|
|
db02b9fb94 | ||
|
|
4d88823c2d | ||
|
|
933530a96c | ||
|
|
43f4e0d15d | ||
|
|
21e522cba7 | ||
|
|
d8bfa10b43 | ||
|
|
7a000a80f0 | ||
|
|
866155d907 | ||
|
|
72439d4ec9 | ||
|
|
51f079696a | ||
|
|
abe3368115 | ||
|
|
16d357364d | ||
|
|
2d505588c7 | ||
|
|
a9ab551ca2 | ||
|
|
075d6aba2d | ||
|
|
a1f571b2d8 | ||
|
|
d4eca86ec6 | ||
|
|
44a208aed5 | ||
|
|
ccc3613c83 | ||
|
|
fd309e0aab | ||
|
|
3d06e0cb57 | ||
|
|
dbf5cfe0a3 | ||
|
|
0b66f81bfc | ||
|
|
35a85c18bd | ||
|
|
e116f7e9ec | ||
|
|
cbf18d482d | ||
|
|
d11a52992e | ||
|
|
056f2a0b5f | ||
|
|
50897e1164 | ||
|
|
db001beeb5 | ||
|
|
301b0d526b | ||
|
|
c474cd5c6c | ||
|
|
0bcb45270f | ||
|
|
01063423f6 | ||
|
|
3af97e461d | ||
|
|
c24f72b34c | ||
|
|
39e0d48b3e | ||
|
|
73fe1f4b64 | ||
|
|
886131319c | ||
|
|
05f19f05c4 | ||
|
|
481e8d46cf | ||
|
|
00f843fb4b | ||
|
|
3652871330 | ||
|
|
592d70bb1a | ||
|
|
d79ed7df68 | ||
|
|
31f303b192 | ||
|
|
ef6962d7c7 | ||
|
|
adc4dd19b7 | ||
|
|
d823aea175 | ||
|
|
e1d85e66be | ||
|
|
0a106da544 | ||
|
|
b57cdb2561 | ||
|
|
64a84b3d56 | ||
|
|
ae3a90779b | ||
|
|
f76f47b1f9 | ||
|
|
589fc24f73 | ||
|
|
e9397174dc | ||
|
|
0affd69adf | ||
|
|
154f83e728 | ||
|
|
a1b0b072f7 | ||
|
|
d56761eb08 | ||
|
|
aad3152b35 | ||
|
|
2399a618c7 | ||
|
|
37f2d937d8 | ||
|
|
a3b4dd0326 | ||
|
|
465bef91e8 | ||
|
|
c29843063e | ||
|
|
cab17434f9 | ||
|
|
a7b3eb317f | ||
|
|
b0c0b5c9a4 | ||
|
|
20186ac94c | ||
|
|
2f0b277481 | ||
|
|
1bd21f2625 | ||
|
|
cb9421d89c | ||
|
|
5084353afe | ||
|
|
430806fbf9 | ||
|
|
18456f2293 | ||
|
|
bd61f93174 | ||
|
|
677103a1f1 | ||
|
|
cc65cae4b2 | ||
|
|
60f42c4d40 | ||
|
|
8f93a1b55a | ||
|
|
926d1cbeba | ||
|
|
930ae56f40 | ||
|
|
0b2003d9f8 | ||
|
|
f5d1c31b3b | ||
|
|
1f1380cc28 | ||
|
|
a6b07558ca | ||
|
|
ccd26cbb71 | ||
|
|
8b4d86692a | ||
|
|
a4f9e0b94b | ||
|
|
7544a8a5c6 | ||
|
|
4acc969e1e | ||
|
|
897a8e40bb | ||
|
|
31fcbe99a9 | ||
|
|
695b56c3cb | ||
|
|
d1b9a9bffd | ||
|
|
c9350aa8bd | ||
|
|
579fb0d843 | ||
|
|
4ca9feb252 | ||
|
|
d13bc84232 | ||
|
|
05bdd275d1 | ||
|
|
7bc80f2b9e | ||
|
|
919c76befa | ||
|
|
8e296f2eb8 | ||
|
|
511a02312d | ||
|
|
05834af874 | ||
|
|
3988a81c31 | ||
|
|
de420cd615 | ||
|
|
3120f47b50 | ||
|
|
a798114de0 | ||
|
|
e14e298ad4 | ||
|
|
f033a40e8e | ||
|
|
1101573d20 | ||
|
|
f881a4b8a5 | ||
|
|
a0821468e9 | ||
|
|
ad9fdb16c2 | ||
|
|
2f96db8b96 | ||
|
|
84bebe02cb | ||
|
|
caa555986a | ||
|
|
f0b819dc33 | ||
|
|
e85e429ba1 | ||
|
|
cfa8f69ad5 | ||
|
|
51f71689fa | ||
|
|
b025f519be | ||
|
|
130cb7055a | ||
|
|
4bd48a65bb | ||
|
|
51645b284a | ||
|
|
1a0693e72a | ||
|
|
557f244991 | ||
|
|
16a5a79ddb | ||
|
|
28665385cc | ||
|
|
766262ca1a | ||
|
|
b334680ee7 | ||
|
|
58b4d1562d | ||
|
|
c833716723 | ||
|
|
446bd84742 | ||
|
|
8bc7fe7aeb | ||
|
|
3765e8f8c0 | ||
|
|
50811bde7a | ||
|
|
369ab0bf1e | ||
|
|
6cf69da69e | ||
|
|
90eb7c7bb5 | ||
|
|
d22a56d306 | ||
|
|
0c1d6b48df | ||
|
|
14500596d3 | ||
|
|
b7f366efcd | ||
|
|
08df445cae | ||
|
|
0d2055dd01 | ||
|
|
52f8a99654 | ||
|
|
b67c1466a5 | ||
|
|
16cfdb555e | ||
|
|
d75bd386aa | ||
|
|
fa02679936 | ||
|
|
f89a481c9c | ||
|
|
7041ac3648 | ||
|
|
edd8c5488b | ||
|
|
5628d78cc0 | ||
|
|
ee78156071 | ||
|
|
9c3b0d2100 | ||
|
|
0ff7d8ad47 | ||
|
|
44c5dab300 | ||
|
|
7879182446 | ||
|
|
c6c3973a72 | ||
|
|
71f82ed717 | ||
|
|
4b47dc19ce | ||
|
|
a1c9b70b2e | ||
|
|
2e68c54dbe | ||
|
|
efbd659ccd | ||
|
|
cab7d62b2e | ||
|
|
33a1747a65 | ||
|
|
7fdf69599b | ||
|
|
808ccb9266 | ||
|
|
e0e210bce9 | ||
|
|
47b1dd23d3 | ||
|
|
1093d6df85 | ||
|
|
547a879414 | ||
|
|
8fa8493c82 | ||
|
|
1ef60bf507 | ||
|
|
6c3c3d9d6d | ||
|
|
5d09b68843 | ||
|
|
17898607d1 | ||
|
|
97f312c3d3 | ||
|
|
f3ac3f1815 | ||
|
|
a23f5d792d | ||
|
|
f2227ad66a | ||
|
|
f8542e56db | ||
|
|
80757b86b1 | ||
|
|
430b7028ab | ||
|
|
30648dbf97 | ||
|
|
bfe8d76db4 | ||
|
|
fcc5d26faa | ||
|
|
ffe5cba399 | ||
|
|
552f76766b | ||
|
|
7494a7f9e1 | ||
|
|
9aa2bf7da4 | ||
|
|
1ab86f2009 | ||
|
|
646a67d19d | ||
|
|
aafccd5645 | ||
|
|
dd1362debe | ||
|
|
6790925928 | ||
|
|
0d7e616753 | ||
|
|
6eb6bde5bb | ||
|
|
b39e52487c | ||
|
|
0a079a8a55 | ||
|
|
687d6be704 | ||
|
|
44f2933897 | ||
|
|
23e86c0398 | ||
|
|
52a9289c5b | ||
|
|
2bb07a2e5a | ||
|
|
498481b238 | ||
|
|
0bd86b28ac | ||
|
|
c1dcfd5b7f | ||
|
|
d6dbefeb6d | ||
|
|
62e98c02fd | ||
|
|
80f2f33423 | ||
|
|
a379de544a | ||
|
|
bfb36c9633 | ||
|
|
9f32bb135b | ||
|
|
d2a668e3ee | ||
|
|
9e25f7b033 | ||
|
|
b4d9fc1967 | ||
|
|
bec4782a38 | ||
|
|
141fa7dadb | ||
|
|
1ef930557b | ||
|
|
0bd7ee94fd | ||
|
|
6a456e64f0 | ||
|
|
8c125db804 | ||
|
|
1c4b1e6263 | ||
|
|
67aea6a3b2 | ||
|
|
70fa01a640 | ||
|
|
c037bd1376 | ||
|
|
ecec383f2f | ||
|
|
6ec4f7319c | ||
|
|
865a7b83b8 | ||
|
|
6b2b5e6e92 | ||
|
|
0318a8c836 | ||
|
|
b88e2ab4f8 | ||
|
|
958a48f23d | ||
|
|
496f687d85 | ||
|
|
b7133fb6c1 | ||
|
|
93bb1ba9a1 | ||
|
|
7833091e2c | ||
|
|
37fb176ea1 | ||
|
|
166c2eb72c | ||
|
|
4ec49e1308 | ||
|
|
74d42a926c | ||
|
|
c88b4f1750 | ||
|
|
5047d95cf4 | ||
|
|
c364b3f796 | ||
|
|
d3739bcba0 | ||
|
|
7f958275a9 | ||
|
|
460132ff39 | ||
|
|
f72bce37b6 | ||
|
|
977d6a46a4 | ||
|
|
1d441e42f5 | ||
|
|
3c889288f8 | ||
|
|
ec4e035618 | ||
|
|
428c6b0e2e | ||
|
|
a08e59248d | ||
|
|
2f6da4fe11 | ||
|
|
db22404415 | ||
|
|
27cc61d2cf | ||
|
|
b6a1ba0b59 | ||
|
|
878e23d43f | ||
|
|
0126fd6c66 | ||
|
|
3b2179fb10 | ||
|
|
add685257b | ||
|
|
4226159f5d | ||
|
|
2ecb67e082 | ||
|
|
cd59d57db9 | ||
|
|
1bbe210f4f | ||
|
|
ab91a56da6 | ||
|
|
4ad315f964 | ||
|
|
e4c3fc8b05 | ||
|
|
51f7a42d3e | ||
|
|
c82b7fea7c | ||
|
|
f31ca89b4f | ||
|
|
f0f40894d2 | ||
|
|
34b7f9110a | ||
|
|
97791ed21a | ||
|
|
f7939a5fdc | ||
|
|
aec53eb498 | ||
|
|
d779dd102b | ||
|
|
9c24785b11 | ||
|
|
f43ce5cb5b | ||
|
|
7b5415a5f1 | ||
|
|
8819437067 | ||
|
|
3d12645d9c | ||
|
|
5fe781de6c | ||
|
|
b505953d0a | ||
|
|
a390593841 | ||
|
|
dad4ce0aa4 | ||
|
|
7bb7939a4a | ||
|
|
b454e9b4cb | ||
|
|
abd132951f | ||
|
|
e9d7942e5e | ||
|
|
3cd6908d78 | ||
|
|
2ce2f15fcf | ||
|
|
027059fcb8 | ||
|
|
8d2c4b8284 | ||
|
|
5c3c565174 | ||
|
|
e648ecd8b8 | ||
|
|
b87934da1a | ||
|
|
a2bde12926 | ||
|
|
f2dd2cf7fa | ||
|
|
d1818800c6 | ||
|
|
3de4b3771d | ||
|
|
05682be587 | ||
|
|
d52d6d900d | ||
|
|
fd8cda9ea8 | ||
|
|
c65b8ff1b9 | ||
|
|
13a197e80d | ||
|
|
fe45508297 | ||
|
|
c517468bec | ||
|
|
87c677739e | ||
|
|
7d75dad6a7 | ||
|
|
e633b8ffbf | ||
|
|
715b51a4dc | ||
|
|
72fb41d69d | ||
|
|
c450f4ac2d | ||
|
|
1954fada4e | ||
|
|
1100d306de | ||
|
|
c6baf5d3f9 | ||
|
|
b7b34d7b43 | ||
|
|
f7c8f31fbb | ||
|
|
7fd233a4f4 | ||
|
|
cb1bb48c4c | ||
|
|
e28863f38a | ||
|
|
1bb949217a | ||
|
|
0b95398f2d | ||
|
|
9337b4c9ea | ||
|
|
b5039c76f8 | ||
|
|
1432e968bc | ||
|
|
45b0ae836a | ||
|
|
b9d65e39b1 | ||
|
|
1406306407 | ||
|
|
278b146062 | ||
|
|
d6b0ff7b13 | ||
|
|
c95a41dd01 | ||
|
|
12710c58a7 | ||
|
|
a8990bbe3a | ||
|
|
a20ae242de | ||
|
|
ebbfea5c20 | ||
|
|
613f8b76bb | ||
|
|
00485a6889 | ||
|
|
39509478b6 | ||
|
|
bacf6f2869 | ||
|
|
f2933ba4b4 | ||
|
|
9a6058fedb | ||
|
|
fb487ea622 | ||
|
|
73246c88a1 | ||
|
|
5bcf7d7b79 | ||
|
|
bda50285af | ||
|
|
92643a1355 | ||
|
|
a4228adf74 | ||
|
|
104d95d5ab | ||
|
|
496ab8722a | ||
|
|
ca45f62585 | ||
|
|
aa82aaf02c | ||
|
|
766c51ecde | ||
|
|
00d4b9aaac | ||
|
|
d0c039b37b | ||
|
|
5cf0c60b88 | ||
|
|
15214490af | ||
|
|
fa434957b7 | ||
|
|
c21d0cca09 | ||
|
|
a05b5e8610 | ||
|
|
275d8691cb | ||
|
|
462bbb4298 | ||
|
|
ee18a63e0c | ||
|
|
77d37f071a | ||
|
|
2869113d7d | ||
|
|
0f0f9e6945 | ||
|
|
07048d2b5f | ||
|
|
d9a4efe2b2 | ||
|
|
d93b9b2670 | ||
|
|
f2f1941a30 | ||
|
|
a07241a0cb | ||
|
|
a343c4a530 | ||
|
|
f04ff1073e | ||
|
|
920b4c4426 | ||
|
|
510fb3c4f6 | ||
|
|
3972d57297 | ||
|
|
804be34a3e | ||
|
|
0653f3feb8 | ||
|
|
3337e96cfa | ||
|
|
08cbf296af | ||
|
|
5eb90e17c9 | ||
|
|
b55e04ba77 | ||
|
|
1c746e0bb8 | ||
|
|
4e163a032f | ||
|
|
d9956e60eb | ||
|
|
83b4fe54c7 | ||
|
|
abecdaa5cc | ||
|
|
a4c0498e5b | ||
|
|
2d8d5aa728 | ||
|
|
1eebef173f | ||
|
|
76979c6150 | ||
|
|
4ebca7f077 | ||
|
|
d2971fcdb9 | ||
|
|
1416c5d017 | ||
|
|
8b5cf72356 | ||
|
|
c48288f9e6 | ||
|
|
b419f88571 | ||
|
|
3f5667d62a | ||
|
|
7abb0ace5a | ||
|
|
39adaef4c4 | ||
|
|
388afd0b16 | ||
|
|
5f2faaad61 | ||
|
|
aaf30db257 | ||
|
|
d4c775828f | ||
|
|
cbf85313af | ||
|
|
0b7f9cd2cb | ||
|
|
e0620bcca0 | ||
|
|
97f5481ec7 | ||
|
|
225c90f556 | ||
|
|
51ce9c61ef | ||
|
|
c72170f19c | ||
|
|
111ab724e5 | ||
|
|
23c3cead89 | ||
|
|
945c4209e8 | ||
|
|
7574085213 | ||
|
|
3fba26ddb7 | ||
|
|
bbcc56c800 | ||
|
|
cb794b5719 | ||
|
|
931733ba16 | ||
|
|
52fe76c9c6 | ||
|
|
7f5265cc92 | ||
|
|
7f4b7f2a03 | ||
|
|
34ede4b799 | ||
|
|
d5c28c3097 | ||
|
|
31de1b934d | ||
|
|
45f1202b9d | ||
|
|
b4f0ede7b7 | ||
|
|
df39f78d20 | ||
|
|
b7e94ff67c | ||
|
|
8b981dcf36 | ||
|
|
f702d2300b | ||
|
|
4edbb8a73a | ||
|
|
98f584a851 | ||
|
|
8b438c8c1b | ||
|
|
d18cfb4849 | ||
|
|
b04c1440b5 | ||
|
|
5fa16115fd | ||
|
|
795eaa50c2 | ||
|
|
3da2075539 | ||
|
|
a87063f6e9 | ||
|
|
75cab68281 | ||
|
|
1abc37f388 | ||
|
|
24c8525360 | ||
|
|
2f4fb16e94 | ||
|
|
3e8d5fb87c | ||
|
|
7b438bae34 | ||
|
|
cb4cc16760 | ||
|
|
aca620e460 | ||
|
|
89db9c354a | ||
|
|
fc0134a3a8 | ||
|
|
2477b5417c | ||
|
|
92483728d0 | ||
|
|
ba0ec1f420 | ||
|
|
bdcaa2ef76 | ||
|
|
d1d8f1dd15 | ||
|
|
66d08d05de | ||
|
|
bb8912dd57 | ||
|
|
8ce69023af | ||
|
|
f8350e1d62 | ||
|
|
804cdbd789 | ||
|
|
f022332595 | ||
|
|
ba509584b7 | ||
|
|
787877d2c7 | ||
|
|
0b269f78a4 | ||
|
|
7a11137aed | ||
|
|
1d0231bc03 | ||
|
|
8b62ba8e7e | ||
|
|
4e0625721e | ||
|
|
3529d43b91 | ||
|
|
93a636589d | ||
|
|
eba609ae73 | ||
|
|
8c60a3a8bc | ||
|
|
939deabb5b | ||
|
|
2ec32f5537 | ||
|
|
124e9d5937 | ||
|
|
b064c9ff86 | ||
|
|
a9a5cafcac | ||
|
|
2db9d5e513 | ||
|
|
e8156243d0 | ||
|
|
e9c73693ce | ||
|
|
a474cd8cee | ||
|
|
10ea68547c | ||
|
|
00d9d4d005 | ||
|
|
d02d8959f6 | ||
|
|
5a5bec28c4 | ||
|
|
4ce51b3659 | ||
|
|
cf29632261 | ||
|
|
ecdb33460d | ||
|
|
52198a0a3c | ||
|
|
185cdc51fb | ||
|
|
1a9a553523 | ||
|
|
fc6a70793f | ||
|
|
fba1328e5f | ||
|
|
a45e29578c | ||
|
|
c1cbbed05c | ||
|
|
d95abf2499 | ||
|
|
4316b766e2 | ||
|
|
8800a55eed | ||
|
|
48dfd2d99e | ||
|
|
cb971955ae | ||
|
|
deb593c1b6 | ||
|
|
3b3637009d | ||
|
|
dc50d41928 | ||
|
|
ca334d7585 | ||
|
|
57a80ad33d | ||
|
|
a05ad13e67 | ||
|
|
247919a24b | ||
|
|
9b43f07372 | ||
|
|
af8fb22438 | ||
|
|
fc4e82c26d | ||
|
|
3b305b5b86 | ||
|
|
456ea946e7 | ||
|
|
6c770630d8 | ||
|
|
8f4598b9b8 | ||
|
|
64c06ec430 | ||
|
|
29aae4f55b | ||
|
|
fb12bda5fa | ||
|
|
7348aaf9ce | ||
|
|
8948507b6f | ||
|
|
2dbb9a23e3 | ||
|
|
11867b3bb2 | ||
|
|
0f82ab15ec | ||
|
|
80ae098323 | ||
|
|
fa64a5ce52 | ||
|
|
870e2f6b9b | ||
|
|
26c09733f8 | ||
|
|
2a80e586ba | ||
|
|
9f20fd6196 | ||
|
|
94bcc7eccb | ||
|
|
f62b2f807c | ||
|
|
374d2804ad | ||
|
|
c0f906ae7e | ||
|
|
92e2ac1ce5 | ||
|
|
e81fb33ffe | ||
|
|
9a65d5d086 | ||
|
|
61d5a5fefc | ||
|
|
75e961d281 | ||
|
|
93e992f128 | ||
|
|
7ab30af944 | ||
|
|
6296fc4366 | ||
|
|
147c7cdf3a | ||
|
|
18a276a44e | ||
|
|
a20bbfdf29 | ||
|
|
980cb60f1b | ||
|
|
2956c86f88 | ||
|
|
c46077af67 | ||
|
|
e5ca49962e | ||
|
|
f5c5684ac8 | ||
|
|
6a72711aa0 | ||
|
|
1ed4a5abd4 | ||
|
|
db57619bca | ||
|
|
0f4075ce38 | ||
|
|
ad5902cdc6 | ||
|
|
ce4a602270 | ||
|
|
5e352e60e9 | ||
|
|
37147a69d4 | ||
|
|
ec5d84d3f7 | ||
|
|
0b949d55b9 | ||
|
|
25f14ee2b3 | ||
|
|
7057c34f01 | ||
|
|
d932f05d04 | ||
|
|
e9f8e99ac5 | ||
|
|
0bdc9fa6a3 | ||
|
|
688b35fa41 | ||
|
|
2e38591943 | ||
|
|
568ea5dc04 | ||
|
|
4f9d3ae1d1 | ||
|
|
9bd7e36597 | ||
|
|
fdfdcb4b16 | ||
|
|
50e16e1b57 | ||
|
|
77d8cdddad | ||
|
|
662f95d35d | ||
|
|
ecb74cd31e | ||
|
|
f40ef03b58 | ||
|
|
458eec0e27 | ||
|
|
3751cb23fc | ||
|
|
399e9a0262 | ||
|
|
d6124119f7 | ||
|
|
74e472338d | ||
|
|
e93a60be2c | ||
|
|
71f4397880 | ||
|
|
a1328cb321 | ||
|
|
f8b8f8e61b | ||
|
|
6facf72998 | ||
|
|
77508ea2fc | ||
|
|
0df1ef1e9d | ||
|
|
289caff882 | ||
|
|
bdb3b58cce | ||
|
|
0c379c5495 | ||
|
|
fcf6369356 | ||
|
|
fc36073654 | ||
|
|
131566750d | ||
|
|
540e017074 | ||
|
|
4881480679 | ||
|
|
be13d563c4 | ||
|
|
a5befda7dc | ||
|
|
fe82f36533 | ||
|
|
22de6889d9 | ||
|
|
d0a520ce17 | ||
|
|
aa35b13ad3 | ||
|
|
738b883f3b | ||
|
|
9ea9a4ac4b | ||
|
|
db697d0a85 | ||
|
|
3c75849434 | ||
|
|
2b5e3013ff | ||
|
|
951eefb7b8 | ||
|
|
a68d37452b | ||
|
|
c8653e67dc | ||
|
|
660f25656c | ||
|
|
804efb4d23 | ||
|
|
8932413c2d | ||
|
|
8108407478 | ||
|
|
9de4b167e7 | ||
|
|
c9073bb4bd | ||
|
|
f9f72e6a50 | ||
|
|
feb0bd7d3c | ||
|
|
0eac4c66ee | ||
|
|
aea8c1390b | ||
|
|
893d2e66ab | ||
|
|
e88a11ce21 | ||
|
|
3a8e040212 | ||
|
|
37e15ac786 | ||
|
|
c3fc719e82 | ||
|
|
02750c9b5c | ||
|
|
0e80915d58 | ||
|
|
89f8701855 | ||
|
|
ff95c13f84 | ||
|
|
c38113c9b8 | ||
|
|
c97117db5d | ||
|
|
999c250216 | ||
|
|
6d6f18a877 | ||
|
|
8e8976b9bc | ||
|
|
f4190d22fb | ||
|
|
92376d58b8 | ||
|
|
fb192b8657 | ||
|
|
3e9b15eed3 | ||
|
|
561e5614c5 | ||
|
|
04d812382b | ||
|
|
49d4c5120e | ||
|
|
8aaaea0b8f | ||
|
|
3c46c72bba | ||
|
|
d52d7b57a6 | ||
|
|
cadebaaa0e | ||
|
|
79be6c8252 | ||
|
|
35ac22c74f | ||
|
|
3ec89713bc | ||
|
|
7cbaaec734 | ||
|
|
46a5ca2a1e | ||
|
|
668a6c79d9 | ||
|
|
3692863830 | ||
|
|
6478ed21bb | ||
|
|
25f11dbe1d | ||
|
|
16ee1235d3 | ||
|
|
fed44cef5e | ||
|
|
4ce35b8ff0 | ||
|
|
f6dc218ae7 | ||
|
|
da37ddfdfb | ||
|
|
230d4bc443 | ||
|
|
61254d2ee3 | ||
|
|
b28f700600 | ||
|
|
691077d754 | ||
|
|
7d0c0b6ba2 | ||
|
|
3d42d93ef1 | ||
|
|
d5c5132662 | ||
|
|
ce29d036ad | ||
|
|
c0e00d40f7 | ||
|
|
9678041502 | ||
|
|
154b9330d4 | ||
|
|
bc907fdd63 | ||
|
|
93983f88af | ||
|
|
72a537ce2e | ||
|
|
f06c7dbe70 | ||
|
|
3e502fa3a9 | ||
|
|
d3e257f759 | ||
|
|
69c1000063 | ||
|
|
f797ec55c5 | ||
|
|
7b5c9a5581 | ||
|
|
41d7d7834d | ||
|
|
785f75a39a | ||
|
|
8e3cc67ce2 | ||
|
|
fae90cc85e | ||
|
|
2ed44e43f7 | ||
|
|
53cf844fd6 | ||
|
|
6aa36b6738 | ||
|
|
5cf19c61cc | ||
|
|
5a9fccf631 | ||
|
|
adf9113ab3 | ||
|
|
a3c204f44f | ||
|
|
75d4d13737 | ||
|
|
549385077f | ||
|
|
f3b33c9b48 | ||
|
|
be0b432a00 | ||
|
|
1a60ee6bbe | ||
|
|
c6617beb6d | ||
|
|
718b2f369b | ||
|
|
a823f81b50 | ||
|
|
4cd8683e73 | ||
|
|
27fb8103a3 | ||
|
|
53ac813eb5 | ||
|
|
60f70db7b4 | ||
|
|
050d24fcb7 | ||
|
|
04b9ead22e | ||
|
|
f4f455606f | ||
|
|
62f5a4fe87 | ||
|
|
1a424c0762 | ||
|
|
c5f74ceafc | ||
|
|
ace3e0b3ac | ||
|
|
ba24edc7fe | ||
|
|
8c1927fdf7 | ||
|
|
3c3ac25101 | ||
|
|
adeb3bf53f | ||
|
|
588e32a43d | ||
|
|
57e12261af | ||
|
|
797984c5d3 | ||
|
|
6d49648580 | ||
|
|
4d6bc91650 | ||
|
|
2fdf8a3740 | ||
|
|
f4ccc2d924 | ||
|
|
bda9501e63 | ||
|
|
d4ea9bf1bd | ||
|
|
6f4aa264eb | ||
|
|
f299c73c4d | ||
|
|
1d05aa10eb | ||
|
|
ca2426a800 | ||
|
|
fbea142bbb | ||
|
|
0027752654 | ||
|
|
d64fa0e0ec | ||
|
|
696cbca55a | ||
|
|
92f3c06f51 | ||
|
|
3898681d97 | ||
|
|
ba251d57eb | ||
|
|
efd7c3901b | ||
|
|
e6c9c213b5 | ||
|
|
bd5373f57b | ||
|
|
f67d6dbfc5 | ||
|
|
efbec14d24 | ||
|
|
1c8095d40e | ||
|
|
7807f875f2 | ||
|
|
fdd3fd2b52 | ||
|
|
77863f97be | ||
|
|
1d88ca84f2 | ||
|
|
62cd515a9e | ||
|
|
a1e18ec335 | ||
|
|
dca1573293 | ||
|
|
04d28cbe01 | ||
|
|
234418babd | ||
|
|
e570ee0236 | ||
|
|
45745dc368 | ||
|
|
15ec573ed1 | ||
|
|
23075932b8 | ||
|
|
94755d4cc0 | ||
|
|
2c2d76137b | ||
|
|
b8fd6421fa | ||
|
|
8dfe186e8a | ||
|
|
4ad3c7367d | ||
|
|
350f3b3c5e | ||
|
|
bb830fbae5 | ||
|
|
03b712a917 | ||
|
|
ced204bfde | ||
|
|
dd970c2ca7 | ||
|
|
1cccd8c254 | ||
|
|
6f399af544 | ||
|
|
7437118051 | ||
|
|
656cce0159 | ||
|
|
20778f5045 | ||
|
|
579dd93d6d | ||
|
|
af86b50141 | ||
|
|
395111ac07 | ||
|
|
9c358bb230 | ||
|
|
5cdb62ca1c | ||
|
|
6204164408 | ||
|
|
35757ca822 | ||
|
|
7ff1f639ce | ||
|
|
6c5ee84fe4 | ||
|
|
1653e5d018 | ||
|
|
edb0cd580f | ||
|
|
94f28d2ee8 | ||
|
|
3064866e2b | ||
|
|
3fe03007d2 | ||
|
|
2c9fe492b4 | ||
|
|
000c3d62ab | ||
|
|
83af1d7d2d | ||
|
|
176b156151 | ||
|
|
783e7c38ce | ||
|
|
16b36dab8e | ||
|
|
ebaaf51c22 | ||
|
|
1947402d9a | ||
|
|
61fcbc7003 | ||
|
|
562d2c3085 | ||
|
|
7b4a5ee22e | ||
|
|
9ac157e802 | ||
|
|
aac0d5d320 | ||
|
|
4b42f4cedb | ||
|
|
758ed90bb7 | ||
|
|
6378e49a96 | ||
|
|
ceb716d2ab | ||
|
|
f43e582a78 | ||
|
|
1aafb67cbd | ||
|
|
81af9852a8 | ||
|
|
993b5ece9c | ||
|
|
cd60ab8cbe | ||
|
|
c278618afd | ||
|
|
94a14c5f7e | ||
|
|
47b2f2bb12 | ||
|
|
8d00ac57c7 | ||
|
|
85f1f4597e | ||
|
|
3989a8a217 | ||
|
|
72f8a9def9 | ||
|
|
945bc002f2 | ||
|
|
80e9a8decb | ||
|
|
9ee120f765 | ||
|
|
b73bb3971e | ||
|
|
87c533666d | ||
|
|
69c38b489a | ||
|
|
f7ef7a2080 | ||
|
|
846a3fd685 | ||
|
|
5bcede498d | ||
|
|
bd34c38701 | ||
|
|
60fa8d2239 | ||
|
|
c7527b24df | ||
|
|
7755277877 | ||
|
|
72db1b21f4 | ||
|
|
fec198e7b3 | ||
|
|
2d0e7ae281 | ||
|
|
e8a889c247 | ||
|
|
68edc0b6dc | ||
|
|
a8a7e3ace9 | ||
|
|
8ea62f4b23 | ||
|
|
d7950924a8 | ||
|
|
dd5c7b22be | ||
|
|
5f1eaed12b | ||
|
|
b289983071 | ||
|
|
1f23fa6359 | ||
|
|
94d14a87aa | ||
|
|
4b1c3ee381 | ||
|
|
753c12bcac | ||
|
|
9d53f74782 | ||
|
|
d16515a5c4 | ||
|
|
015a6c8536 | ||
|
|
373f25db76 | ||
|
|
a09916fcb8 | ||
|
|
11522c8426 | ||
|
|
dedb9c7f55 | ||
|
|
ab9c269240 | ||
|
|
a22cc50990 | ||
|
|
b2eb443b43 | ||
|
|
94e1a6543c | ||
|
|
bc009d444e | ||
|
|
1ab895bd59 | ||
|
|
772a2f424b | ||
|
|
55120452c7 | ||
|
|
0dd5ae13a9 | ||
|
|
f56f88b1cb | ||
|
|
c225821a44 | ||
|
|
e8203dd69f | ||
|
|
ffb9c3d95e | ||
|
|
feaa767632 | ||
|
|
425976bb82 | ||
|
|
76fa9940db | ||
|
|
80ed3d606d | ||
|
|
a106a6e10b | ||
|
|
be8309b503 | ||
|
|
f23b92c79f | ||
|
|
21f9511a1e | ||
|
|
82d2aed921 | ||
|
|
7c7275cfdb | ||
|
|
7c500d1047 | ||
|
|
7ad72f6ff8 | ||
|
|
1938c145db | ||
|
|
04f81a3375 | ||
|
|
fa34cade7a | ||
|
|
cab91f692e | ||
|
|
731e74ad06 | ||
|
|
5331a56d36 | ||
|
|
9b85c11803 | ||
|
|
c9069cfebd | ||
|
|
492542df91 | ||
|
|
6935b343ae | ||
|
|
ef6642181e | ||
|
|
ebc4c2d997 | ||
|
|
383fa9b0ae | ||
|
|
787b0bb777 | ||
|
|
0edef42bf2 | ||
|
|
022efa74c3 | ||
|
|
ba62a139e2 | ||
|
|
b72baaeb48 | ||
|
|
bdcc030de6 | ||
|
|
b9568896d6 | ||
|
|
dc55626832 | ||
|
|
2c7fd7d79b | ||
|
|
bb47f36a35 | ||
|
|
a87df5d0aa | ||
|
|
e6864cf8f3 | ||
|
|
0119972cc9 | ||
|
|
874bca5d61 | ||
|
|
81b0571b3e | ||
|
|
ddf09c6684 | ||
|
|
227b0fab76 | ||
|
|
a84ebb16e0 | ||
|
|
9538c72c99 | ||
|
|
8e727b0b63 | ||
|
|
d33fa36591 | ||
|
|
e8e2b28504 | ||
|
|
3f52efe4b8 | ||
|
|
266774fc61 | ||
|
|
e92b3b9cd4 | ||
|
|
5b828f0c83 | ||
|
|
5debca98d6 | ||
|
|
069cda512e | ||
|
|
ff37b3d758 | ||
|
|
4039e1e355 | ||
|
|
943a4e592b | ||
|
|
24b8b5bd05 | ||
|
|
8db727ed14 | ||
|
|
6085713885 | ||
|
|
60eca98d86 | ||
|
|
0b02edfe32 | ||
|
|
79605c7ed1 | ||
|
|
8383384af7 | ||
|
|
bd0ed0a10f | ||
|
|
d7807f3911 | ||
|
|
5f619c769a | ||
|
|
154adfd83f | ||
|
|
9cba46d33f | ||
|
|
0f67f64936 | ||
|
|
ba2cfe7b68 | ||
|
|
251959c18e | ||
|
|
d7fc8f62e8 | ||
|
|
11b9aa9e20 | ||
|
|
6f923251d4 | ||
|
|
9b7b79dacc | ||
|
|
af6942c04f | ||
|
|
d3550b0fca | ||
|
|
795639a8f4 | ||
|
|
0f1126174a | ||
|
|
2433a7daff | ||
|
|
a8b46e04ef | ||
|
|
e899a93358 | ||
|
|
2005acc343 | ||
|
|
716bd42c7d | ||
|
|
c74edebc1b | ||
|
|
6c37b11b59 | ||
|
|
1042bdcf56 | ||
|
|
facbeff722 | ||
|
|
6e9e04a65f | ||
|
|
ddba6c3cea | ||
|
|
695f500ab0 | ||
|
|
9d5f575765 | ||
|
|
9afa747cd4 | ||
|
|
7cbcd03c10 | ||
|
|
a8c021411b | ||
|
|
aaa2dc1100 | ||
|
|
774280dc90 | ||
|
|
85f71fd00a | ||
|
|
0732fc5efd | ||
|
|
d49c52a8d8 | ||
|
|
26635a4b6a | ||
|
|
fd9aa5b683 | ||
|
|
c32fa627e4 | ||
|
|
423828705a | ||
|
|
c8e78f8a19 | ||
|
|
ba273282db | ||
|
|
0e1ccfe469 | ||
|
|
a177c81314 | ||
|
|
6583e29d08 | ||
|
|
a3d491f1a5 | ||
|
|
beeffd820d | ||
|
|
e622c09251 | ||
|
|
8475ca7c1a | ||
|
|
da1d221e1d | ||
|
|
fe5fd75487 | ||
|
|
2e0d97a8bf | ||
|
|
e7f56aaa78 | ||
|
|
a5de673ad9 | ||
|
|
2728be2aa6 | ||
|
|
6fc0bb96be | ||
|
|
5867e1313c | ||
|
|
a9400df4b9 | ||
|
|
11deafd5cc | ||
|
|
6f1e01fe8b | ||
|
|
2e7c185f3b | ||
|
|
35b2e8c53f | ||
|
|
7fe8236611 | ||
|
|
2b95959361 | ||
|
|
0fcea2a61b | ||
|
|
09e4ae7c59 | ||
|
|
f8adf59780 | ||
|
|
e1ca6d7bbc | ||
|
|
1b04be3c46 | ||
|
|
027c4f4fd2 | ||
|
|
3fe2c8e9db | ||
|
|
75c01dafd5 | ||
|
|
6260ce630d | ||
|
|
3841b68d7a | ||
|
|
f789434f1b | ||
|
|
4302b7c2fb | ||
|
|
84a6c1b38c | ||
|
|
d1110445e6 | ||
|
|
365ce0757e | ||
|
|
029edb4758 | ||
|
|
637b6ff0aa | ||
|
|
8a0071563f | ||
|
|
cdc18303b4 | ||
|
|
5e45c86a0f | ||
|
|
b5d8e1764a | ||
|
|
36a4782383 | ||
|
|
f280b0c183 | ||
|
|
3a3cfb51c5 | ||
|
|
1415008d67 | ||
|
|
fd485ac1e9 | ||
|
|
b9d9ab8526 | ||
|
|
5eb18965ff | ||
|
|
53e07d1f26 | ||
|
|
857bea336a | ||
|
|
eb54b1eb9d | ||
|
|
cd378f537e | ||
|
|
4675f1126d | ||
|
|
60bb66d0ac | ||
|
|
02e6d6d1d5 | ||
|
|
5e6208eebb | ||
|
|
7f68a664a7 | ||
|
|
49866709c0 | ||
|
|
a70399b780 | ||
|
|
4555565753 | ||
|
|
4253f57ed8 | ||
|
|
cb2859f60c | ||
|
|
9818b99812 | ||
|
|
d0d85f26b2 | ||
|
|
6c0bab27c0 | ||
|
|
61cdc763f8 | ||
|
|
be73d63bf2 | ||
|
|
6c540fc099 | ||
|
|
7b19cbcd52 | ||
|
|
5350506a89 | ||
|
|
479df7cdad | ||
|
|
570f594dc7 | ||
|
|
b813dbe8c4 | ||
|
|
558044db25 | ||
|
|
5d11f51e05 | ||
|
|
1264384402 | ||
|
|
65309f25c2 | ||
|
|
c565decbe3 | ||
|
|
4bc1ae96c9 | ||
|
|
d3390fdbba | ||
|
|
d90f2cc83d | ||
|
|
e07f55e5ed | ||
|
|
4df17bc17e | ||
|
|
9a4c2a8cb5 | ||
|
|
cd6b797481 | ||
|
|
7ceb99ec79 | ||
|
|
79f11383f1 | ||
|
|
cc62c116a8 | ||
|
|
a9f6a04e83 | ||
|
|
69453350a2 | ||
|
|
a0c3bf02ec | ||
|
|
ba1b08eab8 | ||
|
|
d90d203ac3 | ||
|
|
678d898d48 | ||
|
|
351d13e1c3 | ||
|
|
c9214b5535 | ||
|
|
cfdd412546 | ||
|
|
c649698806 | ||
|
|
3accc0e158 | ||
|
|
352bb2c059 | ||
|
|
4a9bf570f8 | ||
|
|
4f608d2dd2 | ||
|
|
7eaa3f583f | ||
|
|
0cb6096019 | ||
|
|
82daf4044b | ||
|
|
4f31588cec | ||
|
|
5fe4a8fa97 | ||
|
|
6d6e928854 | ||
|
|
54cb053dfe | ||
|
|
d564da3872 | ||
|
|
cd3be1ae27 | ||
|
|
ca8e4616b4 | ||
|
|
8dfefdc7fd | ||
|
|
d89555723b | ||
|
|
28ec6f98cf | ||
|
|
6009ee7360 | ||
|
|
b9677ca557 | ||
|
|
2e2ba2be58 | ||
|
|
1dacc1371b | ||
|
|
1890a22efe | ||
|
|
202b61ec2e | ||
|
|
aba494e6b9 | ||
|
|
56863d5672 | ||
|
|
2ff99b7116 | ||
|
|
a267a2644c | ||
|
|
bb1287e02e | ||
|
|
00a24f13b6 | ||
|
|
213eda9797 | ||
|
|
47e3bf8fe5 | ||
|
|
95f3ebc1e0 | ||
|
|
2f8439d6ac | ||
|
|
f13c99de80 | ||
|
|
ed21b3db8d | ||
|
|
bb19f05f8f | ||
|
|
c5cd14afb5 | ||
|
|
6cfa34c341 | ||
|
|
4bdb25b687 | ||
|
|
477d59d271 | ||
|
|
7b43eed28d | ||
|
|
fc296b44d8 | ||
|
|
05cfecd073 | ||
|
|
6ee7472b65 | ||
|
|
cbcab47db3 | ||
|
|
93f6ab8b61 | ||
|
|
0881ef6524 | ||
|
|
15014a7bb1 | ||
|
|
af911d8592 | ||
|
|
c63caaf040 | ||
|
|
66f1d9140f | ||
|
|
d8b0584915 | ||
|
|
4e0dfd9883 | ||
|
|
8fd42b9a94 | ||
|
|
6fb8e9dbc6 | ||
|
|
4d9a4bf9e2 | ||
|
|
15ce829190 | ||
|
|
faf4b669bb | ||
|
|
9bdfe64ced | ||
|
|
ae6c83dc70 | ||
|
|
52ce8e5d0b | ||
|
|
2f1d7c7302 | ||
|
|
2aa0e0c320 | ||
|
|
c28461942c | ||
|
|
a114de32a9 | ||
|
|
d73206c237 | ||
|
|
f58bc266d6 | ||
|
|
03109e63b5 | ||
|
|
37c16f54ef | ||
|
|
b6275fc33e | ||
|
|
68d852b5b8 | ||
|
|
a7d44e7ec5 | ||
|
|
87f5d6a117 | ||
|
|
3bf924ef3a | ||
|
|
79676891a0 | ||
|
|
0fbd5f0b84 | ||
|
|
0b0696e624 | ||
|
|
43a272b50f | ||
|
|
1ab9763302 | ||
|
|
e0053af20a | ||
|
|
ddedf9d11f | ||
|
|
27c541a6be | ||
|
|
ba4b8d040f | ||
|
|
29ce881e63 | ||
|
|
9c3812c405 | ||
|
|
6b28a01413 | ||
|
|
d1f7063d48 | ||
|
|
6b99d31fdc | ||
|
|
5b2f6e1938 | ||
|
|
245e424c3a | ||
|
|
f09236d61d | ||
|
|
295854af48 | ||
|
|
d0190cacf9 | ||
|
|
9b35a16d7b | ||
|
|
75e2830057 | ||
|
|
c68f76adbc | ||
|
|
5ac349f1eb | ||
|
|
df45d927db | ||
|
|
0fa7093461 | ||
|
|
514fb9c2b0 | ||
|
|
b55a378396 | ||
|
|
3d8ccdca45 | ||
|
|
157ddfdac9 | ||
|
|
bcfb9d54ef | ||
|
|
0ae7a45dd8 | ||
|
|
475b998c1a | ||
|
|
cdbcbfa3ee | ||
|
|
96b7d31475 | ||
|
|
08024d2269 | ||
|
|
f7f76fe14f | ||
|
|
ec5d8de6c2 |
No files matched your search
@@ -0,0 +1,14 @@
|
||||
# Sentry
|
||||
VITE_SENTRY_DSN="https://********************************@*****************.example.com/****************"
|
||||
|
||||
# GitHub OAuth Configuration
|
||||
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
|
||||
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
|
||||
|
||||
# Netlify OAuth Configuration
|
||||
VITE_NETLIFY_OAUTH_CLIENT_ID="********************"
|
||||
VITE_NETLIFY_OAUTH_CLIENT_SECRET="****************************************"
|
||||
|
||||
# Vercel OAuth Configuration
|
||||
VITE_VERCEL_OAUTH_CLIENT_ID="********************"
|
||||
VITE_VERCEL_OAUTH_CLIENT_SECRET="****************************************"
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"nostr": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "xjsr", "@nostrbook/mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -6,13 +6,18 @@ yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
.ai/
|
||||
|
||||
deploy.sh
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.ai-history/
|
||||
*.apk
|
||||
*.aab
|
||||
|
||||
# Electron build output
|
||||
electron-dist
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
@@ -30,4 +35,5 @@ dist-ssr
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
.ai/
|
||||
*.keystore
|
||||
@@ -11,6 +11,8 @@ stages:
|
||||
test:
|
||||
stage: test
|
||||
script:
|
||||
- npm run typecheck
|
||||
- npm run build
|
||||
- npm run test
|
||||
|
||||
pages:
|
||||
|
||||
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -1,16 +0,0 @@
|
||||
# jsr registry should not be edited or removed
|
||||
.npmrc
|
||||
|
||||
# vite client types are needed
|
||||
src/vite-env.d.ts
|
||||
|
||||
# tsconfig is stable and working correctly, so should not be edited
|
||||
tsconfig.json
|
||||
tsconfig.app.json
|
||||
tsconfig.node.json
|
||||
|
||||
# postcss config for Tailwind is stable and working correctly, so should not be edited unless upgrading Tailwind to v4
|
||||
postcss.config.js
|
||||
|
||||
# vite config is stable and usually should not need to be edited
|
||||
vite.config.ts
|
||||
@@ -1,9 +1,19 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"js-dev": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
|
||||
},
|
||||
"nostr": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "xjsr", "@nostrbook/mcp"]
|
||||
"args": ["-y", "@nostrbook/mcp@latest"]
|
||||
},
|
||||
"fetch": {
|
||||
"type":"stdio",
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-fetch", "--ignore-robots-txt"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
{
|
||||
"editor.tabSize": 2
|
||||
}
|
||||
"editor.tabSize": 2,
|
||||
"editor.insertSpaces": true
|
||||
}
|
||||
@@ -1,3 +1,187 @@
|
||||
# Shakespeare - AI-Powered App Builder
|
||||
|
||||
Shakespeare is a browser-based AI chat application that allows users to build custom web applications through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
|
||||
|
||||
### Virtual Filesystem Layout
|
||||
|
||||
Shakespeare uses LightningFS to provide a browser-based virtual filesystem (VFS) that persists project files in IndexedDB. This is the VFS within the browser that Shakespeare agents act upon. Each project is stored in its own isolated directory structure within the virtual filesystem.
|
||||
|
||||
#### Virtual Filesystem Architecture
|
||||
|
||||
```
|
||||
/
|
||||
├── projects/
|
||||
│ └── {projectId}/ # Individual project directory
|
||||
│ └── ... # Project files (package.json, src/, public/, etc.)
|
||||
├── config/ # Configuration files
|
||||
│ ├── ai.json # AI provider settings and API keys
|
||||
│ └── git.json # Git credentials and repository settings
|
||||
└── tmp/ # Temporary files and scratch space
|
||||
└── ... # Various temporary files and directories
|
||||
```
|
||||
|
||||
#### Key Features
|
||||
|
||||
- **IndexedDB Backend**: All project files are stored in the browser's IndexedDB for persistence across sessions
|
||||
- **Project Isolation**: Each project has its own directory namespace to prevent conflicts
|
||||
- **File Operations**: Full POSIX-like filesystem operations (read, write, mkdir, rm, etc.)
|
||||
- **Git Integration**: Projects can be initialized as Git repositories for template cloning
|
||||
|
||||
This architecture allows Shakespeare to provide a full development environment entirely within the browser, with no server-side storage requirements.
|
||||
|
||||
#### AI Tools Available in Shakespeare
|
||||
|
||||
Shakespeare provides AI agents with specialized tools for project development (note: these are different from the tools available during Shakespeare's own development). These tools are defined in `src/lib/tools/`:
|
||||
|
||||
- **ShellTool**: Execute shell commands (virtual in browser, real OS shell in Electron)
|
||||
- **TextEditorViewTool**: Read file contents and view directory structures
|
||||
- **TextEditorWriteTool**: Create or overwrite files with new content
|
||||
- **TextEditorStrReplaceTool**: Replace strings in files
|
||||
- **BuildProjectTool**: Build and compile projects
|
||||
- **TypecheckTool**: Run TypeScript type checking
|
||||
- **NpmAddPackageTool**: Add npm packages to projects
|
||||
- **NpmRemovePackageTool**: Remove npm packages from projects
|
||||
- **GitCommitTool**: Commit changes to Git repositories
|
||||
- **DeployProjectTool**: Deploy projects to hosting platforms
|
||||
- **ReadWebpageTool**: Fetch and read web pages
|
||||
- **NostrReadNipTool**: Read Nostr protocol NIP documents
|
||||
- **NostrReadKindTool**: Read Nostr event kind documentation
|
||||
- **NostrReadTagTool**: Read Nostr tag documentation
|
||||
- **NostrReadProtocolTool**: Read Nostr protocol basics
|
||||
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
|
||||
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
|
||||
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
||||
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
|
||||
|
||||
#### Shell Commands
|
||||
|
||||
**In Browser Mode:**
|
||||
Shakespeare provides a comprehensive set of shell commands that are JavaScript reimplementations of common Unix commands. These commands operate on the virtual filesystem (VFS) and are accessible through the ShellTool. The shell commands are implemented in `src/lib/commands/` and provide familiar Unix-like functionality for file and directory operations.
|
||||
|
||||
**Available Commands:**
|
||||
- **File Operations**: `cat`, `cp`, `mv`, `rm`, `touch`, `find`, `grep`
|
||||
- **Directory Operations**: `cd`, `ls`, `mkdir`, `pwd`, `tree`
|
||||
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
|
||||
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
|
||||
|
||||
**In Electron Mode:**
|
||||
When running in Electron, the ShellTool automatically uses the **real OS terminal** instead of the virtual terminal. This means:
|
||||
- **All OS commands available**: Not limited to built-in commands
|
||||
- **Native shell features**: Pipes, redirection, environment variables work natively
|
||||
- **Package managers**: `npm`, `yarn`, `pnpm` work directly
|
||||
- **Build tools**: `vite`, `webpack`, `tsc`, etc. available
|
||||
- **System utilities**: Full access to OS commands
|
||||
|
||||
The ShellTool detects the environment automatically and uses the appropriate execution method.
|
||||
|
||||
#### Security
|
||||
|
||||
AI filesystem access through tools (including shell commands via ShellTool) has path restrictions to ensure safe operation:
|
||||
|
||||
- **Read operations**: Can access any file in the VFS, including absolute paths
|
||||
- **Write operations**: Restricted to current project directory and `/tmp/` directory (including subdirectories)
|
||||
- **Copy operations**: Can copy from any absolute path to relative paths or `/tmp/`, but cannot copy from relative to absolute paths outside allowed areas
|
||||
|
||||
### Git Integration with isomorphic-git
|
||||
|
||||
Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB.
|
||||
|
||||
#### Key Components
|
||||
|
||||
- **LightningFSAdapter**: Adapts LightningFS to the unified JSRuntimeFS interface
|
||||
- **GitCommitTool**: AI tool for automated commits with staging and validation
|
||||
- **useGitStatus Hook**: Real-time Git status monitoring (updates every 5 seconds)
|
||||
- **useGitFetch Hook**: Automatic remote fetch with change detection (updates every 60 seconds, shows toast notifications)
|
||||
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
|
||||
|
||||
#### Core Features
|
||||
|
||||
**Project Creation:**
|
||||
1. Clone template from GitLab repository (shallow clone, depth: 1)
|
||||
2. Remove original Git history
|
||||
3. Initialize fresh repository with `main` branch
|
||||
4. Stage all files and create initial commit
|
||||
|
||||
**Version Control:**
|
||||
- Automatic staging of all changed files before commits
|
||||
- Real-time status tracking (modified, added, deleted, untracked, staged files)
|
||||
- Full commit history with author info and SHA hashes
|
||||
- Branch management and remote repository support
|
||||
|
||||
**AI Integration:**
|
||||
- GitCommitTool allows AI assistants to commit changes automatically
|
||||
- Validates repository status and handles edge cases
|
||||
- Generates descriptive commit messages with file change statistics
|
||||
|
||||
**Browser Compatibility:**
|
||||
- CORS proxy for GitHub/GitLab repositories (`https://cors.isomorphic-git.org`)
|
||||
- IndexedDB persistence across browser sessions
|
||||
- Gitignore support using the `ignore` library
|
||||
|
||||
Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users.
|
||||
|
||||
### Gift Card Redemption
|
||||
|
||||
Shakespeare supports automatic gift card redemption via URL parameters. Users can click shareable gift card links to instantly redeem AI credits.
|
||||
|
||||
**URL Format:**
|
||||
```
|
||||
/giftcard#baseURL=<providerBaseURL>&code=<giftcardCode>
|
||||
```
|
||||
|
||||
**Flow:**
|
||||
1. User clicks gift card link (e.g., from email or social media)
|
||||
2. Shakespeare displays a dialog showing the credit amount
|
||||
3. URL is rewritten to `/` for privacy (removes gift card code from history)
|
||||
4. If user is not logged in or provider is not configured, a multi-step wizard guides them through setup
|
||||
5. User can switch between Nostr accounts before redeeming
|
||||
6. Credits are added to the user's account via NIP-98 authenticated API call
|
||||
|
||||
**Components:**
|
||||
- `GiftCardRedeemDialog`: Main dialog handling the entire redemption flow
|
||||
- Integrates with existing login/signup dialogs and provider configuration
|
||||
- Automatically matches provider baseURL against configured providers and presets
|
||||
|
||||
See `GIFTCARD_REDEMPTION.md` for detailed documentation.
|
||||
|
||||
## AI Message Format
|
||||
|
||||
Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions:
|
||||
|
||||
### User Messages
|
||||
|
||||
**String Content**: When the user message `content` is a string, it represents the actual user's message directly.
|
||||
|
||||
```json
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Please help me build a todo app"
|
||||
}
|
||||
```
|
||||
|
||||
**Array Content**: When the user message `content` is an array of parts, the structure follows this pattern:
|
||||
|
||||
- **First text part**: Represents the user's actual message
|
||||
- **Subsequent text parts**: Represent user actions, such as adding files to the VFS
|
||||
|
||||
```json
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Can you add this logo to my site?"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Added file: /tmp/logo.svg"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
This format allows the Shakespeare UI to parse and display user actions appropriately while maintaining compatibility with OpenAI's message format standard.
|
||||
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
@@ -18,6 +202,12 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog)
|
||||
- `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection)
|
||||
- `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane)
|
||||
- `/src/components/ProjectSidebar.tsx`: Sidebar component containing project list and import options
|
||||
- `/src/components/ZipImportDialog.tsx`: Dialog component for importing projects from ZIP files
|
||||
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
@@ -25,15 +215,45 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useFS`: Access virtual filesystem for project file operations
|
||||
- `useAISettings`: Manage AI provider configurations and API keys
|
||||
- `useGitSettings`: Manage Git credentials and repository settings
|
||||
- `useSessionManager`: Access session management for AI chat sessions
|
||||
- `useGitStatus`: Real-time Git repository status monitoring
|
||||
- `useGitFetch`: Automatic remote fetch with change detection and toast notifications
|
||||
- `useProjects`: Project management and CRUD operations
|
||||
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `useZaps`: Lightning zap functionality with payment processing
|
||||
- `useWallet`: Unified wallet detection (WebLN + NWC)
|
||||
- `useNWC`: Nostr Wallet Connect connection management
|
||||
- `useNWCContext`: Access NWC context provider
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound, ProjectView, Settings pages)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/lib/build/`: Project build system with esbuild integration (esmPlugin, fsPlugin)
|
||||
- `/src/lib/commands/`: Shell command implementations for virtual filesystem
|
||||
- `/src/lib/commands/git/`: Git command implementations (add, commit, push, pull, etc.)
|
||||
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
|
||||
- `/src/lib/tools/`: AI tool implementations for project development
|
||||
- File operations: `TextEditorViewTool`, `TextEditorWriteTool`, `TextEditorStrReplaceTool`
|
||||
- Project tools: `BuildProjectTool`, `TypecheckTool`, `DeployProjectTool`
|
||||
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
|
||||
- Git integration: `GitCommitTool`
|
||||
- Shell access: `ShellTool`
|
||||
- Web access: `ReadWebpageTool`
|
||||
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
|
||||
- `/src/contexts/`: React context providers
|
||||
- `AppContext`: Global app configuration and theme
|
||||
- `FSContext`: Virtual filesystem access
|
||||
- `AISettingsContext`: AI provider settings and API key management
|
||||
- `GitSettingsContext`: Git credentials and repository configuration
|
||||
- `SessionManagerContext`: AI chat session management
|
||||
- `NWCContext`: Nostr Wallet Connect integration
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
@@ -81,7 +301,6 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
@@ -95,11 +314,52 @@ These components follow a consistent pattern using React's `forwardRef` and use
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
1. Edit AGENTS.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## Translations
|
||||
|
||||
Shakespeare includes internationalization (i18n) support using react-i18next. The translation system allows the interface to be displayed in multiple languages.
|
||||
|
||||
### Key Files
|
||||
|
||||
- **`src/lib/i18n.ts`**: Main translation configuration file containing all translation resources for supported languages
|
||||
- **`src/components/LanguagePicker.tsx`**: Language selection component used in preferences, must be updated when adding new languages
|
||||
|
||||
### Usage in Components
|
||||
|
||||
Use the `useTranslation` hook to access translations in React components:
|
||||
|
||||
```tsx
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
function MyComponent() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return <h1>{t('settings')}</h1>; // Returns "Settings", "Configurações", etc.
|
||||
}
|
||||
```
|
||||
|
||||
### Translation Key Organization
|
||||
|
||||
Translation keys are organized by functionality:
|
||||
- **Navigation and Layout**: `preferences`, `settings`, `help`, etc.
|
||||
- **Authentication**: `logIn`, `signUp`
|
||||
- **UI Elements**: `save`, `cancel`, `loading`, etc.
|
||||
- **Feature-specific sections**: AI Settings, Git Settings, Nostr Settings, etc.
|
||||
|
||||
### Adding New Languages
|
||||
|
||||
1. Add the new language code and translation object to the `resources` object in `src/lib/i18n.ts`
|
||||
2. Add all required key-value pairs for the new language, following existing patterns
|
||||
3. Update `src/components/LanguagePicker.tsx` to include the new language option in the dropdown
|
||||
4. Add the language name translations (e.g., `spanish: 'Spanish'`) to all existing language objects
|
||||
5. Use descriptive, hierarchical key names (avoid duplicates)
|
||||
6. Keep translations concise and consistent with existing patterns
|
||||
7. Test the new language thoroughly to ensure proper display across all components
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
@@ -110,9 +370,9 @@ This project comes with custom hooks for querying and publishing events on the N
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
- Always check the full list of existing NIPs before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, read the relevant NIPs to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
@@ -120,7 +380,7 @@ Knowing when to create a new kind versus reusing an existing kind requires caref
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Get an overview of all NIPs, and then read specific NIPs and kind documentation to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
@@ -138,7 +398,7 @@ When implementing features that could use existing NIPs, follow this decision fr
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
@@ -299,6 +559,70 @@ function usePosts() {
|
||||
}
|
||||
```
|
||||
|
||||
### Infinite Scroll for Feeds
|
||||
|
||||
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
|
||||
export function useGlobalFeed() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: ['global-feed'],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
const filter = { kinds: [1], limit: 20 };
|
||||
if (pageParam) filter.until = pageParam;
|
||||
|
||||
const events = await nostr.query([filter], {
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
|
||||
});
|
||||
|
||||
return events;
|
||||
},
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (lastPage.length === 0) return undefined;
|
||||
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
|
||||
},
|
||||
initialPageParam: undefined,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Example usage with intersection observer for automatic loading:
|
||||
|
||||
```tsx
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
|
||||
function GlobalFeed() {
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
|
||||
const { ref, inView } = useInView();
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage) {
|
||||
fetchNextPage();
|
||||
}
|
||||
}, [inView, hasNextPage, fetchNextPage]);
|
||||
|
||||
const posts = data?.pages.flat() || [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{posts.map((post) => (
|
||||
<PostCard key={post.id} post={post} />
|
||||
))}
|
||||
{hasNextPage && (
|
||||
<div ref={ref} className="py-4">
|
||||
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
@@ -494,12 +818,14 @@ The `LoginArea` component handles all the login-related UI and interactions, inc
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
**Important**: Social applications should include a profile menu button in the main interface (typically in headers/navigation) to provide access to account settings, profile editing, and logout functionality. Don't only show `LoginArea` in logged-out states.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
@@ -553,7 +879,7 @@ This project includes a boilerplate `NIP19Page` component that provides the foun
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
@@ -774,12 +1100,19 @@ The project includes an `AppProvider` that manages global application state incl
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
theme: "system",
|
||||
relayMetadata: {
|
||||
relays: [
|
||||
{ url: 'wss://relay.ditto.pub', read: true, write: true },
|
||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
// ... other config options
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
The app uses NIP-65 relay lists for managing multiple relays with read/write permissions. Configuration is persisted in local storage.
|
||||
|
||||
## Routing
|
||||
|
||||
@@ -833,11 +1166,12 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
|
||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state that guides users to take action or provides helpful context.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
@@ -845,37 +1179,77 @@ import { Card, CardContent } from '@/components/ui/card';
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
No results found. Configure your relays to discover more content.
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
<Button asChild variant="outline">
|
||||
<Link to="/settings/nostr">Manage Relays</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
## CRITICAL Design Standards
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
- Create breathtaking, immersive designs that feel like bespoke masterpieces, rivaling the polish of Apple, Stripe, or luxury brands
|
||||
- Designs must be production-ready, fully featured, with no placeholders unless explicitly requested, ensuring every element serves a functional and aesthetic purpose
|
||||
- Avoid generic or templated aesthetics at all costs; every design must have a unique, brand-specific visual signature that feels custom-crafted
|
||||
- Headers must be dynamic, immersive, and storytelling-driven, using layered visuals, motion, and symbolic elements to reflect the brand’s identity—never use simple “icon and text” combos
|
||||
- Incorporate purposeful, lightweight animations for scroll reveals, micro-interactions (e.g., hover, click, transitions), and section transitions to create a sense of delight and fluidity
|
||||
|
||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||
### Design Principles
|
||||
|
||||
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
|
||||
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
|
||||
- Use custom illustrations, 3D elements, or symbolic visuals instead of generic stock imagery to create a unique brand narrative; stock imagery, when required, must be sourced exclusively from Pexels (NEVER Unsplash) and align with the design’s emotional tone
|
||||
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
|
||||
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
|
||||
|
||||
### Avoid Generic Design
|
||||
|
||||
- No basic layouts (e.g., text-on-left, image-on-right) without significant custom polish, such as dynamic backgrounds, layered visuals, or interactive elements
|
||||
- No simplistic headers; they must be immersive, animated, and reflective of the brand’s core identity and mission
|
||||
- No designs that could be mistaken for free templates or overused patterns; every element must feel intentional and tailored
|
||||
|
||||
### Interaction Patterns
|
||||
|
||||
- Use progressive disclosure for complex forms or content to guide users intuitively and reduce cognitive load
|
||||
- Incorporate contextual menus, smart tooltips, and visual cues to enhance navigation and usability
|
||||
- Implement drag-and-drop, hover effects, and transitions with clear, dynamic visual feedback to elevate the user experience
|
||||
- Support power users with keyboard shortcuts, ARIA labels, and focus states for accessibility and efficiency
|
||||
- Add subtle parallax effects or scroll-triggered animations to create depth and engagement without overwhelming the user
|
||||
|
||||
### Technical Requirements
|
||||
|
||||
- Curated color FRpalette (3-5 evocative colors + neutrals) that aligns with the brand’s emotional tone and creates a memorable impact
|
||||
- Ensure a minimum 4.5:1 contrast ratio for all text and interactive elements to meet accessibility standards
|
||||
- Use expressive, readable fonts (18px+ for body text, 40px+ for headlines) with a clear hierarchy; pair a modern sans-serif (e.g., Inter) with an elegant serif (e.g., Playfair Display) for personality
|
||||
- Design for full responsiveness, ensuring flawless performance and aesthetics across all screen sizes (mobile, tablet, desktop)
|
||||
- Adhere to WCAG 2.1 AA guidelines, including keyboard navigation, screen reader support, and reduced motion options
|
||||
- Follow an 8px grid system for consistent spacing, padding, and alignment to ensure visual harmony
|
||||
- Add depth with subtle shadows, gradients, glows, and rounded corners (e.g., 16px radius) to create a polished, modern aesthetic
|
||||
- Optimize animations and interactions to be lightweight and performant, ensuring smooth experiences across devices
|
||||
|
||||
### Components
|
||||
|
||||
- Design reusable, modular components with consistent styling, behavior, and feedback states (e.g., hover, active, focus, error)
|
||||
- Include purposeful animations (e.g., scale-up on hover, fade-in on scroll) to guide attention and enhance interactivity without distraction
|
||||
- Ensure full accessibility support with keyboard navigation, ARIA labels, and visible focus states (e.g., a glowing outline in an accent color)
|
||||
- Use custom icons or illustrations for components to reinforce the brand’s visual identity
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
1. **Install a font package** using npm:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
- For Inter Variable: `@fontsource-variable/inter`
|
||||
- For Roboto: `@fontsource/roboto`
|
||||
- For Outfit Variable: `@fontsource-variable/outfit`
|
||||
- For Poppins: `@fontsource/poppins`
|
||||
- For Open Sans: `@fontsource/open-sans`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
@@ -928,8 +1302,11 @@ When users specify color schemes:
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
## Writing Tests vs Running Tests
|
||||
|
||||
There is an important distinction between **writing new tests** and **running existing tests**:
|
||||
|
||||
### Writing Tests (Creating New Test Files)
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
@@ -942,6 +1319,14 @@ When users specify color schemes:
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Running Tests (Executing the Test Suite)
|
||||
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
|
||||
|
||||
- **You must run the test script** to validate your changes
|
||||
- **Your task is not complete** until the test script passes without errors
|
||||
- **This applies to all changes** - bug fixes, new features, refactoring, or any code modifications
|
||||
- **The test script includes** TypeScript compilation, ESLint checks, and existing test validation
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
@@ -971,8 +1356,24 @@ describe('MyComponent', () => {
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
## Validating Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
|
||||
|
||||
### Validation Priority Order
|
||||
|
||||
Run available tools in this priority order:
|
||||
|
||||
1. **Type Checking** (Required): Ensure TypeScript compilation succeeds
|
||||
2. **Building/Compilation** (Required): Verify the project builds successfully
|
||||
3. **Linting** (Recommended): Check code style and catch potential issues
|
||||
4. **Tests** (If Available): Run existing test suite
|
||||
|
||||
**Minimum Requirements:**
|
||||
- Code must type-check without errors
|
||||
- Code must build/compile successfully
|
||||
- Fix any critical linting errors that would break functionality
|
||||
|
||||
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
|
||||
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -1,59 +1,43 @@
|
||||
# Shakespeare - AI-Powered Nostr Website Builder
|
||||
# Shakespeare 🎭
|
||||
|
||||
Shakespeare is an AI chat application that allows users to build custom Nostr websites through natural language conversation. Simply describe what you want to build, and AI will help you create it.
|
||||
[](https://shakespeare.diy/clone?url=https://gitlab.com/soapbox-pub/shakespeare.git)
|
||||
|
||||
Shakespeare is an open-source AI app builder that runs entirely in your browser.
|
||||
|
||||
https://shakespeare.diy
|
||||
|
||||
## Features
|
||||
|
||||
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
|
||||
- **Project Management**: Create and manage multiple projects in a Google Drive-like interface
|
||||
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting
|
||||
- **File Explorer**: Browse and manage your project files
|
||||
- **Project Preview**: Preview your website as you build it
|
||||
- **Template Cloning**: Start from a pre-configured Nostr template
|
||||
- **Use any AI provider** OpenAI, Anthropic, OpenRouter, xAI, ZAI, Deepseek, and more
|
||||
- **Buy credits anonymously** with Nostr and Lightning ⚡
|
||||
- **Redeem gift cards** with shareable links for instant credits
|
||||
- **Runs entirely in the browser** No backend required
|
||||
|
||||
## Getting Started
|
||||
## How it Works
|
||||
|
||||
1. **Create a Project**: Enter a description of what you want to build in the prompt textarea
|
||||
2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website
|
||||
3. **Edit Code**: Switch to the code view to manually edit files if needed
|
||||
4. **Preview**: View your website in the preview pane
|
||||
Shakespeare is a React PWA that stores files in IndexedDB with [LightningFS](https://github.com/isomorphic-git/lightning-fs). Your browser connects directly to AI providers and git services (through [isomorphic-git](https://github.com/isomorphic-git/isomorphic-git)) to enable you to build and deploy AI apps entirely from your device.
|
||||
|
||||
## Project Structure
|
||||
Shakespeare hosts no backend (except for a couple microservices in the `services/` directory; these are fully configurable within Shakespeare's settings). All your code and configuration is stored in your browser.
|
||||
|
||||
Each project includes:
|
||||
- React 18 with TypeScript
|
||||
- Vite for building
|
||||
- TailwindCSS for styling
|
||||
- Nostrify for Nostr integration
|
||||
- shadcn/ui components
|
||||
Configure any AI providers and git services you want. Configuration is stored entirely in the browser in localStorage.
|
||||
|
||||
## AI Capabilities
|
||||
You can then push and pull code to syncronize your work across devices.
|
||||
|
||||
The AI assistant can:
|
||||
- Read and write project files
|
||||
- Add new components and pages
|
||||
- Configure Nostr functionality
|
||||
- Build the project
|
||||
- Search through files
|
||||
- Provide project structure overview
|
||||
- Add and remove npm packages
|
||||
- Install dependencies and dev dependencies
|
||||
Shakespeare can work on any type of project. But it is specialized to build React applications in TypeScript, which it compiles in the browser with [esbuild-wasm](https://www.npmjs.com/package/esbuild-wasm) and custom plugins. Any codebase can be worked on, but only compatible projects can be previewed directly in Shakespeare.
|
||||
|
||||
## Usage
|
||||
## Open Source
|
||||
|
||||
1. **Homepage**: Create new projects and view existing ones
|
||||
2. **Project View**: Split-pane interface with AI chat on the left and preview/code on the right
|
||||
3. **File Explorer**: Navigate your project files in the code view
|
||||
4. **File Editor**: Edit files with syntax highlighting and save changes
|
||||
Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The purpose of Shakespeare is to provide a free and open platform for building AI applications that respects user privacy and freedom.
|
||||
|
||||
## Development
|
||||
## Mirrors
|
||||
|
||||
Built with:
|
||||
- React 18
|
||||
- TypeScript
|
||||
- Vite
|
||||
- TailwindCSS
|
||||
- shadcn/ui
|
||||
- Vercel AI SDK
|
||||
- LightningFS for filesystem
|
||||
- isomorphic-git for template cloning
|
||||
Shakespeare is available on the following URLs:
|
||||
|
||||
- [shakespeare.diy](https://shakespeare.diy)
|
||||
- [shakespeare-diy.github.io](https://shakespeare-diy.github.io)
|
||||
- [shakespeare-b0b9c8.gitlab.io](https://shakespeare-b0b9c8.gitlab.io)
|
||||
|
||||
## Alternatives
|
||||
|
||||
- [goose](https://github.com/block/goose) - open-source desktop app and cli utilizing your full computer for AI tasks
|
||||
- [bolt.diy](https://github.com/stackblitz-labs/bolt.diy) - similar to Shakespeare, but built on closed-source WebContainers technology
|
||||
@@ -1,11 +0,0 @@
|
||||
Please create Shakespeare, an AI chat application that allows users to build custom Nostr websites. On the landing page would be a prompt textarea. Upon entering a prompt, a template would be cloned with `isomorphic-git`. That template's clone URL is hardcoded to `https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git`. A unique directory name would also be generated from the prompt since the user would be able to work on multiple projects within this app.
|
||||
|
||||
For the filesystem, use LightningFS (`@isomorphic-git/lightning-fs` on npm). Note that `isomorphic-git` requires a `Buffer` polyfill to work. isomorphic-git's http client should be added by using `import http from "isomorphic-git/http/web"` (not `fetch`).
|
||||
|
||||
After projects have been created, they'll show up in a grid on the homepage, below the prompt textarea, in a grid design similar to Google Drive. Clicking them navigates to the project view. Creating a project through the homepage prompt also redirects to its project view.
|
||||
|
||||
In the project view, there is a chat in the left pane, and a project preview in the right. Initially the project preview will be empty, because the site won't have been built yet. The project needs to be built with Vite (directly in the browser) and displayed in an iframe, but we'll figure that out later. Just include a placeholder for it in the UI for now.
|
||||
|
||||
In the project chat pane, the user is able to chat with an AI assistant. The assistant will have tools that allow it to work on the project, including editing files and running the Vite build (again, just a stub). In the right preview pane, the user would also be able to switch to a "Code" view, which would display the list of files in the project.
|
||||
|
||||
For the AI implementation, use Vercel's ai-sdk (`ai` on npm). It should use the openai provider (`@ai-sdk/openai` on npm) and include a tool set for working on the project.
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"model": "claude-sonnet-4-0",
|
||||
"temperature": 0.2,
|
||||
"mcpServers": {
|
||||
"js-dev": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
|
||||
},
|
||||
"nostr": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@nostrbook/mcp@latest"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,978 +0,0 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
|
||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- No existing NIP covers the core functionality
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```typescript
|
||||
// This creates unnecessary load and can trigger rate limiting
|
||||
const [notes, reposts, genericReposts] = await Promise.all([
|
||||
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['calendar-events'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### Empty States and No Content Found
|
||||
|
||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -0,0 +1,544 @@
|
||||
# Unified OAuth System
|
||||
|
||||
Shakespeare implements a unified OAuth 2.0 authentication system that supports multiple providers with a consistent API. This document explains how the system works and how to add new OAuth providers.
|
||||
|
||||
## Architecture
|
||||
|
||||
The OAuth system consists of three main components:
|
||||
|
||||
1. **Generic OAuth Hook** (`useOAuth`) - Core OAuth logic that works with any provider
|
||||
2. **Provider-Specific Hooks** - Thin wrappers that configure the generic hook for specific providers
|
||||
3. **OAuth Callback Pages** - React components that handle the OAuth redirect flow
|
||||
|
||||
### Current Supported Providers
|
||||
|
||||
- **GitHub** - Git repository hosting (with PKCE support)
|
||||
- **Netlify** - Static site deployment
|
||||
- **Vercel** - Static site deployment
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── hooks/
|
||||
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
|
||||
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
|
||||
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
|
||||
│ └── useVercelOAuth.ts # Vercel-specific configuration
|
||||
├── pages/
|
||||
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
|
||||
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
|
||||
│ └── VercelOAuth.tsx # Vercel OAuth callback page
|
||||
└── AppRouter.tsx # Routes for OAuth callbacks
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
OAuth credentials are stored in environment variables and loaded from `process.env`:
|
||||
|
||||
```bash
|
||||
# GitHub OAuth Configuration
|
||||
VITE_GITHUB_OAUTH_CLIENT_ID="your_github_client_id"
|
||||
VITE_GITHUB_OAUTH_CLIENT_SECRET="your_github_client_secret"
|
||||
|
||||
# Netlify OAuth Configuration
|
||||
VITE_NETLIFY_OAUTH_CLIENT_ID="your_netlify_client_id"
|
||||
VITE_NETLIFY_OAUTH_CLIENT_SECRET="your_netlify_client_secret"
|
||||
|
||||
# Vercel OAuth Configuration
|
||||
VITE_VERCEL_OAUTH_CLIENT_ID="your_vercel_client_id"
|
||||
VITE_VERCEL_OAUTH_CLIENT_SECRET="your_vercel_client_secret"
|
||||
```
|
||||
|
||||
### Security Note
|
||||
|
||||
**Client secrets are stored in environment variables** and bundled into the client-side JavaScript. This is necessary because the OAuth flow runs entirely in the browser. While this approach is less secure than a traditional server-side OAuth flow, it's acceptable for this use case because:
|
||||
|
||||
1. Shakespeare is a client-side application with no backend
|
||||
2. The OAuth tokens are scoped to specific permissions
|
||||
3. Users can revoke tokens at any time from the provider's settings
|
||||
4. The redirect URIs are validated by the OAuth provider
|
||||
|
||||
For production deployments, consider using a serverless function or backend service to handle the token exchange step, keeping client secrets secure.
|
||||
|
||||
## How It Works
|
||||
|
||||
### 1. Generic OAuth Hook (`useOAuth`)
|
||||
|
||||
The `useOAuth` hook implements the OAuth 2.0 authorization code flow with optional PKCE (Proof Key for Code Exchange) support. It accepts a configuration object and returns methods to initiate and handle the OAuth flow.
|
||||
|
||||
**Configuration Interface:**
|
||||
|
||||
```typescript
|
||||
interface OAuthConfig {
|
||||
provider: 'github' | 'netlify' | 'vercel'; // Provider identifier
|
||||
clientId: string; // OAuth client ID
|
||||
clientSecret: string; // OAuth client secret
|
||||
authorizeUrl: string; // Provider's authorization endpoint
|
||||
tokenUrl: string; // Provider's token exchange endpoint
|
||||
scope?: string; // Requested OAuth scopes (optional)
|
||||
redirectUri: string; // Callback URL after authorization
|
||||
usePKCE?: boolean; // Enable PKCE (default: false)
|
||||
getUserInfo?: ( // Optional function to fetch user info
|
||||
accessToken: string,
|
||||
corsProxy: string
|
||||
) => Promise<{
|
||||
username: string;
|
||||
[key: string]: unknown;
|
||||
}>;
|
||||
}
|
||||
```
|
||||
|
||||
**Returned API:**
|
||||
|
||||
```typescript
|
||||
{
|
||||
isLoading: boolean; // True during token exchange
|
||||
error: string | null; // Error message if OAuth fails
|
||||
isOAuthConfigured: boolean; // True if client ID and secret are set
|
||||
initiateOAuth: () => void; // Start the OAuth flow
|
||||
handleCallback: ( // Handle the OAuth callback
|
||||
code: string,
|
||||
state: string
|
||||
) => Promise<OAuthResult | null>;
|
||||
}
|
||||
```
|
||||
|
||||
### 2. OAuth Flow Steps
|
||||
|
||||
#### Step 1: Initiate OAuth
|
||||
|
||||
When the user clicks "Connect to [Provider]", the `initiateOAuth()` function:
|
||||
|
||||
1. Generates a random `state` parameter for CSRF protection
|
||||
2. Optionally generates PKCE parameters (code verifier and challenge)
|
||||
3. Stores the state and code verifier in localStorage
|
||||
4. Redirects to the provider's authorization page
|
||||
|
||||
```typescript
|
||||
const { initiateOAuth } = useGitHubOAuth();
|
||||
|
||||
// User clicks button
|
||||
<Button onClick={initiateOAuth}>Connect to GitHub</Button>
|
||||
```
|
||||
|
||||
#### Step 2: User Authorizes
|
||||
|
||||
The user is redirected to the provider's authorization page where they:
|
||||
1. Log in to their account (if not already logged in)
|
||||
2. Review the requested permissions
|
||||
3. Approve or deny the authorization request
|
||||
|
||||
#### Step 3: OAuth Callback
|
||||
|
||||
After authorization, the provider redirects back to the callback URL with:
|
||||
- `code` - Authorization code
|
||||
- `state` - The state parameter we sent
|
||||
- `error` (optional) - Error code if authorization failed
|
||||
- `error_description` (optional) - Human-readable error description
|
||||
|
||||
The callback page (e.g., `GitHubOAuth.tsx`) extracts these parameters and calls `handleCallback()`.
|
||||
|
||||
#### Step 4: Token Exchange
|
||||
|
||||
The `handleCallback()` function:
|
||||
|
||||
1. Verifies the `state` parameter matches what we stored
|
||||
2. Retrieves the PKCE code verifier (if PKCE is enabled)
|
||||
3. Exchanges the authorization code for an access token
|
||||
4. Optionally fetches user information using the access token
|
||||
5. Returns an `OAuthResult` object with the token and user data
|
||||
|
||||
```typescript
|
||||
interface OAuthResult {
|
||||
accessToken: string; // OAuth access token
|
||||
username?: string; // User's username/email
|
||||
scopes?: string[]; // Granted OAuth scopes
|
||||
userData?: Record<string, unknown>; // Additional user data
|
||||
}
|
||||
```
|
||||
|
||||
#### Step 5: Store Credentials
|
||||
|
||||
Provider-specific hooks override `handleCallback` to store the credentials appropriately:
|
||||
|
||||
- **GitHub**: Stores in Git settings (for push/pull operations)
|
||||
- **Netlify/Vercel**: Stores in Deploy settings (for deployment operations)
|
||||
|
||||
### 3. PKCE Support
|
||||
|
||||
PKCE (Proof Key for Code Exchange) adds an extra layer of security to the OAuth flow by preventing authorization code interception attacks. It's recommended for public clients like browser-based apps.
|
||||
|
||||
**How PKCE works:**
|
||||
|
||||
1. Generate a random `code_verifier` (cryptographically random string)
|
||||
2. Create a `code_challenge` by hashing the verifier with SHA-256
|
||||
3. Send the `code_challenge` during authorization
|
||||
4. Send the `code_verifier` during token exchange
|
||||
5. The server verifies that the verifier matches the challenge
|
||||
|
||||
**Enabling PKCE:**
|
||||
|
||||
```typescript
|
||||
const config: OAuthConfig = {
|
||||
// ... other config
|
||||
usePKCE: true, // Enable PKCE
|
||||
};
|
||||
```
|
||||
|
||||
**Provider Support:**
|
||||
- ✅ GitHub - Supports PKCE (enabled)
|
||||
- ❌ Netlify - Doesn't support PKCE (disabled)
|
||||
- ❌ Vercel - Doesn't support PKCE (disabled)
|
||||
|
||||
### Scope Parameter
|
||||
|
||||
The `scope` parameter is optional in the OAuth configuration. Some providers (like Netlify) don't use scopes in the authorization request - instead, permissions are configured when you create the OAuth application in the provider's settings.
|
||||
|
||||
**Provider Scope Usage:**
|
||||
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
|
||||
- ❌ Netlify - No scope parameter (permissions set in app settings)
|
||||
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
|
||||
|
||||
## Adding a New OAuth Provider
|
||||
|
||||
To add a new OAuth provider, follow these steps:
|
||||
|
||||
### 1. Add Environment Variables
|
||||
|
||||
Add the client ID and secret to `.env.example`:
|
||||
|
||||
```bash
|
||||
# NewProvider OAuth Configuration
|
||||
VITE_NEWPROVIDER_OAUTH_CLIENT_ID="********************"
|
||||
VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET="****************************************"
|
||||
```
|
||||
|
||||
### 2. Create Provider-Specific Hook
|
||||
|
||||
Create a new file `src/hooks/useNewProviderOAuth.ts`:
|
||||
|
||||
```typescript
|
||||
import { useCallback } from 'react';
|
||||
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
interface NewProviderUserInfo {
|
||||
id: string;
|
||||
email: string;
|
||||
// ... other user fields
|
||||
}
|
||||
|
||||
export function useNewProviderOAuth() {
|
||||
// Get the context where you want to store credentials
|
||||
// e.g., useDeploySettings() or useGitSettings()
|
||||
const { setProviders, settings } = useDeploySettings();
|
||||
|
||||
const config: OAuthConfig = {
|
||||
provider: 'newprovider',
|
||||
clientId: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_ID || '',
|
||||
clientSecret: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET || '',
|
||||
authorizeUrl: 'https://provider.com/oauth/authorize',
|
||||
tokenUrl: 'https://provider.com/oauth/token',
|
||||
scope: 'read write', // Optional - omit if provider doesn't use scopes
|
||||
redirectUri: window.location.origin + '/oauth/newprovider',
|
||||
usePKCE: false, // Set to true if provider supports PKCE
|
||||
getUserInfo: async (accessToken: string, corsProxy: string) => {
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userResponse.ok) {
|
||||
throw new Error(`Failed to verify token: ${userResponse.statusText}`);
|
||||
}
|
||||
|
||||
const userData: NewProviderUserInfo = await userResponse.json();
|
||||
return {
|
||||
username: userData.email,
|
||||
...userData,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const oauth = useOAuth(config);
|
||||
|
||||
const handleCallbackAndStore = useCallback(async (
|
||||
code: string,
|
||||
state: string
|
||||
): Promise<boolean> => {
|
||||
const result: OAuthResult | null = await oauth.handleCallback(code, state);
|
||||
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Store the credentials in the appropriate context
|
||||
// This will vary based on what the provider is used for
|
||||
const newProvider = {
|
||||
id: crypto.randomUUID(),
|
||||
name: result.username ? `NewProvider (${result.username})` : 'NewProvider',
|
||||
type: 'newprovider',
|
||||
apiKey: result.accessToken,
|
||||
proxy: true,
|
||||
};
|
||||
|
||||
setProviders([...settings.providers, newProvider]);
|
||||
return true;
|
||||
}, [oauth, setProviders, settings.providers]);
|
||||
|
||||
return {
|
||||
...oauth,
|
||||
handleCallback: handleCallbackAndStore,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Create OAuth Callback Page
|
||||
|
||||
Create a new file `src/pages/NewProviderOAuth.tsx`:
|
||||
|
||||
```typescript
|
||||
import { useEffect } from 'react';
|
||||
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
export default function NewProviderOAuth() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const { handleCallback } = useNewProviderOAuth();
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
const code = searchParams.get('code');
|
||||
const state = searchParams.get('state');
|
||||
const error = searchParams.get('error');
|
||||
const errorDescription = searchParams.get('error_description');
|
||||
const storedState = localStorage.getItem('newprovider_oauth_state');
|
||||
|
||||
if (error) {
|
||||
toast({
|
||||
title: "NewProvider OAuth Error",
|
||||
description: errorDescription || error,
|
||||
variant: "destructive",
|
||||
});
|
||||
navigate('/settings/deploy'); // or appropriate settings page
|
||||
return;
|
||||
}
|
||||
|
||||
if (code && state && storedState) {
|
||||
handleCallback(code, state).then((success) => {
|
||||
if (success) {
|
||||
toast({
|
||||
title: "NewProvider Connected",
|
||||
description: "Successfully connected to NewProvider.",
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Connection Failed",
|
||||
description: "Failed to connect to NewProvider. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
navigate('/settings/deploy'); // or appropriate settings page
|
||||
});
|
||||
} else {
|
||||
navigate('/settings/deploy');
|
||||
}
|
||||
}, [searchParams, handleCallback, toast, navigate]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="space-y-6">
|
||||
{/* Provider logo/icon */}
|
||||
<div className="flex justify-center">
|
||||
<svg className="h-12 w-12 text-primary" viewBox="0 0 24 24">
|
||||
{/* Provider icon SVG */}
|
||||
</svg>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-semibold">Connecting to NewProvider</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Processing your NewProvider authentication...
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex justify-center">
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Add Route
|
||||
|
||||
Add the OAuth callback route to `src/AppRouter.tsx`:
|
||||
|
||||
```typescript
|
||||
import NewProviderOAuth from "./pages/NewProviderOAuth";
|
||||
|
||||
// ...
|
||||
|
||||
<Route path="/oauth/newprovider" element={<NewProviderOAuth />} />
|
||||
```
|
||||
|
||||
### 5. Add to UI
|
||||
|
||||
Add the provider to the appropriate settings page (e.g., `DeploySettings.tsx`):
|
||||
|
||||
```typescript
|
||||
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
|
||||
|
||||
// In component:
|
||||
const newProviderOAuth = useNewProviderOAuth();
|
||||
|
||||
// In PRESET_PROVIDERS array:
|
||||
{
|
||||
id: 'newprovider',
|
||||
type: 'newprovider',
|
||||
name: 'NewProvider',
|
||||
description: 'Deploy to NewProvider',
|
||||
apiKeyLabel: 'Access Token',
|
||||
apiKeyURL: 'https://provider.com/settings/tokens',
|
||||
proxy: true,
|
||||
}
|
||||
|
||||
// In the render logic, add the OAuth hook to the switch:
|
||||
const oauthHook = preset.type === 'netlify' ? netlifyOAuth :
|
||||
preset.type === 'vercel' ? vercelOAuth :
|
||||
preset.type === 'newprovider' ? newProviderOAuth : null;
|
||||
```
|
||||
|
||||
### 6. Register OAuth Application
|
||||
|
||||
Register your OAuth application with the provider:
|
||||
|
||||
1. Go to the provider's developer settings
|
||||
2. Create a new OAuth application
|
||||
3. Set the **redirect URI** to: `https://yourdomain.com/oauth/newprovider`
|
||||
4. Note the **client ID** and **client secret**
|
||||
5. Add them to your `.env` file
|
||||
|
||||
## Testing OAuth Flow
|
||||
|
||||
To test the OAuth flow locally:
|
||||
|
||||
1. **Set up a tunnel** (e.g., ngrok, cloudflared) to expose localhost:
|
||||
```bash
|
||||
npx cloudflared tunnel --url http://localhost:5173
|
||||
```
|
||||
|
||||
2. **Register OAuth app** with the tunnel URL as the redirect URI:
|
||||
```
|
||||
https://your-tunnel-url.trycloudflare.com/oauth/provider
|
||||
```
|
||||
|
||||
3. **Add credentials** to `.env`:
|
||||
```bash
|
||||
VITE_PROVIDER_OAUTH_CLIENT_ID="your_client_id"
|
||||
VITE_PROVIDER_OAUTH_CLIENT_SECRET="your_client_secret"
|
||||
```
|
||||
|
||||
4. **Start the dev server**:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
5. **Test the flow** by clicking the "Connect to Provider" button
|
||||
|
||||
## Error Handling
|
||||
|
||||
The OAuth system handles several types of errors:
|
||||
|
||||
### User Denies Authorization
|
||||
|
||||
If the user denies authorization, the provider redirects with an `error` parameter:
|
||||
```
|
||||
/oauth/provider?error=access_denied&error_description=User+denied+access
|
||||
```
|
||||
|
||||
The callback page displays an error toast and redirects to settings.
|
||||
|
||||
### Invalid State Parameter
|
||||
|
||||
If the `state` parameter doesn't match what we stored (CSRF attack), the flow is aborted and an error is shown.
|
||||
|
||||
### Token Exchange Failure
|
||||
|
||||
If the token exchange fails (invalid code, expired, etc.), an error is logged and shown to the user.
|
||||
|
||||
### Missing PKCE Verifier
|
||||
|
||||
If PKCE is enabled but the code verifier is missing from localStorage, the flow is aborted.
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **State Parameter**: Always used for CSRF protection
|
||||
2. **PKCE**: Used when supported by the provider for additional security
|
||||
3. **HTTPS Only**: OAuth should only be used over HTTPS in production
|
||||
4. **Token Storage**: Tokens are stored in browser storage (localStorage/IndexedDB)
|
||||
5. **Token Revocation**: Users can revoke tokens from the provider's settings
|
||||
6. **Scope Limitation**: Request only the minimum required scopes
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "OAuth client ID not configured"
|
||||
|
||||
The environment variables are not set. Check your `.env` file and ensure the variables are prefixed with `VITE_`.
|
||||
|
||||
### "Invalid OAuth state parameter"
|
||||
|
||||
The state parameter doesn't match. This could be caused by:
|
||||
- Multiple OAuth flows running simultaneously
|
||||
- Browser localStorage being cleared mid-flow
|
||||
- CSRF attack attempt
|
||||
|
||||
### "Failed to verify token"
|
||||
|
||||
The provider's API rejected the access token. This could be caused by:
|
||||
- Incorrect API endpoint URL
|
||||
- Token doesn't have required scopes
|
||||
- Provider API is down
|
||||
|
||||
### Redirect URI Mismatch
|
||||
|
||||
The redirect URI in your OAuth app registration must exactly match the URI in your code:
|
||||
```typescript
|
||||
redirectUri: window.location.origin + '/oauth/provider'
|
||||
```
|
||||
|
||||
For local development with a tunnel, this would be:
|
||||
```
|
||||
https://your-tunnel-url.trycloudflare.com/oauth/provider
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Always use PKCE** when the provider supports it
|
||||
2. **Request minimal scopes** - only what you need
|
||||
3. **Handle errors gracefully** - show user-friendly error messages
|
||||
4. **Clear localStorage** on errors to prevent stuck states
|
||||
5. **Validate tokens** by fetching user info after exchange
|
||||
6. **Store tokens securely** - use appropriate browser storage APIs
|
||||
7. **Provide token revocation** - link to provider's token management page
|
||||
8. **Test error cases** - user denial, network failures, etc.
|
||||
|
||||
## Future Improvements
|
||||
|
||||
Potential enhancements to the OAuth system:
|
||||
|
||||
1. **Token Refresh**: Implement refresh token flow for long-lived sessions
|
||||
2. **Token Expiry**: Track token expiration and prompt for re-authentication
|
||||
3. **Multiple Accounts**: Support multiple accounts per provider
|
||||
4. **Backend Proxy**: Optional backend service for secure token exchange
|
||||
5. **Device Flow**: Support OAuth device flow for CLI tools
|
||||
6. **Biometric Auth**: Integrate with WebAuthn for passwordless OAuth
|
||||
@@ -0,0 +1,278 @@
|
||||
# Shakespeare Plugins System
|
||||
|
||||
Shakespeare now includes a comprehensive plugins system that allows you to extend the AI's capabilities with reusable skills.
|
||||
|
||||
## Overview
|
||||
|
||||
Plugins are Git repositories that can contain **skills** - specialized AI workflows that help the AI assistant perform specific tasks more effectively. Skills are automatically discovered and made available to the AI through the `skill` tool.
|
||||
|
||||
## Features
|
||||
|
||||
- **Git-based plugins**: Clone plugins from any Git repository (GitHub, GitLab, etc.)
|
||||
- **Automatic skill discovery**: Skills are automatically found and registered from all installed plugins
|
||||
- **Configurable storage**: Plugin directory is configurable in System Settings
|
||||
- **Sync support**: Pull latest changes from plugin repositories
|
||||
- **Delete support**: Remove plugins when no longer needed
|
||||
- **AI integration**: Skills are automatically included in the system prompt and accessible via the `skill` tool
|
||||
|
||||
## User Interface
|
||||
|
||||
### AI Settings Page (`/settings/ai`)
|
||||
|
||||
The AI Settings page now includes a **Plugins** section with:
|
||||
|
||||
1. **Add Plugin**: Clone a new plugin by entering its Git URL
|
||||
2. **Plugin List**: View all installed plugins with their skills
|
||||
3. **Sync**: Pull latest changes from a plugin's Git repository
|
||||
4. **Delete**: Remove a plugin and all its skills
|
||||
|
||||
### System Settings Page (`/settings/system`)
|
||||
|
||||
The System Settings page includes a **Filesystem Paths** section where you can configure:
|
||||
|
||||
- **Plugins Directory**: Path where plugins are stored (default: `/plugins`)
|
||||
|
||||
## Plugin Structure
|
||||
|
||||
A plugin is a Git repository with the following structure:
|
||||
|
||||
```
|
||||
my-plugin/
|
||||
├── skills/
|
||||
│ ├── skill1/
|
||||
│ │ └── SKILL.md
|
||||
│ ├── skill2/
|
||||
│ │ └── SKILL.md
|
||||
│ └── ...
|
||||
└── README.md (optional)
|
||||
```
|
||||
|
||||
### Skill Format
|
||||
|
||||
Each skill is defined by a `SKILL.md` file with YAML frontmatter:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: skillname
|
||||
description: A brief description of what this skill does
|
||||
---
|
||||
|
||||
# Skill Content
|
||||
|
||||
The rest of the file contains instructions, examples, and context
|
||||
that will be provided to the AI when this skill is invoked.
|
||||
|
||||
This can include:
|
||||
- Step-by-step workflows
|
||||
- Code examples
|
||||
- Best practices
|
||||
- Domain-specific knowledge
|
||||
```
|
||||
|
||||
#### Required Frontmatter Fields
|
||||
|
||||
- **`name`**: Skill identifier (must be lowercase alphanumeric with hyphens, e.g., `myskill`, `skill-123`, `condition-based-waiting`)
|
||||
- **`description`**: Human-readable description of what the skill does
|
||||
|
||||
#### Skill Name Validation
|
||||
|
||||
Skill names must:
|
||||
- Contain only lowercase letters (a-z), numbers (0-9), and hyphens (-)
|
||||
- No spaces, underscores, uppercase letters, or other special characters
|
||||
- Examples: ✅ `myskill`, `skill-123`, `condition-based-waiting` | ❌ `My-Skill`, `skill_name`, `SKILL`
|
||||
|
||||
## How It Works
|
||||
|
||||
### For Users
|
||||
|
||||
1. **Add a Plugin**:
|
||||
- Go to Settings > AI
|
||||
- Scroll to the Plugins section
|
||||
- Click "Add Plugin"
|
||||
- Enter the Git URL (e.g., `https://github.com/user/shakespeare-skills.git`)
|
||||
- Click "Add Plugin"
|
||||
|
||||
2. **View Skills**:
|
||||
- Installed plugins show the number of skills they contain
|
||||
- Expand a plugin to see all its skills with descriptions
|
||||
|
||||
3. **Sync a Plugin**:
|
||||
- Click the "Sync" button next to a plugin to pull latest changes
|
||||
- Useful when the plugin repository is updated with new skills
|
||||
|
||||
4. **Delete a Plugin**:
|
||||
- Click the "Delete" button next to a plugin to remove it
|
||||
- All skills from that plugin will no longer be available
|
||||
|
||||
### For the AI
|
||||
|
||||
The AI assistant automatically:
|
||||
|
||||
1. **Discovers Skills**: All skills from installed plugins are scanned on startup
|
||||
2. **Includes in System Prompt**: Skills are listed in the system prompt with their names, descriptions, and paths
|
||||
3. **Enforces Usage**: The system prompt instructs the AI to use skills whenever applicable
|
||||
4. **Accesses via Tool**: The AI calls the `skill` tool with a skill name to load its content
|
||||
|
||||
Example AI workflow:
|
||||
```
|
||||
User: "Help me build a Nostr marketplace"
|
||||
|
||||
AI: [Sees "nostrmarket" skill in system prompt]
|
||||
[Calls skill tool with name="nostrmarket"]
|
||||
[Receives SKILL.md content with marketplace implementation guide]
|
||||
[Follows the skill's instructions to build the marketplace]
|
||||
```
|
||||
|
||||
## Technical Implementation
|
||||
|
||||
### Key Files
|
||||
|
||||
- **`src/lib/plugins.ts`**: Core plugin and skill management functions
|
||||
- **`src/lib/tools/SkillTool.ts`**: AI tool for loading skill content
|
||||
- **`src/hooks/usePlugins.ts`**: React hook for plugin CRUD operations
|
||||
- **`src/components/PluginsSection.tsx`**: UI component for managing plugins
|
||||
- **`src/lib/system.ts`**: Updated to include skills in system prompt
|
||||
|
||||
### API
|
||||
|
||||
#### `getPlugins(fs, pluginsPath)`
|
||||
Returns array of plugin names (directory basenames).
|
||||
|
||||
#### `getAllSkills(fs, pluginsPath)`
|
||||
Returns array of all skills from all plugins.
|
||||
|
||||
#### `findSkill(fs, pluginsPath, skillName)`
|
||||
Finds a skill by name across all plugins.
|
||||
|
||||
#### `readSkillContent(fs, skill)`
|
||||
Reads the SKILL.md content for a skill.
|
||||
|
||||
#### `deletePlugin(fs, pluginsPath, pluginName)`
|
||||
Recursively deletes a plugin directory.
|
||||
|
||||
### Skill Tool
|
||||
|
||||
The `SkillTool` is exposed to the AI as the `skill` function:
|
||||
|
||||
```typescript
|
||||
{
|
||||
name: "skill",
|
||||
description: "Load and execute a skill from the configured plugins",
|
||||
parameters: {
|
||||
name: "The name of the skill to execute"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When called, it:
|
||||
1. Searches all plugins for a skill with the matching name
|
||||
2. Returns the full SKILL.md content
|
||||
3. Includes metadata (plugin name, description, path)
|
||||
|
||||
### Storage
|
||||
|
||||
Plugins are stored in the configured plugins directory:
|
||||
|
||||
- **Browser**: `/plugins` (IndexedDB via LightningFS)
|
||||
- **Electron (Windows)**: `~/AppData/Local/shakespeare/plugins`
|
||||
- **Electron (macOS)**: `~/Library/Application Support/shakespeare/plugins`
|
||||
- **Electron (Linux)**: `~/.config/shakespeare/plugins`
|
||||
|
||||
## System Prompt Integration
|
||||
|
||||
The system prompt now includes a **Skills** section that:
|
||||
|
||||
1. Lists all available skills with their names, descriptions, plugins, and paths
|
||||
2. Instructs the AI to use skills whenever applicable
|
||||
3. Provides the Settings > AI URL for users to configure skills
|
||||
4. Includes this section even when no skills are configured (to inform users about the feature)
|
||||
|
||||
Example system prompt section:
|
||||
|
||||
```
|
||||
## Skills
|
||||
|
||||
You have access to the following skills. **Skills MUST be used whenever applicable** by calling the `skill` tool with the skill name.
|
||||
|
||||
Available skills:
|
||||
|
||||
- **nostrmarket**: Build a Nostr marketplace application
|
||||
- Plugin: nostr-skills
|
||||
- Path: /plugins/nostr-skills/skills/nostrmarket
|
||||
|
||||
**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.
|
||||
|
||||
Users can configure skills in Settings > AI (https://shakespeare.diy/settings/ai) by adding plugins that contain skills.
|
||||
```
|
||||
|
||||
## Creating Your Own Plugin
|
||||
|
||||
1. **Create a Git repository** with the plugin structure
|
||||
2. **Add skills** in the `skills/` directory
|
||||
3. **Write SKILL.md files** with frontmatter and content
|
||||
4. **Push to GitHub/GitLab** or any Git hosting service
|
||||
5. **Share the Git URL** with others to install your plugin
|
||||
|
||||
### Example Plugin Repository
|
||||
|
||||
```
|
||||
my-shakespeare-skills/
|
||||
├── README.md
|
||||
└── skills/
|
||||
├── webdesign/
|
||||
│ └── SKILL.md
|
||||
└── database/
|
||||
└── SKILL.md
|
||||
```
|
||||
|
||||
**skills/webdesign/SKILL.md**:
|
||||
```markdown
|
||||
---
|
||||
name: webdesign
|
||||
description: Create beautiful, modern web designs with best practices
|
||||
---
|
||||
|
||||
# Web Design Skill
|
||||
|
||||
When designing web interfaces, follow these principles:
|
||||
|
||||
1. **Use a consistent color palette** (3-5 colors + neutrals)
|
||||
2. **Implement proper spacing** (8px grid system)
|
||||
3. **Choose readable fonts** (18px+ for body text)
|
||||
4. **Ensure accessibility** (WCAG 2.1 AA compliance)
|
||||
|
||||
[... detailed instructions ...]
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Plugins Directory Path
|
||||
|
||||
Configure in **Settings > System > Filesystem Paths**:
|
||||
|
||||
- Default browser: `/plugins`
|
||||
- Default Electron: OS-specific (see Storage section)
|
||||
- Custom: Any absolute path
|
||||
|
||||
Changes take effect immediately.
|
||||
|
||||
## Limitations
|
||||
|
||||
- Plugins must be Git repositories (no ZIP uploads)
|
||||
- Skills must be in `skills/` subdirectory
|
||||
- Skill names must be alphanumeric lowercase only
|
||||
- Each skill must have a `SKILL.md` file with required frontmatter
|
||||
- No automatic skill updates (users must manually sync)
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Potential future features:
|
||||
|
||||
- Plugin marketplace/registry
|
||||
- Automatic skill updates
|
||||
- Skill versioning
|
||||
- Skill dependencies
|
||||
- Plugin configuration files
|
||||
- Skill categories/tags
|
||||
- Skill search functionality
|
||||
- Plugin publishing workflow
|
||||
@@ -0,0 +1,5 @@
|
||||
package.json
|
||||
package-lock.json
|
||||
README.md
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -0,0 +1,582 @@
|
||||
# Shakespeare Electron - Complete Guide
|
||||
|
||||
This guide provides comprehensive documentation for developing, building, and troubleshooting the Shakespeare Electron desktop application.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Filesystem Architecture](#filesystem-architecture)
|
||||
2. [Terminal Integration](#terminal-integration)
|
||||
3. [Development Workflow](#development-workflow)
|
||||
4. [Building for Distribution](#building-for-distribution)
|
||||
5. [Troubleshooting](#troubleshooting)
|
||||
|
||||
---
|
||||
|
||||
## Filesystem Architecture
|
||||
|
||||
### Overview
|
||||
|
||||
The Electron version uses your local OS filesystem at `~/shakespeare` instead of IndexedDB, providing direct file access and unlimited storage.
|
||||
|
||||
### Path Resolution
|
||||
|
||||
All paths are relative to `~/shakespeare`:
|
||||
- `/projects/my-app/` → `~/shakespeare/projects/my-app/`
|
||||
- `/tmp/upload.txt` → `~/shakespeare/tmp/upload.txt`
|
||||
- `/config/ai.json` → `~/shakespeare/config/ai.json`
|
||||
|
||||
### Implementation
|
||||
|
||||
**Automatic Adapter Selection** (`src/App.tsx`):
|
||||
```typescript
|
||||
const fs = window.electron?.isElectron
|
||||
? new NodeFSAdapter() // Real filesystem
|
||||
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
|
||||
```
|
||||
|
||||
**IPC Communication Flow:**
|
||||
1. **Renderer** (`NodeFSAdapter.ts`) - Calls `window.electron.fs.*` methods
|
||||
2. **Preload** (`preload.js`) - Exposes API via `contextBridge`
|
||||
3. **Main** (`main.js`) - Handles IPC with `ipcMain.handle()`, performs filesystem operations
|
||||
|
||||
### Supported Operations
|
||||
|
||||
All standard filesystem operations are supported:
|
||||
- **Files**: `readFile`, `writeFile`, `unlink`, `rename`
|
||||
- **Directories**: `readdir`, `mkdir`, `rmdir`
|
||||
- **Metadata**: `stat`, `lstat`
|
||||
- **Symlinks**: `readlink`, `symlink`
|
||||
|
||||
### Benefits
|
||||
|
||||
✅ **No storage limits** - Only limited by disk space
|
||||
✅ **Direct access** - Use any editor, file manager, or Git client
|
||||
✅ **Easy backup** - Standard backup tools work
|
||||
✅ **Better performance** - Faster for large projects
|
||||
✅ **Data portability** - Copy projects between machines
|
||||
|
||||
### Data Migration
|
||||
|
||||
**Browser to Electron:**
|
||||
1. Export project as ZIP from browser
|
||||
2. Import ZIP in Electron version
|
||||
|
||||
**Electron to Browser:**
|
||||
1. Export project as ZIP from Electron
|
||||
2. Import ZIP in browser version
|
||||
|
||||
---
|
||||
|
||||
## Terminal Integration
|
||||
|
||||
### Overview
|
||||
|
||||
The Electron version uses the **real OS terminal** instead of the virtual terminal, providing access to all system commands.
|
||||
|
||||
### Architecture
|
||||
|
||||
**ShellTool Detection** (`src/lib/tools/ShellTool.ts`):
|
||||
```typescript
|
||||
if (window.electron?.shell) {
|
||||
// Use real OS shell
|
||||
const result = await window.electron.shell.exec(command, workingDir);
|
||||
} else {
|
||||
// Use virtual command system
|
||||
const result = await executeCommand(command, workingDir, fs);
|
||||
}
|
||||
```
|
||||
|
||||
**Shell Execution** (`electron/main.js`):
|
||||
- Uses `child_process.spawn()` to execute commands
|
||||
- Windows: Uses `cmd.exe`
|
||||
- macOS/Linux: Uses `/bin/sh`
|
||||
- Executes in project directory: `~/shakespeare/projects/{projectId}`
|
||||
|
||||
### Features
|
||||
|
||||
**All OS Commands Available:**
|
||||
```bash
|
||||
# Package managers
|
||||
$ npm install
|
||||
$ yarn add lodash
|
||||
$ pnpm update
|
||||
|
||||
# Build tools
|
||||
$ vite build
|
||||
$ webpack --config webpack.config.js
|
||||
$ tsc --noEmit
|
||||
|
||||
# Git operations
|
||||
$ git commit -m "Update"
|
||||
$ git push origin main
|
||||
|
||||
# System utilities
|
||||
$ grep -r "TODO" src/
|
||||
$ curl https://api.example.com
|
||||
$ python script.py
|
||||
```
|
||||
|
||||
**Native Shell Features:**
|
||||
- Pipes: `ls | grep ".ts$"`
|
||||
- Redirection: `echo "test" > file.txt`
|
||||
- Environment variables: `$PATH`, `$HOME`
|
||||
- Command chaining: `npm install && npm run build`
|
||||
|
||||
### ANSI Code Stripping
|
||||
|
||||
Output from shell commands is cleaned for AI consumption:
|
||||
- Color codes removed (e.g., `\u001b[31m`)
|
||||
- Cursor control sequences stripped
|
||||
- Text formatting removed (bold, italic)
|
||||
- Newlines preserved
|
||||
|
||||
**Example:**
|
||||
```
|
||||
Input: \u001b[1m\u001b[32madded 142 packages\u001b[39m\u001b[22m in 3s
|
||||
Output: added 142 packages in 3s
|
||||
```
|
||||
|
||||
Terminal UI still shows colored output for users.
|
||||
|
||||
### Platform Support
|
||||
|
||||
| Platform | Shell | Notes |
|
||||
|----------|-------|-------|
|
||||
| macOS | `/bin/sh` | All Unix commands available |
|
||||
| Linux | `/bin/sh` | Standard Linux utilities |
|
||||
| Windows | `cmd.exe` | Windows commands, consider Git Bash for Unix tools |
|
||||
|
||||
### Security
|
||||
|
||||
- Commands run with user permissions (no sudo/elevation)
|
||||
- Working directory sandboxed to `~/shakespeare`
|
||||
- Environment variables inherited from Electron process
|
||||
|
||||
---
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Running in Development Mode
|
||||
|
||||
```bash
|
||||
npm run electron:dev
|
||||
```
|
||||
|
||||
This will:
|
||||
1. Start Vite dev server on http://localhost:5173
|
||||
2. Wait for server to be ready
|
||||
3. Launch Electron with hot reload
|
||||
4. Open DevTools automatically
|
||||
|
||||
### Testing Shell Execution
|
||||
|
||||
Use the provided test script to verify shell functionality:
|
||||
|
||||
```bash
|
||||
# Start Electron in dev mode
|
||||
npm run electron:dev
|
||||
|
||||
# Open DevTools (View > Toggle Developer Tools)
|
||||
# Paste contents of electron/test-terminal.js into console
|
||||
```
|
||||
|
||||
The test script verifies:
|
||||
- Basic command execution
|
||||
- File listing
|
||||
- Node.js version check
|
||||
- Error handling
|
||||
- Working directory
|
||||
|
||||
### Debugging
|
||||
|
||||
**Renderer Process:**
|
||||
- DevTools open automatically in dev mode
|
||||
- Or press `Cmd+Option+I` (macOS) / `Ctrl+Shift+I` (Windows/Linux)
|
||||
|
||||
**Main Process:**
|
||||
```bash
|
||||
# Enable verbose logging
|
||||
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
|
||||
```
|
||||
|
||||
**Check Configuration:**
|
||||
```bash
|
||||
node electron/test-config.js
|
||||
```
|
||||
|
||||
### File Watching
|
||||
|
||||
In development mode:
|
||||
- Vite provides hot module replacement
|
||||
- Changes to React components reload instantly
|
||||
- Electron process restarts on main.js changes (via `nodemon` in the script)
|
||||
|
||||
---
|
||||
|
||||
## Building for Distribution
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 18+ installed
|
||||
- All dependencies installed: `npm install`
|
||||
- Web build completed: `npm run build`
|
||||
|
||||
### Build Commands
|
||||
|
||||
**Current Platform:**
|
||||
```bash
|
||||
npm run electron:build
|
||||
```
|
||||
|
||||
**Specific Platforms:**
|
||||
```bash
|
||||
npm run electron:build:mac # macOS (DMG + ZIP)
|
||||
npm run electron:build:win # Windows (NSIS + Portable)
|
||||
npm run electron:build:linux # Linux (AppImage, DEB, RPM)
|
||||
npm run electron:build:all # All platforms
|
||||
```
|
||||
|
||||
### Build Output
|
||||
|
||||
```
|
||||
electron-dist/
|
||||
├── mac/
|
||||
│ ├── Shakespeare.app # macOS application bundle
|
||||
│ ├── Shakespeare.dmg # DMG installer
|
||||
│ └── Shakespeare-mac.zip # ZIP archive
|
||||
├── win-unpacked/
|
||||
│ └── Shakespeare.exe # Windows executable
|
||||
├── Shakespeare Setup.exe # NSIS installer
|
||||
├── Shakespeare Portable.exe # Portable executable
|
||||
├── shakespeare-*.AppImage # Linux AppImage
|
||||
├── shakespeare_*.deb # Debian package
|
||||
└── shakespeare-*.rpm # RPM package
|
||||
```
|
||||
|
||||
### Platform-Specific Notes
|
||||
|
||||
**macOS:**
|
||||
- Builds for Intel (x64) and Apple Silicon (arm64)
|
||||
- Code signing optional for development
|
||||
- For distribution: Requires Apple Developer account
|
||||
|
||||
**Windows:**
|
||||
- Builds for x64 and ARM64
|
||||
- No code signing required for development
|
||||
- For distribution: EV certificate recommended for SmartScreen
|
||||
|
||||
**Linux:**
|
||||
- Builds for x64 and ARM64
|
||||
- AppImage requires FUSE: `sudo apt-get install fuse`
|
||||
- DEB/RPM packages can be installed with package managers
|
||||
|
||||
### Cross-Platform Limitations
|
||||
|
||||
- **macOS builds require macOS** (for code signing)
|
||||
- Windows/Linux can be built from any platform
|
||||
- Use GitHub Actions or CI/CD for multi-platform builds
|
||||
|
||||
### Code Signing
|
||||
|
||||
**Development (Disable Signing):**
|
||||
|
||||
Edit `electron/builder.config.js`:
|
||||
```javascript
|
||||
mac: {
|
||||
identity: null, // Disable code signing
|
||||
}
|
||||
```
|
||||
|
||||
**Production (macOS):**
|
||||
1. Obtain Apple Developer account
|
||||
2. Create certificates in Xcode
|
||||
3. Configure signing in builder.config.js
|
||||
4. See: https://www.electron.build/code-signing
|
||||
|
||||
**Production (Windows):**
|
||||
1. Obtain EV code signing certificate
|
||||
2. Configure in builder.config.js
|
||||
3. Builds reputation with SmartScreen over time
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Development Issues
|
||||
|
||||
#### Port 5173 Already in Use
|
||||
|
||||
**Solution:**
|
||||
```bash
|
||||
# Find and kill the process
|
||||
lsof -i :5173 # macOS/Linux
|
||||
netstat -ano | findstr :5173 # Windows
|
||||
|
||||
# Or change the port in vite.config.ts
|
||||
export default defineConfig({
|
||||
server: { port: 5174 },
|
||||
});
|
||||
```
|
||||
|
||||
#### Blank Screen on Launch
|
||||
|
||||
**Browser Mode:**
|
||||
1. Check Vite server is running: http://localhost:5173
|
||||
2. Check Electron console for errors
|
||||
3. Verify URL in `electron/main.js` matches Vite server
|
||||
4. Clear cache: Delete `node_modules/.vite`
|
||||
|
||||
**Production Build:**
|
||||
1. Ensure `base: './'` is set in `vite.config.ts`
|
||||
2. Check `dist/` directory contains all files
|
||||
3. Look for "Failed to load resource" errors in console
|
||||
4. Verify file:// protocol is used in loadURL
|
||||
|
||||
#### Assets Fail to Load: "net::ERR_FILE_NOT_FOUND"
|
||||
|
||||
**Problem:** CSS/JS fail to load with `file:///assets/npm/...` errors
|
||||
|
||||
**Solution:** Add to `vite.config.ts`:
|
||||
```typescript
|
||||
export default defineConfig(() => ({
|
||||
base: './', // Required for Electron
|
||||
// ... rest of config
|
||||
}))
|
||||
```
|
||||
|
||||
Then rebuild: `npm run build`
|
||||
|
||||
#### 404 Error: Page Not Found
|
||||
|
||||
**Problem:** App shows "404: Oops! Page not found" on launch
|
||||
|
||||
**Solution:** Verify `HashRouter` is used in Electron.
|
||||
|
||||
Check `src/AppRouter.tsx`:
|
||||
```typescript
|
||||
const Router = window.electron?.isElectron ? HashRouter : BrowserRouter;
|
||||
```
|
||||
|
||||
Rebuild: `npm run build && npm run electron:build`
|
||||
|
||||
#### Service Worker Errors
|
||||
|
||||
**Solution:** Service workers don't work with `file://` protocol.
|
||||
|
||||
Check `src/main.tsx`:
|
||||
```typescript
|
||||
if ('serviceWorker' in navigator && !window.electron?.isElectron) {
|
||||
// Only register in web environment
|
||||
}
|
||||
```
|
||||
|
||||
#### CSP Font Errors
|
||||
|
||||
**Solution:** Update CSP in `index.html`:
|
||||
```html
|
||||
<meta http-equiv="content-security-policy"
|
||||
content="... font-src 'self' data:; ...">
|
||||
```
|
||||
|
||||
#### Broken SVG Images
|
||||
|
||||
**Problem:** Logo/SVG files show as broken
|
||||
|
||||
**Solution:** Import SVG files properly:
|
||||
```typescript
|
||||
// ❌ Wrong
|
||||
<img src="/shakespeare.svg" alt="Logo" />
|
||||
|
||||
// ✅ Correct
|
||||
import logo from '/shakespeare.svg?url';
|
||||
<img src={logo} alt="Logo" />
|
||||
```
|
||||
|
||||
#### Preload Script ESM Errors
|
||||
|
||||
**Solution:** Requires `sandbox: false` in webPreferences.
|
||||
|
||||
Check `electron/main.js`:
|
||||
```javascript
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true, // Still enabled
|
||||
sandbox: false, // Disabled for ESM
|
||||
webSecurity: true,
|
||||
}
|
||||
```
|
||||
|
||||
### Build Issues
|
||||
|
||||
#### Build Fails with "Cannot find module"
|
||||
|
||||
**Solutions:**
|
||||
1. Install dependencies: `npm install`
|
||||
2. Clear and reinstall: `rm -rf node_modules package-lock.json && npm install`
|
||||
3. Build web first: `npm run build`
|
||||
4. Verify `dist/` exists
|
||||
5. Check config: `node electron/test-config.js`
|
||||
|
||||
#### Icons Not Appearing
|
||||
|
||||
**Solution:** Should work automatically with `public/shakespeare-512x512.png`.
|
||||
|
||||
If not:
|
||||
1. Verify PNG exists
|
||||
2. Check build output for icon errors
|
||||
3. Try: `npm run electron:icons` (requires ImageMagick)
|
||||
4. Check paths in `electron/builder.config.js`
|
||||
|
||||
#### Code Signing Errors (macOS)
|
||||
|
||||
**Development:** Disable signing:
|
||||
```javascript
|
||||
mac: {
|
||||
identity: null,
|
||||
}
|
||||
```
|
||||
|
||||
**Production:** Requires Apple Developer account and certificates.
|
||||
|
||||
#### App Won't Launch After Build
|
||||
|
||||
**Solutions:**
|
||||
1. Check console/terminal for errors
|
||||
2. Try unpacked version first
|
||||
3. macOS: Check Security & Privacy settings
|
||||
4. Windows: Check Windows Defender logs
|
||||
5. Verify `dist/` contains valid files
|
||||
|
||||
### Runtime Issues
|
||||
|
||||
#### App Crashes on Startup
|
||||
|
||||
**Solutions:**
|
||||
1. Check crash logs:
|
||||
- macOS: `~/Library/Logs/Shakespeare/`
|
||||
- Windows: `%APPDATA%\Shakespeare\logs\`
|
||||
- Linux: `~/.config/Shakespeare/logs/`
|
||||
2. Run from terminal to see errors
|
||||
3. Test web build in browser first
|
||||
|
||||
#### Shell Execution Error: "spawn /bin/sh ENOENT"
|
||||
|
||||
**Problem:** Terminal commands fail with spawn error
|
||||
|
||||
**Root Cause:** Working directory doesn't exist
|
||||
|
||||
**Solution:** Should be fixed - main.js creates directories automatically.
|
||||
|
||||
**Debug:**
|
||||
1. Open DevTools
|
||||
2. Check console for "Shell exec in directory: ..."
|
||||
3. Verify directory exists: `ls -la ~/shakespeare/projects/`
|
||||
4. Manually create if needed: `mkdir -p ~/shakespeare/projects`
|
||||
|
||||
#### External Links Not Opening
|
||||
|
||||
**Solution:** Should open in default browser automatically.
|
||||
|
||||
Check `electron/main.js` has:
|
||||
```javascript
|
||||
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
|
||||
shell.openExternal(url);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
```
|
||||
|
||||
### Platform-Specific Issues
|
||||
|
||||
#### macOS: "App is damaged and can't be opened"
|
||||
|
||||
**Solutions:**
|
||||
1. Development: `xattr -cr /path/to/Shakespeare.app`
|
||||
2. Distribution: Requires code signing
|
||||
3. Users: Right-click → Open (instead of double-click)
|
||||
|
||||
#### Windows: "Windows protected your PC"
|
||||
|
||||
**Solutions:**
|
||||
1. Testing: Click "More info" → "Run anyway"
|
||||
2. Distribution: Requires EV code signing
|
||||
3. Build reputation over time
|
||||
|
||||
#### Linux: "Permission denied"
|
||||
|
||||
**Solutions:**
|
||||
1. Make executable: `chmod +x Shakespeare*.AppImage`
|
||||
2. Install FUSE: `sudo apt-get install fuse`
|
||||
3. Try DEB/RPM package instead
|
||||
|
||||
### Performance Issues
|
||||
|
||||
#### App Feels Slow
|
||||
|
||||
**Solutions:**
|
||||
1. Close DevTools
|
||||
2. Check system resources
|
||||
3. Use production build
|
||||
4. Disable hardware acceleration in `main.js`:
|
||||
```javascript
|
||||
app.disableHardwareAcceleration();
|
||||
```
|
||||
|
||||
#### High Memory Usage
|
||||
|
||||
**Solutions:**
|
||||
1. Normal for Chromium-based apps
|
||||
2. Close unused projects
|
||||
3. Restart app periodically
|
||||
4. Check for memory leaks in web code
|
||||
|
||||
---
|
||||
|
||||
## Getting Help
|
||||
|
||||
If issues persist:
|
||||
|
||||
1. **Check existing issues:** https://gitlab.com/soapbox-pub/shakespeare/-/issues
|
||||
2. **Create new issue** with:
|
||||
- OS and version
|
||||
- Electron version: `npm list electron`
|
||||
- Steps to reproduce
|
||||
- Error messages/logs
|
||||
- Screenshots
|
||||
3. **Community support:** Check project README for links
|
||||
|
||||
## Useful Commands
|
||||
|
||||
**Complete rebuild:**
|
||||
```bash
|
||||
rm -rf node_modules dist electron-dist package-lock.json
|
||||
npm install
|
||||
npm run build
|
||||
npm run electron:build
|
||||
```
|
||||
|
||||
**Check versions:**
|
||||
```bash
|
||||
npm list electron
|
||||
node --version
|
||||
npm --version
|
||||
```
|
||||
|
||||
**Verbose logging:**
|
||||
```bash
|
||||
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
|
||||
```
|
||||
|
||||
**Check build contents:**
|
||||
```bash
|
||||
npm run electron:build -- --dir
|
||||
ls -la electron-dist/[platform]-unpacked/
|
||||
```
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Documentation](https://www.electronjs.org/docs)
|
||||
- [electron-builder Documentation](https://www.electron.build/)
|
||||
- [Electron Security](https://www.electronjs.org/docs/latest/tutorial/security)
|
||||
- [Debugging Electron](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process)
|
||||
- [Shakespeare Main Docs](../README.md)
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env node
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
import electron from 'electron';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const appPath = join(__dirname, '..');
|
||||
|
||||
const child = spawn(electron, [appPath], {
|
||||
stdio: 'inherit',
|
||||
windowsHide: false,
|
||||
});
|
||||
|
||||
child.on('close', code => process.exit(code ?? 0));
|
||||
child.on('error', err => {
|
||||
console.error('Failed to launch Electron:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
process.on('SIGINT', () => child.kill('SIGINT'));
|
||||
process.on('SIGTERM', () => child.kill('SIGTERM'));
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* TypeScript definitions for the Electron API exposed to the renderer process.
|
||||
*
|
||||
* Add this to your tsconfig.json include array to use these types:
|
||||
* "include": ["src", "electron/electron.d.ts"]
|
||||
*/
|
||||
|
||||
interface DirectoryEntry {
|
||||
name: string;
|
||||
isDirectory: boolean;
|
||||
isFile: boolean;
|
||||
}
|
||||
|
||||
interface StatResult {
|
||||
isDirectory: boolean;
|
||||
isFile: boolean;
|
||||
isBlockDevice: boolean;
|
||||
isCharacterDevice: boolean;
|
||||
isSymbolicLink: boolean;
|
||||
isFIFO: boolean;
|
||||
isSocket: boolean;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
ctimeMs: number;
|
||||
atimeMs: number;
|
||||
// Timestamps (serialized as numbers for IPC)
|
||||
mtime: number;
|
||||
ctime: number;
|
||||
atime: number;
|
||||
}
|
||||
|
||||
interface ElectronFSAPI {
|
||||
readFile(path: string, encoding?: string): Promise<string | number[]>;
|
||||
writeFile(path: string, data: string | number[], encoding?: string): Promise<void>;
|
||||
readdir(path: string, withFileTypes?: boolean): Promise<string[] | DirectoryEntry[]>;
|
||||
mkdir(path: string, recursive?: boolean): Promise<void>;
|
||||
stat(path: string): Promise<StatResult>;
|
||||
lstat(path: string): Promise<StatResult>;
|
||||
unlink(path: string): Promise<void>;
|
||||
rmdir(path: string): Promise<void>;
|
||||
rename(oldPath: string, newPath: string): Promise<void>;
|
||||
readlink(path: string): Promise<string>;
|
||||
symlink(target: string, path: string): Promise<void>;
|
||||
}
|
||||
|
||||
interface ShellExecResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number;
|
||||
}
|
||||
|
||||
interface ElectronShellAPI {
|
||||
/**
|
||||
* Execute a shell command on the host OS.
|
||||
* @param command - The command to execute
|
||||
* @param cwd - Working directory (relative to ~/shakespeare)
|
||||
* @returns Promise with stdout, stderr, and exit code
|
||||
*/
|
||||
exec(command: string, cwd?: string): Promise<ShellExecResult>;
|
||||
}
|
||||
|
||||
interface ElectronAPI {
|
||||
/**
|
||||
* Get the user's home directory path.
|
||||
*/
|
||||
homedir: string;
|
||||
|
||||
/**
|
||||
* Get the current platform.
|
||||
* @returns 'darwin' | 'win32' | 'linux'
|
||||
*/
|
||||
platform(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Get the application version from package.json.
|
||||
* @returns Version string (e.g., "1.0.0")
|
||||
*/
|
||||
version(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Filesystem API for accessing the local OS filesystem.
|
||||
* All paths are relative to ~/shakespeare directory.
|
||||
*/
|
||||
fs: ElectronFSAPI;
|
||||
|
||||
/**
|
||||
* Shell API for executing real shell commands on the host OS.
|
||||
* All paths in commands are relative to ~/shakespeare directory.
|
||||
*/
|
||||
shell: ElectronShellAPI;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
/**
|
||||
* Electron API exposed via preload script.
|
||||
* Only available when running in Electron.
|
||||
*/
|
||||
electron?: ElectronAPI;
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
import { app, BrowserWindow, ipcMain, shell, Menu, protocol } from 'electron';
|
||||
import { spawn } from 'child_process';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs/promises';
|
||||
import os from 'os';
|
||||
|
||||
// ESM equivalent of __dirname
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
let mainWindow;
|
||||
|
||||
function createWindow() {
|
||||
// Remove the default menu (File, Edit, View, etc.)
|
||||
Menu.setApplicationMenu(null);
|
||||
|
||||
// Create the browser window.
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1400,
|
||||
height: 900,
|
||||
minWidth: 800,
|
||||
minHeight: 600,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
sandbox: false, // Disabled to support ESM in preload
|
||||
webSecurity: true,
|
||||
},
|
||||
icon: path.join(__dirname, 'dist/shakespeare-512x512.png'),
|
||||
title: 'Shakespeare',
|
||||
backgroundColor: '#ffffff',
|
||||
});
|
||||
|
||||
// Enable DevTools keyboard shortcut (Ctrl+Shift+I / Cmd+Option+I)
|
||||
mainWindow.webContents.on('before-input-event', (event, input) => {
|
||||
// Check for Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac)
|
||||
if (input.control && input.shift && input.key.toLowerCase() === 'i') {
|
||||
mainWindow.webContents.toggleDevTools();
|
||||
event.preventDefault();
|
||||
}
|
||||
// Also support F12
|
||||
if (input.key === 'F12') {
|
||||
mainWindow.webContents.toggleDevTools();
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
// Load the app
|
||||
if (process.env.ELECTRON_DEV) {
|
||||
// Development mode - load from Vite dev server
|
||||
console.log('Loading from Vite dev server: http://localhost:5173');
|
||||
mainWindow.loadURL('http://localhost:5173');
|
||||
mainWindow.webContents.openDevTools();
|
||||
} else {
|
||||
// Production mode - load from custom protocol
|
||||
// This allows absolute paths like /shakespeare.svg to work naturally
|
||||
console.log('Loading from app:// protocol: app://./index.html');
|
||||
mainWindow.loadURL('app://./index.html');
|
||||
}
|
||||
|
||||
// Log any load errors
|
||||
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
|
||||
console.error('Failed to load:', validatedURL, errorCode, errorDescription);
|
||||
});
|
||||
|
||||
// Log successful load
|
||||
mainWindow.webContents.on('did-finish-load', () => {
|
||||
console.log('Successfully loaded app');
|
||||
});
|
||||
|
||||
// Handle window close
|
||||
mainWindow.on('closed', () => {
|
||||
mainWindow = null;
|
||||
});
|
||||
}
|
||||
|
||||
// Register custom protocol scheme before app is ready (required for privileges)
|
||||
if (!process.env.ELECTRON_DEV) {
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: 'app',
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
// This method will be called when Electron has finished
|
||||
// initialization and is ready to create browser windows.
|
||||
app.whenReady().then(async () => {
|
||||
// Register the app:// protocol to serve files from dist/
|
||||
// This allows absolute paths (/) to work naturally without base: './'
|
||||
if (!process.env.ELECTRON_DEV) {
|
||||
protocol.registerFileProtocol('app', (request, callback) => {
|
||||
// Remove 'app://' prefix and normalize path
|
||||
let filePath = request.url.replace('app://', '');
|
||||
|
||||
// Remove trailing slashes
|
||||
filePath = filePath.replace(/\/+$/, '');
|
||||
|
||||
// Handle root path
|
||||
if (filePath === '' || filePath === '/') {
|
||||
filePath = 'index.html';
|
||||
}
|
||||
|
||||
// Remove leading slash if present
|
||||
if (filePath.startsWith('/')) {
|
||||
filePath = filePath.substring(1);
|
||||
}
|
||||
|
||||
// Resolve to dist directory
|
||||
const fullPath = path.join(__dirname, 'dist', filePath);
|
||||
|
||||
console.log('Protocol handler:', request.url, '->', fullPath);
|
||||
callback({ path: fullPath });
|
||||
});
|
||||
}
|
||||
|
||||
createWindow();
|
||||
|
||||
app.on('activate', () => {
|
||||
// On macOS it's common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Quit when all windows are closed, except on macOS.
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
// Handle app-level events
|
||||
app.on('web-contents-created', (event, contents) => {
|
||||
// Security: Prevent navigation to external sites
|
||||
contents.on('will-navigate', (event, navigationUrl) => {
|
||||
const parsedUrl = new URL(navigationUrl);
|
||||
|
||||
// Allow navigation within the app
|
||||
if (parsedUrl.origin === 'http://localhost:5173' ||
|
||||
parsedUrl.protocol === 'file:') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Block all other navigation
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
// Security: Prevent opening new windows
|
||||
contents.setWindowOpenHandler(({ url }) => {
|
||||
// Open external links in the default browser
|
||||
shell.openExternal(url);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
});
|
||||
|
||||
// IPC handlers can be added here if needed for future Electron-specific features
|
||||
// For example: file system access, native dialogs, etc.
|
||||
|
||||
// Example: Handle getting app version
|
||||
ipcMain.handle('get-app-version', () => {
|
||||
return app.getVersion();
|
||||
});
|
||||
|
||||
// Example: Handle getting platform
|
||||
ipcMain.handle('get-platform', () => {
|
||||
return process.platform;
|
||||
});
|
||||
|
||||
// Helper function to expand tilde (~) in paths
|
||||
function expandTilde(filepath) {
|
||||
if (filepath.startsWith('~/') || filepath === '~') {
|
||||
return path.join(os.homedir(), filepath.slice(1));
|
||||
}
|
||||
return filepath;
|
||||
}
|
||||
|
||||
// Filesystem IPC handlers
|
||||
ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
|
||||
if (!filePath) {
|
||||
const err = new Error('Failed to read file: path is required');
|
||||
err.code = 'EINVAL';
|
||||
// Don't log - empty paths are expected from isomorphic-git's ref resolution
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
const data = await fs.readFile(fullPath, encoding ? { encoding } : undefined);
|
||||
// If no encoding, convert Buffer to array for IPC serialization
|
||||
return encoding ? data : Array.from(data);
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
// Serialize the error code as a regular property so it survives IPC
|
||||
const err = new Error(`Failed to read file ${filePath}: ${error.message}`);
|
||||
// Copy enumerable properties including code
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
// Don't log ENOENT errors - these are expected for git packed objects and missing refs
|
||||
// Only log unexpected errors
|
||||
if (error.code !== 'ENOENT' && error.code !== 'EINVAL') {
|
||||
console.error(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:writeFile', async (event, filePath, data, encoding) => {
|
||||
if (!filePath) {
|
||||
const err = new Error('Failed to write file: path is required');
|
||||
err.code = 'EINVAL';
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
// Ensure parent directory exists
|
||||
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
||||
// Convert array back to Buffer if needed
|
||||
const dataToWrite = Array.isArray(data) ? Buffer.from(data) : data;
|
||||
await fs.writeFile(fullPath, dataToWrite, encoding ? { encoding } : undefined);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to write file ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
|
||||
try {
|
||||
const fullPath = expandTilde(dirPath);
|
||||
const entries = await fs.readdir(fullPath, { withFileTypes: !!withFileTypes });
|
||||
|
||||
if (withFileTypes) {
|
||||
// Convert Dirent objects to plain objects for IPC
|
||||
return entries.map(entry => ({
|
||||
name: entry.name,
|
||||
isDirectory: entry.isDirectory(),
|
||||
isFile: entry.isFile(),
|
||||
}));
|
||||
}
|
||||
|
||||
return entries;
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
// Only log non-ENOTDIR errors (ENOTDIR is expected when checking if a file is a directory)
|
||||
if (error.code !== 'ENOTDIR') {
|
||||
console.error(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:mkdir', async (event, dirPath, recursive) => {
|
||||
try {
|
||||
const fullPath = expandTilde(dirPath);
|
||||
await fs.mkdir(fullPath, { recursive: !!recursive });
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to create directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:stat', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
const stats = await fs.stat(fullPath);
|
||||
const now = Date.now();
|
||||
return {
|
||||
isDirectory: stats.isDirectory(),
|
||||
isFile: stats.isFile(),
|
||||
isBlockDevice: stats.isBlockDevice(),
|
||||
isCharacterDevice: stats.isCharacterDevice(),
|
||||
isSymbolicLink: stats.isSymbolicLink(),
|
||||
isFIFO: stats.isFIFO(),
|
||||
isSocket: stats.isSocket(),
|
||||
size: stats.size,
|
||||
mtimeMs: stats.mtimeMs ?? now,
|
||||
ctimeMs: stats.ctimeMs ?? now,
|
||||
atimeMs: stats.atimeMs ?? now,
|
||||
// Date objects need to be serialized as timestamps for IPC
|
||||
// Use optional chaining and fallback to now to prevent valueOf errors
|
||||
mtime: stats.mtime?.getTime() ?? now,
|
||||
ctime: stats.ctime?.getTime() ?? now,
|
||||
atime: stats.atime?.getTime() ?? now,
|
||||
};
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:lstat', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
const stats = await fs.lstat(fullPath);
|
||||
const now = Date.now();
|
||||
return {
|
||||
isDirectory: stats.isDirectory(),
|
||||
isFile: stats.isFile(),
|
||||
isBlockDevice: stats.isBlockDevice(),
|
||||
isCharacterDevice: stats.isCharacterDevice(),
|
||||
isSymbolicLink: stats.isSymbolicLink(),
|
||||
isFIFO: stats.isFIFO(),
|
||||
isSocket: stats.isSocket(),
|
||||
size: stats.size,
|
||||
mtimeMs: stats.mtimeMs ?? now,
|
||||
ctimeMs: stats.ctimeMs ?? now,
|
||||
atimeMs: stats.atimeMs ?? now,
|
||||
// Date objects need to be serialized as timestamps for IPC
|
||||
// Use optional chaining and fallback to now to prevent valueOf errors
|
||||
mtime: stats.mtime?.getTime() ?? now,
|
||||
ctime: stats.ctime?.getTime() ?? now,
|
||||
atime: stats.atime?.getTime() ?? now,
|
||||
};
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to lstat ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:unlink', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
await fs.unlink(fullPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to unlink ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:rmdir', async (event, dirPath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(dirPath);
|
||||
await fs.rmdir(fullPath);
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to remove directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:rename', async (event, oldPath, newPath) => {
|
||||
try {
|
||||
const fullOldPath = expandTilde(oldPath);
|
||||
const fullNewPath = expandTilde(newPath);
|
||||
// Ensure parent directory of new path exists
|
||||
await fs.mkdir(path.dirname(fullNewPath), { recursive: true });
|
||||
await fs.rename(fullOldPath, fullNewPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to rename ${oldPath} to ${newPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:readlink', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
return await fs.readlink(fullPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to read link ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:symlink', async (event, target, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
// Ensure parent directory exists
|
||||
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
||||
await fs.symlink(target, fullPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to create symlink ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// Shell execution handler
|
||||
ipcMain.handle('shell:exec', async (event, command, cwd) => {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
// Determine the shell and command execution method based on platform
|
||||
const isWindows = process.platform === 'win32';
|
||||
const shellCmd = isWindows ? 'cmd.exe' : '/bin/sh';
|
||||
const shellArgs = isWindows ? ['/c', command] : ['-c', command];
|
||||
|
||||
// Expand tilde in working directory if provided, otherwise use home directory
|
||||
const workingDir = cwd ? expandTilde(cwd) : os.homedir();
|
||||
|
||||
// Ensure the working directory exists before spawning
|
||||
try {
|
||||
await fs.mkdir(workingDir, { recursive: true });
|
||||
console.log(`Shell exec in directory: ${workingDir}`);
|
||||
console.log(`Command: ${command}`);
|
||||
} catch (mkdirError) {
|
||||
console.warn(`Failed to create directory ${workingDir}:`, mkdirError.message);
|
||||
// Continue anyway - directory might already exist
|
||||
}
|
||||
|
||||
const child = spawn(shellCmd, shellArgs, {
|
||||
cwd: workingDir,
|
||||
env: { ...process.env },
|
||||
shell: false, // We're already using the shell
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
child.stdout?.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
child.stderr?.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
child.on('error', (error) => {
|
||||
console.error('Shell execution error:', error);
|
||||
console.error('Working directory:', workingDir);
|
||||
console.error('Shell command:', shellCmd);
|
||||
console.error('Shell args:', shellArgs);
|
||||
reject(new Error(`Failed to execute command: ${error.message} (cwd: ${workingDir})`));
|
||||
});
|
||||
|
||||
child.on('close', (code) => {
|
||||
resolve({
|
||||
stdout,
|
||||
stderr,
|
||||
exitCode: code ?? 0,
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Shell setup error:', error);
|
||||
reject(new Error(`Failed to setup shell execution: ${error.message}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron';
|
||||
import os from 'node:os';
|
||||
|
||||
// Expose protected methods that allow the renderer process to use
|
||||
// ipcRenderer without exposing the entire object
|
||||
contextBridge.exposeInMainWorld('electron', {
|
||||
// Get the home directory
|
||||
homedir: os.homedir(),
|
||||
|
||||
// Platform information
|
||||
platform: () => ipcRenderer.invoke('get-platform'),
|
||||
|
||||
// App version
|
||||
version: () => ipcRenderer.invoke('get-app-version'),
|
||||
|
||||
// Filesystem API - paths support tilde (~) expansion for home directory
|
||||
fs: {
|
||||
readFile: (path, encoding) => ipcRenderer.invoke('fs:readFile', path, encoding),
|
||||
writeFile: (path, data, encoding) => ipcRenderer.invoke('fs:writeFile', path, data, encoding),
|
||||
readdir: (path, withFileTypes) => ipcRenderer.invoke('fs:readdir', path, withFileTypes),
|
||||
mkdir: (path, recursive) => ipcRenderer.invoke('fs:mkdir', path, recursive),
|
||||
stat: (path) => ipcRenderer.invoke('fs:stat', path),
|
||||
lstat: (path) => ipcRenderer.invoke('fs:lstat', path),
|
||||
unlink: (path) => ipcRenderer.invoke('fs:unlink', path),
|
||||
rmdir: (path) => ipcRenderer.invoke('fs:rmdir', path),
|
||||
rename: (oldPath, newPath) => ipcRenderer.invoke('fs:rename', oldPath, newPath),
|
||||
readlink: (path) => ipcRenderer.invoke('fs:readlink', path),
|
||||
symlink: (target, path) => ipcRenderer.invoke('fs:symlink', target, path),
|
||||
},
|
||||
|
||||
// Shell API - execute real shell commands
|
||||
shell: {
|
||||
exec: (command, cwd) => ipcRenderer.invoke('shell:exec', command, cwd),
|
||||
},
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
@@ -19,7 +19,7 @@ export default {
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
|
||||
|
||||
// Only run this rule on HTML files
|
||||
if (!filename.endsWith('.html')) {
|
||||
return {};
|
||||
@@ -29,11 +29,11 @@ export default {
|
||||
Program(node) {
|
||||
const sourceCode = context.getSourceCode();
|
||||
const htmlContent = sourceCode.getText();
|
||||
|
||||
|
||||
// Check for manifest link tag in HTML
|
||||
const manifestLinkRegex = /<link[^>]*rel=["']manifest["'][^>]*>/i;
|
||||
const manifestMatch = htmlContent.match(manifestLinkRegex);
|
||||
|
||||
|
||||
if (!manifestMatch) {
|
||||
context.report({
|
||||
node,
|
||||
@@ -53,11 +53,11 @@ export default {
|
||||
}
|
||||
|
||||
const manifestPath = hrefMatch[1];
|
||||
|
||||
|
||||
// Resolve the manifest file path relative to the project root
|
||||
const htmlDir = path.dirname(filename);
|
||||
let resolvedManifestPath;
|
||||
|
||||
|
||||
if (manifestPath.startsWith('/')) {
|
||||
// Absolute path - check in public directory first, then project root
|
||||
const publicPath = path.resolve(htmlDir, 'public' + manifestPath);
|
||||
@@ -67,7 +67,7 @@ export default {
|
||||
// Relative path
|
||||
resolvedManifestPath = path.resolve(htmlDir, manifestPath);
|
||||
}
|
||||
|
||||
|
||||
// Check if the manifest file exists
|
||||
if (!fs.existsSync(resolvedManifestPath)) {
|
||||
context.report({
|
||||
|
||||
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
|
||||
import customRules from "./eslint-rules/index.js";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist"] },
|
||||
{ ignores: ["dist", "electron/dist"] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
@@ -27,6 +27,7 @@ export default tseslint.config(
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
"react-hooks/exhaustive-deps": "error",
|
||||
"react-refresh/only-export-components": [
|
||||
"warn",
|
||||
{ allowConstantExport: true },
|
||||
@@ -39,11 +40,18 @@ export default tseslint.config(
|
||||
"ignoreRestSiblings": true,
|
||||
},
|
||||
],
|
||||
"indent": [
|
||||
"warn",
|
||||
2,
|
||||
{ SwitchCase: 1 },
|
||||
],
|
||||
"no-tabs": "warn",
|
||||
"custom/no-placeholder-comments": "error",
|
||||
"no-warning-comments": [
|
||||
"error",
|
||||
{ terms: ["fixme"] },
|
||||
],
|
||||
"no-control-regex": "off", // Allow ANSI escape sequences in regex
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,260 +0,0 @@
|
||||
/**
|
||||
* iframe Fetch Client Main Script
|
||||
* JSON-RPC based communication with parent page
|
||||
*/
|
||||
|
||||
class JSONRPCClient {
|
||||
constructor() {
|
||||
this.requestId = 0;
|
||||
this.pendingRequests = new Map();
|
||||
this.setupMessageListener();
|
||||
}
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
const message = event.data;
|
||||
if (message.jsonrpc === "2.0" && message.id !== undefined) {
|
||||
// Check if this is a response to our own request or a ServiceWorker request
|
||||
if (this.pendingRequests.has(message.id)) {
|
||||
this.handleResponse(message);
|
||||
} else {
|
||||
// This is a response to a ServiceWorker request, relay it back
|
||||
this.relayJSONRPCToServiceWorker(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
relayJSONRPCToServiceWorker(response) {
|
||||
// Forward the JSON-RPC response to ServiceWorker
|
||||
if (navigator.serviceWorker.controller) {
|
||||
navigator.serviceWorker.controller.postMessage(response);
|
||||
}
|
||||
}
|
||||
|
||||
async fetch(request) {
|
||||
const id = ++this.requestId;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.pendingRequests.set(id, { resolve, reject });
|
||||
|
||||
// Send JSON-RPC request to parent
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "fetch",
|
||||
params: { request },
|
||||
id,
|
||||
}, "*");
|
||||
|
||||
// Timeout after 10 seconds
|
||||
setTimeout(() => {
|
||||
if (this.pendingRequests.has(id)) {
|
||||
this.pendingRequests.delete(id);
|
||||
reject(new Error(`Timeout fetching: ${request.url}`));
|
||||
}
|
||||
}, 10000);
|
||||
});
|
||||
}
|
||||
|
||||
handleResponse(message) {
|
||||
const { id, result, error } = message;
|
||||
const pending = this.pendingRequests.get(id);
|
||||
|
||||
if (!pending) return;
|
||||
|
||||
this.pendingRequests.delete(id);
|
||||
|
||||
if (error) {
|
||||
pending.reject(new Error(`${error.message} (code: ${error.code})`));
|
||||
} else {
|
||||
pending.resolve(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class FetchClient {
|
||||
constructor() {
|
||||
this.rpcClient = new JSONRPCClient();
|
||||
this.swReady = false;
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
async init() {
|
||||
try {
|
||||
await this.registerServiceWorker();
|
||||
this.setupServiceWorkerCommunication();
|
||||
await this.waitForServiceWorker();
|
||||
await this.fetchSiteIndex();
|
||||
} catch (error) {
|
||||
this.showError("Failed to initialize fetch client", error);
|
||||
}
|
||||
}
|
||||
|
||||
async registerServiceWorker() {
|
||||
if (!("serviceWorker" in navigator)) {
|
||||
throw new Error("ServiceWorker not supported");
|
||||
}
|
||||
|
||||
// Check if SW is already registered
|
||||
const existingRegistration = await navigator.serviceWorker
|
||||
.getRegistration();
|
||||
if (existingRegistration) {
|
||||
console.log("ServiceWorker already registered");
|
||||
this.swReady = true;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.register("/sw.js", {
|
||||
scope: "/",
|
||||
});
|
||||
|
||||
console.log("ServiceWorker registered:", registration);
|
||||
|
||||
// Wait for SW to be ready
|
||||
await navigator.serviceWorker.ready;
|
||||
this.swReady = true;
|
||||
|
||||
// Block future registrations to prevent site from registering its own SW
|
||||
this.blockFutureRegistrations();
|
||||
} catch (error) {
|
||||
throw new Error(`ServiceWorker registration failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
blockFutureRegistrations() {
|
||||
navigator.serviceWorker.register = function () {
|
||||
console.log("Blocked ServiceWorker registration attempt");
|
||||
return Promise.resolve({
|
||||
scope: "/",
|
||||
active: navigator.serviceWorker.controller,
|
||||
installing: null,
|
||||
waiting: null,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
setupServiceWorkerCommunication() {
|
||||
// Listen for JSON-RPC requests from ServiceWorker and relay them to parent
|
||||
navigator.serviceWorker.addEventListener("message", async (event) => {
|
||||
const { data } = event;
|
||||
|
||||
// Check if this is a JSON-RPC request from ServiceWorker
|
||||
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
|
||||
this.relayJSONRPCToParent(data);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
relayJSONRPCToParent(request) {
|
||||
// Forward the JSON-RPC request directly to parent
|
||||
window.parent.postMessage(request, "*");
|
||||
}
|
||||
|
||||
async waitForServiceWorker() {
|
||||
const timeout = 10000; // 10 seconds
|
||||
const start = Date.now();
|
||||
|
||||
while (!this.swReady) {
|
||||
if (Date.now() - start > timeout) {
|
||||
throw new Error("Timeout waiting for ServiceWorker readiness");
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
console.log("ServiceWorker is ready");
|
||||
}
|
||||
|
||||
async fetchSiteIndex() {
|
||||
try {
|
||||
// Request site index from parent via JSON-RPC fetch
|
||||
const serializedRequest = {
|
||||
url: `${location.origin}/`,
|
||||
method: "GET",
|
||||
body: null,
|
||||
headers: {},
|
||||
};
|
||||
|
||||
const response = await this.rpcClient.fetch(serializedRequest);
|
||||
|
||||
// Replace current document with the site index content
|
||||
this.replaceDocument(response.body);
|
||||
} catch (error) {
|
||||
this.showError("Failed to load site index", error);
|
||||
}
|
||||
}
|
||||
|
||||
replaceDocument(htmlContent) {
|
||||
// Create a new document from the HTML content
|
||||
const parser = new DOMParser();
|
||||
const newDoc = parser.parseFromString(htmlContent, "text/html");
|
||||
|
||||
const scripts = [];
|
||||
newDoc.querySelectorAll("script").forEach((script) => {
|
||||
scripts.push({
|
||||
src: script.src,
|
||||
type: script.type,
|
||||
async: script.hasAttribute("async"),
|
||||
defer: script.hasAttribute("defer"),
|
||||
});
|
||||
script.parentNode.removeChild(script);
|
||||
});
|
||||
|
||||
// Replace the entire document
|
||||
document.head.innerHTML = newDoc.head.innerHTML;
|
||||
document.body.innerHTML = newDoc.body.innerHTML;
|
||||
|
||||
// Re-add scripts (this is necessary to execute them)
|
||||
scripts.forEach((script) => {
|
||||
const newScript = document.createElement("script");
|
||||
newScript.src = script.src;
|
||||
newScript.type = script.type;
|
||||
if (script.async) newScript.async = true;
|
||||
if (script.defer) newScript.defer = true;
|
||||
document.body.appendChild(newScript);
|
||||
});
|
||||
|
||||
console.log("Document replaced with site content");
|
||||
}
|
||||
|
||||
showError(message, error) {
|
||||
console.error(message, error);
|
||||
|
||||
document.body.innerHTML = `
|
||||
<div style="
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
max-width: 600px;
|
||||
margin: 50px auto;
|
||||
padding: 20px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
border-left: 4px solid #dc3545;
|
||||
">
|
||||
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
|
||||
<p><strong>${message}</strong></p>
|
||||
<p style="color: #6c757d;">${error.message || error}</p>
|
||||
<details style="margin-top: 20px;">
|
||||
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
|
||||
<pre style="
|
||||
background: #f1f3f4;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
overflow-x: auto;
|
||||
font-size: 12px;
|
||||
margin-top: 10px;
|
||||
">${error.stack || JSON.stringify(error, null, 2)}</pre>
|
||||
</details>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize when DOM is ready
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () => new FetchClient());
|
||||
} else {
|
||||
new FetchClient();
|
||||
}
|
||||
@@ -2,14 +2,19 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Shakespeare - AI-Powered Nostr Development</title>
|
||||
<meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<title>Shakespeare - Open Source AI Builder</title>
|
||||
<meta name="description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:title" content="Shakespeare - AI-Powered Nostr Development">
|
||||
<meta property="og:description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
||||
<!-- <meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:"> -->
|
||||
<link rel="icon" type="image/png" href="/favicon.png">
|
||||
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
|
||||
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
|
||||
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
|
||||
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
|
||||
<meta name="theme-color" content="#2b0037">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -1,21 +1,38 @@
|
||||
{
|
||||
"name": "mkstack",
|
||||
"private": true,
|
||||
"name": "shakespeare.diy",
|
||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
||||
"homepage": "https://shakespeare.diy",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"author": {
|
||||
"name": "shakespeare.diy",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://gitlab.com/soapbox-pub/shakespeare.git"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "npm i && vite",
|
||||
"build": "npm i && vite build && cp dist/index.html dist/404.html",
|
||||
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
|
||||
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||
"dev": "npm i --silent && vite",
|
||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||
"typecheck": "npm i --silent && tsc --noEmit",
|
||||
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
|
||||
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && node scripts/prepare-electron-publish.js && electron electron",
|
||||
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/openai": "^1.3.23",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^6.0.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "^0.47.1",
|
||||
"@nostrify/react": "^0.2.17",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||
@@ -43,40 +60,54 @@
|
||||
"@radix-ui/react-toggle": "^1.1.0",
|
||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@std/path": "npm:@jsr/std__path@^1.1.1",
|
||||
"@sentry/react": "^10.22.0",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"@webcontainer/api": "^1.6.1",
|
||||
"ai": "^4.3.19",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"decimal.js": "^10.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"esbuild-wasm": "^0.25.8",
|
||||
"gray-matter": "^4.0.3",
|
||||
"i18next": "^25.5.2",
|
||||
"ignore": "^7.0.5",
|
||||
"input-otp": "^1.2.4",
|
||||
"isomorphic-git": "^1.32.1",
|
||||
"jsonc-parser": "^3.3.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"next-themes": "^0.3.0",
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"prismjs": "^1.30.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-error-boundary": "^6.0.0",
|
||||
"react-hook-form": "^7.53.0",
|
||||
"react-i18next": "^15.7.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-resizable-panels": "^3.0.3",
|
||||
"react-router-dom": "^6.26.2",
|
||||
"react-syntax-highlighter": "^15.6.1",
|
||||
"recharts": "^2.12.7",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"sonner": "^1.5.0",
|
||||
"streamdown": "~1.0.0",
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"tailwindcss-safe-area": "^0.8.0",
|
||||
"turndown": "^7.2.1",
|
||||
"uri-templates": "^0.2.0",
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"workbox-window": "^7.3.0",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -86,14 +117,20 @@
|
||||
"@tailwindcss/typography": "^0.5.15",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/nunjucks": "^3.2.6",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@types/react-syntax-highlighter": "^15.5.13",
|
||||
"@types/turndown": "^5.0.5",
|
||||
"@types/uri-templates": "^0.1.34",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"electron": "^39.0.0",
|
||||
"eslint": "^9.9.0",
|
||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.9",
|
||||
@@ -104,6 +141,7 @@
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"vite": "^6.3.5",
|
||||
"vite-plugin-pwa": "^1.1.0",
|
||||
"vitest": "^3.1.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,688 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
||||
<!-- saved from url=(0053)https://www.gnu.org/licenses/agpl-3.0-standalone.html -->
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
|
||||
<title>GNU Affero General Public License - GNU Project - Free Software Foundation (FSF)</title>
|
||||
<link rel="alternate" type="application/rdf+xml" href="http://www.gnu.org/licenses/agpl-3.0.rdf">
|
||||
</head>
|
||||
<body>
|
||||
<h3 style="text-align: center;">GNU AFFERO GENERAL PUBLIC LICENSE</h3>
|
||||
<p style="text-align: center;">Version 3, 19 November 2007</p>
|
||||
|
||||
<p>Copyright © 2007 Free Software Foundation,
|
||||
Inc. <<a href="https://fsf.org/">https://fsf.org/</a>>
|
||||
<br>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.</p>
|
||||
|
||||
<h4 id="preamble">Preamble</h4>
|
||||
|
||||
<p>The GNU Affero General Public License is a free, copyleft license
|
||||
for software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.</p>
|
||||
|
||||
<p>The licenses for most software and other practical works are
|
||||
designed to take away your freedom to share and change the works. By
|
||||
contrast, our General Public Licenses are intended to guarantee your
|
||||
freedom to share and change all versions of a program--to make sure it
|
||||
remains free software for all its users.</p>
|
||||
|
||||
<p>When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.</p>
|
||||
|
||||
<p>Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.</p>
|
||||
|
||||
<p>A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.</p>
|
||||
|
||||
<p>The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.</p>
|
||||
|
||||
<p>An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.</p>
|
||||
|
||||
<p>The precise terms and conditions for copying, distribution and
|
||||
modification follow.</p>
|
||||
|
||||
<h4 id="terms">TERMS AND CONDITIONS</h4>
|
||||
|
||||
<h4 id="section0">0. Definitions.</h4>
|
||||
|
||||
<p>"This License" refers to version 3 of the GNU Affero General Public
|
||||
License.</p>
|
||||
|
||||
<p>"Copyright" also means copyright-like laws that apply to other kinds
|
||||
of works, such as semiconductor masks.</p>
|
||||
|
||||
<p>"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.</p>
|
||||
|
||||
<p>To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.</p>
|
||||
|
||||
<p>A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.</p>
|
||||
|
||||
<p>To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.</p>
|
||||
|
||||
<p>To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.</p>
|
||||
|
||||
<p>An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.</p>
|
||||
|
||||
<h4 id="section1">1. Source Code.</h4>
|
||||
|
||||
<p>The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.</p>
|
||||
|
||||
<p>A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.</p>
|
||||
|
||||
<p>The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.</p>
|
||||
|
||||
<p>The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.</p>
|
||||
|
||||
<p>The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.</p>
|
||||
|
||||
<p>The Corresponding Source for a work in source code form is that
|
||||
same work.</p>
|
||||
|
||||
<h4 id="section2">2. Basic Permissions.</h4>
|
||||
|
||||
<p>All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.</p>
|
||||
|
||||
<p>You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.</p>
|
||||
|
||||
<p>Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.</p>
|
||||
|
||||
<h4 id="section3">3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
|
||||
|
||||
<p>No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.</p>
|
||||
|
||||
<p>When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.</p>
|
||||
|
||||
<h4 id="section4">4. Conveying Verbatim Copies.</h4>
|
||||
|
||||
<p>You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.</p>
|
||||
|
||||
<p>You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.</p>
|
||||
|
||||
<h4 id="section5">5. Conveying Modified Source Versions.</h4>
|
||||
|
||||
<p>You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:</p>
|
||||
|
||||
<ul>
|
||||
|
||||
<li>a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.</li>
|
||||
|
||||
<li>b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".</li>
|
||||
|
||||
<li>c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.</li>
|
||||
|
||||
<li>d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.</li>
|
||||
|
||||
</ul>
|
||||
|
||||
<p>A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.</p>
|
||||
|
||||
<h4 id="section6">6. Conveying Non-Source Forms.</h4>
|
||||
|
||||
<p>You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:</p>
|
||||
|
||||
<ul>
|
||||
|
||||
<li>a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.</li>
|
||||
|
||||
<li>b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.</li>
|
||||
|
||||
<li>c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.</li>
|
||||
|
||||
<li>d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.</li>
|
||||
|
||||
<li>e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.</li>
|
||||
|
||||
</ul>
|
||||
|
||||
<p>A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.</p>
|
||||
|
||||
<p>A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.</p>
|
||||
|
||||
<p>"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.</p>
|
||||
|
||||
<p>If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).</p>
|
||||
|
||||
<p>The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.</p>
|
||||
|
||||
<p>Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.</p>
|
||||
|
||||
<h4 id="section7">7. Additional Terms.</h4>
|
||||
|
||||
<p>"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.</p>
|
||||
|
||||
<p>When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.</p>
|
||||
|
||||
<p>Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:</p>
|
||||
|
||||
<ul>
|
||||
|
||||
<li>a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or</li>
|
||||
|
||||
<li>b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or</li>
|
||||
|
||||
<li>c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or</li>
|
||||
|
||||
<li>d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or</li>
|
||||
|
||||
<li>e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or</li>
|
||||
|
||||
<li>f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.</li>
|
||||
|
||||
</ul>
|
||||
|
||||
<p>All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further restriction,
|
||||
you may remove that term. If a license document contains a further
|
||||
restriction but permits relicensing or conveying under this License, you
|
||||
may add to a covered work material governed by the terms of that license
|
||||
document, provided that the further restriction does not survive such
|
||||
relicensing or conveying.</p>
|
||||
|
||||
<p>If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.</p>
|
||||
|
||||
<p>Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.</p>
|
||||
|
||||
<h4 id="section8">8. Termination.</h4>
|
||||
|
||||
<p>You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).</p>
|
||||
|
||||
<p>However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.</p>
|
||||
|
||||
<p>Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.</p>
|
||||
|
||||
<p>Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.</p>
|
||||
|
||||
<h4 id="section9">9. Acceptance Not Required for Having Copies.</h4>
|
||||
|
||||
<p>You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.</p>
|
||||
|
||||
<h4 id="section10">10. Automatic Licensing of Downstream Recipients.</h4>
|
||||
|
||||
<p>Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.</p>
|
||||
|
||||
<p>An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.</p>
|
||||
|
||||
<p>You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.</p>
|
||||
|
||||
<h4 id="section11">11. Patents.</h4>
|
||||
|
||||
<p>A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".</p>
|
||||
|
||||
<p>A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.</p>
|
||||
|
||||
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.</p>
|
||||
|
||||
<p>In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.</p>
|
||||
|
||||
<p>If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.</p>
|
||||
|
||||
<p>If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.</p>
|
||||
|
||||
<p>A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.</p>
|
||||
|
||||
<p>Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.</p>
|
||||
|
||||
<h4 id="section12">12. No Surrender of Others' Freedom.</h4>
|
||||
|
||||
<p>If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.</p>
|
||||
|
||||
<h4 id="section13">13. Remote Network Interaction; Use with the GNU General Public License.</h4>
|
||||
|
||||
<p>Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.</p>
|
||||
|
||||
<p>Notwithstanding any other provision of this License, you have permission
|
||||
to link or combine any covered work with a work licensed under version 3
|
||||
of the GNU General Public License into a single combined work, and to
|
||||
convey the resulting work. The terms of this License will continue to
|
||||
apply to the part which is the covered work, but the work with which it is
|
||||
combined will remain governed by version 3 of the GNU General Public
|
||||
License.</p>
|
||||
|
||||
<h4 id="section14">14. Revised Versions of this License.</h4>
|
||||
|
||||
<p>The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may differ
|
||||
in detail to address new problems or concerns.</p>
|
||||
|
||||
<p>Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero
|
||||
General Public License "or any later version" applies to it, you have
|
||||
the option of following the terms and conditions either of that
|
||||
numbered version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number
|
||||
of the GNU Affero General Public License, you may choose any version
|
||||
ever published by the Free Software Foundation.</p>
|
||||
|
||||
<p>If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that
|
||||
proxy's public statement of acceptance of a version permanently
|
||||
authorizes you to choose that version for the Program.</p>
|
||||
|
||||
<p>Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.</p>
|
||||
|
||||
<h4 id="section15">15. Disclaimer of Warranty.</h4>
|
||||
|
||||
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p>
|
||||
|
||||
<h4 id="section16">16. Limitation of Liability.</h4>
|
||||
|
||||
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.</p>
|
||||
|
||||
<h4 id="section17">17. Interpretation of Sections 15 and 16.</h4>
|
||||
|
||||
<p>If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.</p>
|
||||
|
||||
<p>END OF TERMS AND CONDITIONS</p>
|
||||
|
||||
<h4 id="howto">How to Apply These Terms to Your New Programs</h4>
|
||||
|
||||
<p>If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.</p>
|
||||
|
||||
<p>To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.</p>
|
||||
|
||||
<pre> <one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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/>.
|
||||
</pre>
|
||||
|
||||
<p>Also add information on how to contact you by electronic and paper mail.</p>
|
||||
|
||||
<p>If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.</p>
|
||||
|
||||
<p>You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<<a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>>.</p>
|
||||
|
||||
|
||||
</body></html>
|
||||
@@ -1 +1,2 @@
|
||||
/* /index.html 200
|
||||
/assets/* /assets/:splat 200
|
||||
/* /index.html 200
|
||||
@@ -0,0 +1,27 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="166" height="20" role="img" aria-label="🎭 Edit with: Shakespeare">
|
||||
<title>🎭 Edit with: Shakespeare</title>
|
||||
<defs>
|
||||
<mask id="round">
|
||||
<rect width="166" height="20" rx="3" fill="#fff"/>
|
||||
</mask>
|
||||
<linearGradient id="shine" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#fff" stop-opacity=".2"/>
|
||||
<stop offset="0.1" stop-color="#fff" stop-opacity=".05"/>
|
||||
<stop offset="1" stop-color="#fff" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<g mask="url(#round)">
|
||||
<!-- Left label background -->
|
||||
<rect width="78" height="20" fill="#555"/>
|
||||
<!-- Right label background -->
|
||||
<rect x="78" width="88" height="20" fill="#6f42c1"/>
|
||||
<rect width="166" height="20" fill="url(#shine)"/>
|
||||
</g>
|
||||
|
||||
<!-- Text -->
|
||||
<g fill="#fff" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,Ubuntu,Cantarell,Noto Sans,sans-serif" font-size="11">
|
||||
<text x="39" y="14">🎭 Edit with</text>
|
||||
<text x="122" y="14" font-weight="600">Shakespeare</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 18 KiB |
@@ -1,21 +1,70 @@
|
||||
{
|
||||
"name": "Shakespeare - AI-Powered Nostr Development",
|
||||
"$schema": "https://json.schemastore.org/web-manifest-combined.json",
|
||||
"name": "Shakespeare - Open Source AI Builder",
|
||||
"short_name": "Shakespeare",
|
||||
"description": "Build custom Nostr websites with AI assistance",
|
||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
||||
"categories": ["productivity", "devtools"],
|
||||
"id": "/",
|
||||
"scope": "/",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#ffffff",
|
||||
"theme_color": "#000000",
|
||||
"orientation": "any",
|
||||
"background_color": "#2b0037",
|
||||
"theme_color": "#2b0037",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon-192.png",
|
||||
"src": "/shakespeare-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/icon-512.png",
|
||||
"src": "/shakespeare-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/shakespeare-maskable-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
},
|
||||
{
|
||||
"src": "/shakespeare-maskable-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
],
|
||||
"screenshots": [
|
||||
{
|
||||
"label": "Home",
|
||||
"src": "/screenshot-mobile-home.png",
|
||||
"sizes": "1179x2556",
|
||||
"type": "image/png",
|
||||
"form_factor": "narrow"
|
||||
},
|
||||
{
|
||||
"label": "Project",
|
||||
"src": "/screenshot-mobile-project.png",
|
||||
"sizes": "1179x2556",
|
||||
"type": "image/png",
|
||||
"form_factor": "narrow"
|
||||
},
|
||||
{
|
||||
"label": "Preview",
|
||||
"src": "/screenshot-mobile-preview.png",
|
||||
"sizes": "1179x2556",
|
||||
"type": "image/png",
|
||||
"form_factor": "narrow"
|
||||
},
|
||||
{
|
||||
"label": "Desktop",
|
||||
"src": "/screenshot-desktop.png",
|
||||
"sizes": "1920x1080",
|
||||
"type": "image/png",
|
||||
"form_factor": "wide"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 70 KiB |
@@ -0,0 +1,2 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
|
After Width: | Height: | Size: 219 KiB |
|
After Width: | Height: | Size: 266 KiB |
|
After Width: | Height: | Size: 321 KiB |
|
After Width: | Height: | Size: 167 KiB |
|
After Width: | Height: | Size: 7.9 KiB |
|
After Width: | Height: | Size: 8.6 KiB |
|
After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,63 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="レイヤー_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
|
||||
y="0px" viewBox="0 0 128 128" style="enable-background:new 0 0 128 128;" xml:space="preserve">
|
||||
<g>
|
||||
<g>
|
||||
<path style="fill:#F45125;" d="M110.28,61.32l2.63,8.84c0,0,7.24-1.6,7.62,3.2c0.38,4.8-6.77,8-6.77,8l2.26,10.63
|
||||
c0,0,7.9-6.4,8-15.61c0,0,0.66-11.29-6.11-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
|
||||
<path style="fill:#F45125;" d="M68.71,94.99c0,0-11.1-4.7-16.46,1.98c-0.75,0.94-1.41,1.88-2.16,2.82
|
||||
c-0.56,0.75-1.13,1.5-1.69,2.16c-0.47,0.56-1.03,1.13-1.69,1.5c-0.66,0.38-1.32,0.66-2.07,0.85c-0.94,0.19-1.88,0.19-2.82,0.09
|
||||
c-1.32-0.09-2.63-0.38-3.95-0.66c-0.47-0.09-0.85-0.19-1.22-0.28c-0.09,0-0.19-0.09-0.28-0.09s-0.19-0.09-0.28-0.09
|
||||
c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98c1.32,0.66,2.73,1.03,4.14,1.13
|
||||
c0.09,0,0.38,0,0.47,0.09c0.19,0.19-0.28,0.47-0.47,0.56c-0.28,0.19-0.47,0.28-0.75,0.38c-0.85,0.38-1.79,0.56-2.63,0.75
|
||||
c-0.85,0.19-1.69,0.28-2.45,0.28c-0.47,0-0.85,0.09-1.22,0.09c-0.28,0-0.56-0.09-0.85,0s0.09,0.47,0.28,0.56
|
||||
c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38c1.32-0.19,2.63-0.56,3.86-1.03
|
||||
c6.77-3.1,6.21-9.59,12.42-10.16c4.61-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
|
||||
<path style="fill:#F45125;" d="M19.79,38.28c0,0-12.13,1.98-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22-9.41
|
||||
c0,0-13.07-1.32-12.32-6.3c0.94-6.21,11.85-5.64,11.85-5.64L19.79,38.28z"/>
|
||||
<path style="fill:#F45125;" d="M20.73,70.92c0,0-1.88,0.56-4.61,2.54c-1.88,1.32-4.42,3.01-6.87,5.93
|
||||
c-1.22,1.41-2.16,3.1-2.82,4.89c-0.47,1.22-0.66,2.45-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66
|
||||
c0.09-0.09,0.19-0.38,0.28-0.47c0.19-0.47,0.47-0.85,0.75-1.22c0.85-1.13,1.88-2.16,3.01-3.01c0.38-0.28,0.75-0.47,1.13-0.66
|
||||
c0.28-0.28,0.75-0.66,0.94-0.28c0.09,0.19-0.09,0.47-0.19,0.66c-0.09,0.28-0.19,0.66-0.19,0.94c-0.38,1.5-0.56,3.01-0.75,4.51
|
||||
c-0.09,0.85-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19
|
||||
c0.09-0.09,0.09-0.19,0.19-0.38c0.19-0.28,0.28-0.66,0.47-0.94c0.47-0.85,0.94-1.69,1.5-2.63c0.66-1.13,1.41-2.16,2.16-3.1
|
||||
c0.85-1.13,1.88-2.26,2.92-3.2c1.13-1.03,2.35-2.07,3.67-2.92c0.75-0.47,1.6-0.94,2.45-1.32L20.73,70.92z"/>
|
||||
<g>
|
||||
<path style="fill:#FCC21B;" d="M116.4,79.29c-1.13-5.55-2.73-11.01-4.51-16.46c-1.5-4.61-3.1-9.31-5.83-13.36
|
||||
c-1.22-1.79-3.01-3.01-5.27-3.86c-4.33-1.69-9.97-1.98-13.73-1.98c-5.64,0-11.48,1.22-16.74,3.67
|
||||
c-1.88,5.64-7.05,19.94-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23
|
||||
c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66
|
||||
c2.54-1.13,4.61-2.92,6.3-5.08c1.79-2.26,3.2-4.8,4.42-7.43c1.88-3.95,3.86-8.37,4.14-12.89
|
||||
C117.99,87.38,117.24,83.24,116.4,79.29z"/>
|
||||
<path style="fill:#429ADF;" d="M77.64,33.57c-0.28-1.03-1.03-2.07-1.6-3.01c-6.3-11.01-20.04-16.27-32.26-15.52
|
||||
c-3.76,0.28-9.31,0.85-13.54,2.73c-2.07,0.94-3.86,2.35-4.99,4.14c-2.54,4.23-3.76,8.94-5.08,13.64
|
||||
C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89-1.41,10.25-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32
|
||||
c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94-0.19,1.98-0.28,2.92-0.56
|
||||
c1.88-0.47,3.67-1.13,5.46-1.79c7.52-3.01,13.64-7.43,17.68-14.58c1.69-3.1,3.1-6.4,4.42-9.69c0.09-0.19,0.19-0.38,0.19-0.56
|
||||
c1.98-5.46,3.29-11.19,4.61-16.84c0.66-2.73,1.41-5.55,1.79-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
|
||||
</g>
|
||||
</g>
|
||||
<path style="fill:#193D51;" d="M23.09,40.53c1.69-3.1,5.74-5.55,9.31-5.08c0.56,0.09,1.22,0.19,1.79,0.47
|
||||
c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75-0.66,0.85-1.22,0.38c-1.98-1.69-3.57-3.01-6.21-3.67c-2.16-0.56-4.61-0.28-6.68,0.28
|
||||
c-0.47,0.09-1.22,0.56-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
|
||||
<path style="fill:#193D51;" d="M62.21,64.9c-1.03,1.6-2.45,3.01-3.86,4.33c-0.38,0.28-0.66,0.66-1.03,0.94
|
||||
c-5.64,4.7-13.26,7.05-20.51,5.27c-1.98-0.47-4.14-1.5-5.74-2.73c-1.22-0.94-2.45-2.16-3.48-3.39c-1.88-2.26-3.29-4.89-4.23-7.62
|
||||
c-0.47-1.41-0.75-2.73-0.94-4.23c0-0.47-0.66-5.46,0.85-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03
|
||||
c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09
|
||||
c5.08-0.28,10.25-1.79,14.86-3.76c0.38-0.19,0.85-0.47,1.32-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
|
||||
<path style="fill:#193D51;" d="M67.58,51.16c0,0.47-0.19,1.13-0.75,1.03c-0.47-0.09-0.85-0.94-1.13-1.22
|
||||
c-1.32-1.69-3.86-3.57-6.4-4.14c-3.01-0.75-5.27,0.56-8.28,0.85c-0.85,0.09-1.32-0.28-0.94-1.03c1.6-3.48,5.83-6.21,10.25-5.46
|
||||
c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
|
||||
<path style="fill:#9B7515;" d="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41-0.09,2.26,0.09,1.88,1.69
|
||||
c-0.75,3.29-3.86,5.17-6.87,5.83c-0.75,0.19-1.5,0.19-2.26,0.19c-1.41-0.09-2.82-0.66-4.04-1.5c-2.63-1.79-4.61-4.89-5.17-8
|
||||
C89.68,63.67,90.25,62.83,91.84,63.86z"/>
|
||||
<path style="fill:#9B7515;" d="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51-2.35,9.03-5.93,11.38-10.63
|
||||
c0.85-1.79,1.79-1.41,2.45,0.28c1.13,3.1,1.03,6.87-0.38,9.88c-0.66,1.41-1.6,2.63-2.82,3.57c-0.66,0.47-1.32,0.75-2.07,1.03
|
||||
C71.43,83.33,67.58,83.24,65.22,80.79z"/>
|
||||
<path style="fill:#9B7515;" d="M110,96.41c-0.38,0-0.94-0.38-1.41-0.66c-0.47-0.28-0.94-0.66-1.22-0.85
|
||||
c-1.13-0.56-2.45-1.13-3.67-1.5c-3.76-1.22-7.9-1.22-11.57,0c-2.63,0.85-5.17,2.45-7.24,4.33c-2.26,2.16-3.95,4.8-6.11,7.05
|
||||
c-0.28,0.28-0.56,0.56-0.85,0.75c-0.56,0.28-1.13-0.09-1.32-0.66c-0.94-3.95,1.69-9.5,3.67-12.89c2.26-3.76,5.55-6.77,9.78-8
|
||||
c2.07-0.66,4.33-0.66,6.49-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 5.8 KiB |
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { readFileSync, writeFileSync, copyFileSync, rmSync, cpSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const rootDir = join(__dirname, '..');
|
||||
const electronDir = join(rootDir, 'electron');
|
||||
const distDir = join(rootDir, 'dist');
|
||||
const electronDistDir = join(electronDir, 'dist');
|
||||
|
||||
// Read root package.json
|
||||
const rootPackage = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf-8'));
|
||||
|
||||
// Generate CalVer version (YYYY.MM.DDHHMM) in UTC
|
||||
const now = new Date();
|
||||
const year = now.getUTCFullYear();
|
||||
const month = String(now.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(now.getUTCDate()).padStart(2, '0');
|
||||
const hour = String(now.getUTCHours()).padStart(2, '0');
|
||||
const minute = String(now.getUTCMinutes()).padStart(2, '0');
|
||||
const version = `${year}.${month}.${day}${hour}${minute}`;
|
||||
|
||||
// Get electron version from root devDependencies
|
||||
const electronVersion = rootPackage.devDependencies.electron;
|
||||
|
||||
// Remove old electron/dist and copy new one
|
||||
console.log('Removing old electron/dist...');
|
||||
rmSync(electronDistDir, { recursive: true, force: true });
|
||||
|
||||
console.log('Copying dist to electron/dist...');
|
||||
cpSync(distDir, electronDistDir, { recursive: true });
|
||||
|
||||
// Create electron package.json
|
||||
const electronPackage = {
|
||||
name: rootPackage.name,
|
||||
description: rootPackage.description,
|
||||
homepage: rootPackage.homepage,
|
||||
license: rootPackage.license,
|
||||
version: version,
|
||||
type: "module",
|
||||
main: "main.js",
|
||||
bin: {
|
||||
shakespeare: "./bin/shakespeare.js"
|
||||
},
|
||||
files: [
|
||||
"bin/",
|
||||
"dist/",
|
||||
"main.js",
|
||||
"package.json",
|
||||
"preload.js",
|
||||
"LICENSE",
|
||||
"README.md"
|
||||
],
|
||||
author: rootPackage.author,
|
||||
repository: rootPackage.repository,
|
||||
dependencies: {
|
||||
electron: electronVersion
|
||||
}
|
||||
};
|
||||
|
||||
// Write electron package.json
|
||||
writeFileSync(
|
||||
join(electronDir, 'package.json'),
|
||||
JSON.stringify(electronPackage, null, 2) + '\n',
|
||||
'utf-8'
|
||||
);
|
||||
|
||||
// Copy README.md to electron directory
|
||||
copyFileSync(
|
||||
join(rootDir, 'README.md'),
|
||||
join(electronDir, 'README.md')
|
||||
);
|
||||
|
||||
console.log(`✓ Generated electron/package.json with version ${version}`);
|
||||
console.log('✓ Copied README.md to electron/');
|
||||
@@ -0,0 +1,3 @@
|
||||
# Shakespeare Services
|
||||
|
||||
This directory contains additional microservices that can be optionally deployed alongside Shakespeare to host a complete Shakespeare instance.
|
||||
@@ -0,0 +1,26 @@
|
||||
export default {
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (url.pathname === "/") {
|
||||
return Response.redirect("https://shakespeare.diy", 302);
|
||||
}
|
||||
|
||||
url.hostname = "esm.sh";
|
||||
|
||||
// Cache response via Cloudflare
|
||||
const response = await fetch(url, {
|
||||
cf: { cacheEverything: true }
|
||||
});
|
||||
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("Cache-Control", "public, max-age=86400, immutable");
|
||||
headers.set("Access-Control-Allow-Origin", "*");
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Favicon Proxy Service
|
||||
*
|
||||
* Proxies favicon requests to DuckDuckGo's favicon service.
|
||||
* This allows fetching favicons for any domain without CORS issues.
|
||||
*
|
||||
* Usage: GET /favicon?url=https://example.com
|
||||
* Returns: The favicon image for the specified domain
|
||||
*/
|
||||
|
||||
export default {
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const requestUrl = new URL(request.url);
|
||||
const targetUrl = requestUrl.searchParams.get('url');
|
||||
|
||||
if (!targetUrl) {
|
||||
return new Response('Missing url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(targetUrl);
|
||||
} catch {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
// AI-provider-specific hacks
|
||||
let hostname = url.hostname;
|
||||
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
||||
hostname = 'ollama.com';
|
||||
} else if (url.host === 'generativelanguage.googleapis.com') {
|
||||
hostname = 'gemini.google.com';
|
||||
} else if (url.host === 'api.z.ai') {
|
||||
hostname = 'docs.z.ai';
|
||||
}
|
||||
|
||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||
hostname = hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
return fetchFavicon(hostname);
|
||||
},
|
||||
};
|
||||
|
||||
function fetchFavicon(hostname: string): Promise<Response> {
|
||||
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
||||
}
|
||||
@@ -41,7 +41,7 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/assets/main.js",
|
||||
"method": "GET",
|
||||
@@ -54,6 +54,23 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
"id": 123
|
||||
}
|
||||
|
||||
// POST Request with JSON body
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/api/data",
|
||||
"method": "POST",
|
||||
"headers": {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 encoded: {"name":"John","age":30}
|
||||
}
|
||||
},
|
||||
"id": 124
|
||||
}
|
||||
|
||||
// Success Response
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
@@ -64,7 +81,7 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
"Content-Type": "application/javascript",
|
||||
"Cache-Control": "no-cache"
|
||||
},
|
||||
"body": "console.log('hello');"
|
||||
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7" // base64 encoded: console.log('hello');
|
||||
},
|
||||
"id": 123
|
||||
}
|
||||
@@ -94,14 +111,14 @@ full request body support
|
||||
- `url` (string): Full URL of the request
|
||||
- `method` (string): HTTP method (GET, POST, etc.)
|
||||
- `headers` (object): Request headers as key-value pairs
|
||||
- `body` (string|null): Request body as string, or null if no body
|
||||
- `body` (string|null): Request body as base64 encoded string, or null if no body
|
||||
|
||||
**Result:**
|
||||
|
||||
- `status` (number): HTTP status code (200, 404, etc.)
|
||||
- `statusText` (string): HTTP status text ("OK", "Not Found", etc.)
|
||||
- `headers` (object): Response headers as key-value pairs
|
||||
- `body` (string|null): Response body content (null if status is 204)
|
||||
- `body` (string|null): Response body content as base64 encoded string (null if status is 204)
|
||||
|
||||
**Error Codes:**
|
||||
|
||||
@@ -117,19 +134,61 @@ full request body support
|
||||
- File uploads (as base64 strings)
|
||||
- Any HTTP method with body content
|
||||
|
||||
Request bodies are serialized as strings, so binary data should be
|
||||
base64-encoded.
|
||||
Request bodies must be base64-encoded strings when not null. This ensures
|
||||
consistent handling of both text and binary data across the messaging protocol.
|
||||
|
||||
### `console`
|
||||
|
||||
**Purpose:** Forward console messages from iframe to parent for display
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
|
||||
- `message` (string): The log message
|
||||
|
||||
**Result:** None (notification only, no response expected)
|
||||
|
||||
### Navigation Methods
|
||||
|
||||
#### `navigate`
|
||||
**Purpose:** Navigate iframe to a new URL within the same origin
|
||||
**Parameters:** `url` (string) - Target URL (must be same origin)
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `refresh`
|
||||
**Purpose:** Refresh/reload the current page in the iframe
|
||||
**Parameters:** None
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `goBack`
|
||||
**Purpose:** Navigate back in the iframe's history
|
||||
**Parameters:** None
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `goForward`
|
||||
**Purpose:** Navigate forward in the iframe's history
|
||||
**Parameters:** None
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `updateNavigationState`
|
||||
**Purpose:** Update parent about iframe's current navigation state
|
||||
**Parameters:**
|
||||
- `currentUrl` (string) - Current URL of the iframe
|
||||
- `canGoBack` (boolean) - Whether iframe can go back in history
|
||||
- `canGoForward` (boolean) - Whether iframe can go forward in history
|
||||
**Result:** None (notification only)
|
||||
|
||||
## Implementation
|
||||
|
||||
### Parent Page
|
||||
|
||||
In this example, the parent page acts as a static file server.
|
||||
The parent page acts as a static file server and console log collector:
|
||||
|
||||
```javascript
|
||||
class FetchClientParent {
|
||||
constructor(files) {
|
||||
this.files = files; // Map of path -> {content, contentType}
|
||||
this.consoleLogs = []; // Store console messages
|
||||
this.setupMessageListener();
|
||||
}
|
||||
|
||||
@@ -139,12 +198,43 @@ class FetchClientParent {
|
||||
if (event.origin !== "https://app123.example.com") return;
|
||||
|
||||
const message = event.data;
|
||||
|
||||
// Handle fetch requests
|
||||
if (message.jsonrpc === "2.0" && message.method === "fetch") {
|
||||
this.handleFetch(message);
|
||||
}
|
||||
|
||||
// Handle console messages
|
||||
if (message.jsonrpc === "2.0" && message.method === "console") {
|
||||
this.handleConsoleMessage(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
handleConsoleMessage(message) {
|
||||
const { params } = message;
|
||||
const { level, message: logMessage } = params;
|
||||
|
||||
// Store the log message
|
||||
this.consoleLogs.push({
|
||||
level,
|
||||
message: logMessage,
|
||||
timestamp: Date.now(),
|
||||
id: Date.now()
|
||||
});
|
||||
|
||||
// Update UI to show new logs
|
||||
this.updateConsoleUI();
|
||||
|
||||
// Also log to parent's console for debugging
|
||||
console[level](`[IFRAME] ${logMessage}`);
|
||||
}
|
||||
|
||||
updateConsoleUI() {
|
||||
// Implementation depends on your UI framework
|
||||
console.log(`Total console logs: ${this.consoleLogs.length}`);
|
||||
}
|
||||
|
||||
handleFetch(request) {
|
||||
const { params, id } = request;
|
||||
const { request: fetchRequest } = params;
|
||||
@@ -166,11 +256,10 @@ class FetchClientParent {
|
||||
"Content-Type": file.contentType,
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
body: file.content,
|
||||
body: btoa(file.content),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Return 404 response (not a JSON-RPC error)
|
||||
this.sendResponse({
|
||||
id,
|
||||
jsonrpc: "2.0",
|
||||
@@ -180,7 +269,7 @@ class FetchClientParent {
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
body: `File not found: ${path}`,
|
||||
body: btoa(`File not found: ${path}`),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -190,22 +279,15 @@ class FetchClientParent {
|
||||
const iframe = document.getElementById("preview-iframe");
|
||||
iframe.contentWindow.postMessage(message, "https://app123.example.com");
|
||||
}
|
||||
|
||||
sendError(message) {
|
||||
const iframe = document.getElementById("preview-iframe");
|
||||
iframe.contentWindow.postMessage(message, "https://app123.example.com");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Preview Page
|
||||
### iframe Client Communication
|
||||
|
||||
Below is a simplified RPC client that could be used inside the iframe's main
|
||||
thread to test functionality of the parent. In practice, requests originate from
|
||||
the ServiceWorker and the main thread acts as a relay, so multiple steps of
|
||||
communication are involved.
|
||||
The iframe client uses a simplified JSON-RPC client for communication. In the actual implementation, the ServiceWorker makes requests and the main thread acts as a relay:
|
||||
|
||||
```javascript
|
||||
// Simplified JSON-RPC client (actual implementation in _iframe-client/main.js)
|
||||
class JSONRPCClient {
|
||||
constructor() {
|
||||
this.requestId = 0;
|
||||
@@ -216,7 +298,7 @@ class JSONRPCClient {
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
const message = event.data;
|
||||
if (message.jsonrpc === "2.0" && message.id) {
|
||||
if (message.jsonrpc === "2.0" && message.id !== undefined) {
|
||||
this.handleResponse(message);
|
||||
}
|
||||
});
|
||||
@@ -228,7 +310,6 @@ class JSONRPCClient {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.pendingRequests.set(id, { resolve, reject });
|
||||
|
||||
// Send request to parent
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "fetch",
|
||||
@@ -236,7 +317,6 @@ class JSONRPCClient {
|
||||
id,
|
||||
}, "*");
|
||||
|
||||
// Timeout after 10 seconds
|
||||
setTimeout(() => {
|
||||
if (this.pendingRequests.has(id)) {
|
||||
this.pendingRequests.delete(id);
|
||||
@@ -255,15 +335,36 @@ class JSONRPCClient {
|
||||
this.pendingRequests.delete(id);
|
||||
|
||||
if (error) {
|
||||
pending.reject(new Error(error.message));
|
||||
pending.reject(new Error(`${error.message} (code: ${error.code})`));
|
||||
} else {
|
||||
// Result is a serialized response
|
||||
pending.resolve(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Base64 Encoding
|
||||
|
||||
All request and response bodies are base64 encoded when not null to ensure proper transmission through JSON-RPC:
|
||||
|
||||
- **Consistent Data Handling:** Both text and binary data are handled uniformly
|
||||
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
|
||||
- **Binary Data Support:** Enables transmission of images, files, and other binary content
|
||||
|
||||
**Encoding/Decoding:**
|
||||
```javascript
|
||||
// Encoding text content (parent side)
|
||||
const encodedBody = btoa(textContent);
|
||||
|
||||
// Encoding binary content (ServiceWorker side)
|
||||
const bytes = new Uint8Array(arrayBuffer);
|
||||
const encodedBody = btoa(String.fromCharCode(...bytes));
|
||||
|
||||
// Decoding (receiver side)
|
||||
const decodedText = atob(encodedBody);
|
||||
const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charCodeAt(0)));
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- **Origin Validation:** Always verify message origin
|
||||
@@ -287,9 +388,17 @@ class JSONRPCClient {
|
||||
content: "<!DOCTYPE html><html><body>Hello world!</body></html>",
|
||||
contentType: "text/html",
|
||||
}],
|
||||
["/app.js", {
|
||||
content: "console.log('App loaded');",
|
||||
contentType: "application/javascript",
|
||||
}],
|
||||
]);
|
||||
|
||||
// Example static file server
|
||||
// Initialize the fetch client parent
|
||||
new FetchClientParent(files);
|
||||
</script>
|
||||
```
|
||||
|
||||
## Console Logging Implementation
|
||||
|
||||
The iframe client automatically intercepts console messages and forwards them to the parent. The implementation (in `_iframe-client/main.js`) overrides console methods.
|
||||
@@ -54,30 +54,31 @@ blocked.
|
||||
|
||||
```
|
||||
/
|
||||
├── index.html # Main iframe client page
|
||||
├── _iframe-client.js # Main coordination script
|
||||
├── _iframe-client.css # Styles for the iframe client
|
||||
├── sw.js # ServiceWorker
|
||||
├── MESSAGING_PROTOCOL.md # Communication protocol docs
|
||||
├── example-parent.html # Example parent implementation
|
||||
└── README.md # This file
|
||||
├── index.html # Main iframe client page
|
||||
├── _iframe-client/
|
||||
│ ├── main.js # Main coordination script
|
||||
│ └── client.css # Styles for the iframe client
|
||||
├── sw.js # ServiceWorker
|
||||
├── MESSAGING_PROTOCOL.md # Communication protocol docs
|
||||
└── README.md # This file
|
||||
```
|
||||
|
||||
## Simplified JSON-RPC Protocol
|
||||
|
||||
The system now uses a drastically simplified JSON-RPC 2.0 protocol with only one
|
||||
method:
|
||||
The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
|
||||
|
||||
- **`fetch(request)`** - Handle HTTP requests with serialized fetch
|
||||
request/response
|
||||
- **`console(level, message)`** - Forward console messages from
|
||||
iframe to parent for display
|
||||
|
||||
**Request:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/assets/main.js",
|
||||
"method": "GET",
|
||||
@@ -106,6 +107,19 @@ method:
|
||||
}
|
||||
```
|
||||
|
||||
**Console Message:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "console",
|
||||
"params": {
|
||||
"level": "error",
|
||||
"message": "Failed to load module"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Initialization:**
|
||||
@@ -122,7 +136,27 @@ method:
|
||||
- Parent responds with serialized HTTP responses
|
||||
- ServiceWorker creates Response objects and returns them to the client app
|
||||
|
||||
3. **Content Replacement:**
|
||||
3. **SPA Routing Support:**
|
||||
- ServiceWorker detects navigation requests (HTML page requests with `mode: "navigate"`)
|
||||
- For SPA routes like `/about`, `/contact`, etc., the ServiceWorker serves the site's `index.html`
|
||||
- This allows the SPA's client-side router to handle the route properly
|
||||
- All other requests (assets, API calls, etc.) are handled normally via JSON-RPC
|
||||
|
||||
4. **Semantic Path Navigation:**
|
||||
- **Key Concept**: iframe stays on base URL (`/`) while communicating semantic paths to parent
|
||||
- When user navigates to `/about` in address bar, iframe doesn't actually change URL
|
||||
- Instead, NavigationHandler tracks semantic path (`/about`) and communicates it to parent
|
||||
- Parent displays semantic path while iframe remains on base URL
|
||||
- SPA's client-side router handles navigation internally without page reloads
|
||||
- This prevents 404 errors from literal path navigation
|
||||
|
||||
5. **SPA Navigation Tracking:**
|
||||
- NavigationHandler overrides `history.pushState()` and `history.replaceState()` to detect SPA navigation
|
||||
- When SPAs change URLs via history methods, NavigationHandler detects the change and sends navigation state to parent
|
||||
- Navigation state includes semantic path, back/forward capability, and history tracking
|
||||
- Parent can display current semantic path and enable proper back/forward navigation controls
|
||||
|
||||
6. **Content Replacement:**
|
||||
- Main thread requests `/` from parent via JSON-RPC fetch
|
||||
- Replaces its own content with the site index
|
||||
- Site runs normally, with all requests handled by SW via JSON-RPC
|
||||
@@ -136,8 +170,9 @@ Deploy these files to your iframe client subdomain:
|
||||
```
|
||||
https://*.example.com/
|
||||
├── index.html
|
||||
├── _iframe-client.js
|
||||
├── _iframe-client.css
|
||||
├── _iframe-client/
|
||||
│ ├── main.js
|
||||
│ └── client.css
|
||||
└── sw.js
|
||||
```
|
||||
|
||||
@@ -158,8 +193,7 @@ Include the iframe client in your parent page:
|
||||
</iframe>
|
||||
```
|
||||
|
||||
Implement the JSON-RPC protocol (see `example-parent.html` for a complete
|
||||
example):
|
||||
Implement the JSON-RPC protocol:
|
||||
|
||||
```javascript
|
||||
class FetchClientParent {
|
||||
@@ -270,9 +304,9 @@ function handleRequest(fetchRequest) {
|
||||
|
||||
## Testing
|
||||
|
||||
1. Open `example-parent.html` in a browser
|
||||
2. Click "Load Sample Site"
|
||||
3. The iframe client should load and display the sample app
|
||||
1. Create a parent page implementing the JSON-RPC protocol (see example in MESSAGING_PROTOCOL.md)
|
||||
2. Load the iframe client in an iframe pointing to your deployed client domain
|
||||
3. The iframe client should load and display the served content
|
||||
4. Test navigation and functionality within the iframe client
|
||||
|
||||
## Browser Support
|
||||
@@ -308,14 +342,22 @@ function handleRequest(fetchRequest) {
|
||||
- Check that JSON-RPC messages are properly formatted
|
||||
- Ensure iframe has appropriate sandbox permissions
|
||||
|
||||
### SPA routes don't work
|
||||
|
||||
- Ensure the parent page serves the correct `index.html` for the root path `/`
|
||||
- Check that the SPA's client-side router is properly configured
|
||||
- Verify that navigation requests are being detected correctly by the ServiceWorker
|
||||
- Make sure the parent page returns the same `index.html` content for SPA routes as it does for the root path
|
||||
- **Important**: iframe should stay on base URL (`/`) while semantic paths are communicated to parent. If you see literal path navigation (iframe URL changing to `/about`), this indicates a configuration issue.
|
||||
|
||||
## Development
|
||||
|
||||
To modify the system:
|
||||
|
||||
1. **iframe Client:** Edit `index.html`, `_iframe-client.js`,
|
||||
`_iframe-client.css`, `sw.js`
|
||||
1. **iframe Client:** Edit `index.html`, `_iframe-client/main.js`,
|
||||
`_iframe-client/client.css`, `sw.js`
|
||||
2. **Protocol:** Update `MESSAGING_PROTOCOL.md` for any changes
|
||||
3. **Testing:** Use `example-parent.html` for testing changes
|
||||
3. **Testing:** Create a parent page implementing the JSON-RPC protocol for testing changes
|
||||
|
||||
## License
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
/**
|
||||
* iframe Fetch Client - Simplified Implementation
|
||||
* Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md
|
||||
*/
|
||||
|
||||
// JSON-RPC Client for communication with parent
|
||||
class JSONRPCClient {
|
||||
constructor() {
|
||||
this.requestId = 0;
|
||||
this.pendingRequests = new Map();
|
||||
this.setupMessageListener();
|
||||
}
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
// Only accept messages from parent window for security
|
||||
if (event.source !== window.parent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
// Check if this is a response to our own request or a ServiceWorker request
|
||||
if (message.jsonrpc === "2.0" && message.id !== undefined) {
|
||||
if (this.pendingRequests.has(message.id)) {
|
||||
this.handleResponse(message);
|
||||
} else {
|
||||
// This is a response to a ServiceWorker request, relay it back
|
||||
this.relayToServiceWorker(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
relayToServiceWorker(response) {
|
||||
// Forward the JSON-RPC response to ServiceWorker
|
||||
if (navigator.serviceWorker.controller) {
|
||||
navigator.serviceWorker.controller.postMessage(response);
|
||||
}
|
||||
}
|
||||
|
||||
async fetch(request) {
|
||||
const id = ++this.requestId;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.pendingRequests.set(id, { resolve, reject });
|
||||
|
||||
// Send JSON-RPC request to parent
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "fetch",
|
||||
params: { request },
|
||||
id,
|
||||
}, "*");
|
||||
|
||||
// Timeout after 10 seconds
|
||||
setTimeout(() => {
|
||||
if (this.pendingRequests.has(id)) {
|
||||
this.pendingRequests.delete(id);
|
||||
reject(new Error(`Timeout fetching: ${request.url}`));
|
||||
}
|
||||
}, 10000);
|
||||
});
|
||||
}
|
||||
|
||||
handleResponse(message) {
|
||||
const { id, result, error } = message;
|
||||
const pending = this.pendingRequests.get(id);
|
||||
|
||||
if (!pending) return;
|
||||
|
||||
this.pendingRequests.delete(id);
|
||||
|
||||
if (error) {
|
||||
pending.reject(new Error(`${error.message} (code: ${error.code})`));
|
||||
} else {
|
||||
pending.resolve(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Console Interceptor - forwards console messages to parent
|
||||
class ConsoleInterceptor {
|
||||
constructor() {
|
||||
this.originalConsole = {};
|
||||
this.methods = ['log', 'warn', 'error', 'info', 'debug'];
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
// Store original methods and override in single pass
|
||||
this.methods.forEach((method) => {
|
||||
if (typeof console[method] === 'function') {
|
||||
this.originalConsole[method] = console[method];
|
||||
|
||||
console[method] = (...args) => {
|
||||
// Call original method
|
||||
try {
|
||||
this.originalConsole[method](...args);
|
||||
} catch (e) {
|
||||
// Continue if original fails
|
||||
}
|
||||
|
||||
// Send to parent
|
||||
this.sendConsoleMessage(method, ...args);
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
sendConsoleMessage(level, ...args) {
|
||||
const message = args.map((arg) => {
|
||||
if (arg === undefined) return 'undefined';
|
||||
if (arg === null) return 'null';
|
||||
if (typeof arg === 'object') {
|
||||
try {
|
||||
return JSON.stringify(arg, (key, value) => {
|
||||
if (value instanceof Error) {
|
||||
return {
|
||||
name: value.name,
|
||||
message: value.message,
|
||||
stack: value.stack
|
||||
};
|
||||
}
|
||||
return value;
|
||||
});
|
||||
} catch {
|
||||
return String(arg);
|
||||
}
|
||||
}
|
||||
return String(arg);
|
||||
}).join(' ');
|
||||
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "console",
|
||||
params: { level, message }
|
||||
}, "*");
|
||||
} catch (error) {
|
||||
// Retry once after delay if postMessage fails
|
||||
setTimeout(() => {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "console",
|
||||
params: { level: "error", message: `[DELAYED] ${message}` }
|
||||
}, "*");
|
||||
} catch {
|
||||
// Give up if retry fails
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation Handler - manages iframe navigation and history
|
||||
class NavigationHandler {
|
||||
constructor() {
|
||||
// Get initial path from window property or default to root
|
||||
this.currentSemanticPath = window.__IFRAME_INITIAL_PATH__ || '/';
|
||||
|
||||
this.setupMessageListener();
|
||||
this.setupHistoryListeners();
|
||||
this.overrideHistoryMethods();
|
||||
this.updateNavigationState();
|
||||
}
|
||||
|
||||
// Extract semantic path from URL or string
|
||||
extractSemanticPath(urlOrString) {
|
||||
try {
|
||||
const url = typeof urlOrString === 'string'
|
||||
? new URL(urlOrString, window.location.origin)
|
||||
: urlOrString;
|
||||
return url.pathname + url.search + url.hash;
|
||||
} catch {
|
||||
return window.location.pathname + window.location.search + window.location.hash;
|
||||
}
|
||||
}
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
// Only accept messages from parent window for security
|
||||
if (event.source !== window.parent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
if (message.jsonrpc === "2.0") {
|
||||
switch (message.method) {
|
||||
case "navigate":
|
||||
this.handleNavigate(message.params.url);
|
||||
break;
|
||||
case "refresh":
|
||||
this.handleRefresh();
|
||||
break;
|
||||
case "goBack":
|
||||
this.handleGoBack();
|
||||
break;
|
||||
case "goForward":
|
||||
this.handleGoForward();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
setupHistoryListeners() {
|
||||
// Listen for popstate events (back/forward navigation)
|
||||
window.addEventListener('popstate', () => {
|
||||
this.currentSemanticPath = this.extractSemanticPath(window.location);
|
||||
this.updateNavigationState();
|
||||
});
|
||||
|
||||
// Listen for hash changes
|
||||
window.addEventListener('hashchange', () => {
|
||||
this.currentSemanticPath = this.extractSemanticPath(window.location);
|
||||
this.updateNavigationState();
|
||||
});
|
||||
}
|
||||
|
||||
overrideHistoryMethods() {
|
||||
// Override history.pushState and history.replaceState to detect SPA navigation
|
||||
this.originalPushState = window.history.pushState;
|
||||
this.originalReplaceState = window.history.replaceState;
|
||||
|
||||
window.history.pushState = (...args) => {
|
||||
const result = this.originalPushState.apply(window.history, args);
|
||||
|
||||
// Extract semantic path from URL argument or use current location
|
||||
const semanticPath = args[2]
|
||||
? this.extractSemanticPath(args[2])
|
||||
: this.extractSemanticPath(window.location);
|
||||
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
return result;
|
||||
};
|
||||
|
||||
window.history.replaceState = (...args) => {
|
||||
const result = this.originalReplaceState.apply(window.history, args);
|
||||
|
||||
const semanticPath = args[2]
|
||||
? this.extractSemanticPath(args[2])
|
||||
: this.extractSemanticPath(window.location);
|
||||
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
handleNavigate(url) {
|
||||
try {
|
||||
// Validate URL - must be same origin
|
||||
const targetUrl = new URL(url, window.location.origin);
|
||||
if (targetUrl.origin !== window.location.origin) {
|
||||
console.error('Navigation to different origin not allowed:', url);
|
||||
return;
|
||||
}
|
||||
|
||||
const semanticPath = this.extractSemanticPath(targetUrl);
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
|
||||
// Trigger SPA navigation
|
||||
window.history.pushState({}, '', semanticPath);
|
||||
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
|
||||
|
||||
} catch (error) {
|
||||
console.error('Invalid navigation URL:', url, error);
|
||||
}
|
||||
}
|
||||
|
||||
handleRefresh() {
|
||||
// Store current semantic path for reload
|
||||
const currentPath = this.currentSemanticPath || '/';
|
||||
|
||||
// Save the current path to sessionStorage so it persists across reload
|
||||
try {
|
||||
sessionStorage.setItem('iframe_initial_path', currentPath);
|
||||
} catch (error) {
|
||||
console.warn('Failed to store initial path in sessionStorage:', error);
|
||||
}
|
||||
|
||||
// Actually reload the iframe to get a fresh SPA instance
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
handleGoBack() {
|
||||
window.history.back();
|
||||
}
|
||||
|
||||
handleGoForward() {
|
||||
window.history.forward();
|
||||
}
|
||||
|
||||
updateNavigationState() {
|
||||
// Use tracked semantic path, fallback to current location if needed
|
||||
const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location);
|
||||
|
||||
const state = {
|
||||
currentUrl: semanticPath,
|
||||
canGoBack: false, // Let parent handle history tracking
|
||||
canGoForward: false // Let parent handle history tracking
|
||||
};
|
||||
|
||||
// Send navigation state to parent
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "updateNavigationState",
|
||||
params: state
|
||||
}, "*");
|
||||
} catch (error) {
|
||||
console.error('Failed to send navigation state:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Main Fetch Client
|
||||
class FetchClient {
|
||||
constructor() {
|
||||
this.rpcClient = new JSONRPCClient();
|
||||
this.consoleInterceptor = new ConsoleInterceptor();
|
||||
this.navigationHandler = new NavigationHandler();
|
||||
this.init();
|
||||
}
|
||||
|
||||
// Ensure SPA navigates to initial path after document is loaded
|
||||
ensureInitialNavigation() {
|
||||
// Wait for the SPA to initialize, then navigate to the initial path
|
||||
setTimeout(() => {
|
||||
const initialPath = window.__IFRAME_INITIAL_PATH__;
|
||||
|
||||
if (initialPath && initialPath !== '/') {
|
||||
const currentPath = window.location.pathname + window.location.search + window.location.hash;
|
||||
|
||||
// If we're not already at the initial path, navigate there
|
||||
if (currentPath !== initialPath) {
|
||||
this.navigationHandler.handleNavigate(initialPath);
|
||||
}
|
||||
}
|
||||
}, 150); // Give SPA more time to initialize
|
||||
}
|
||||
|
||||
async init() {
|
||||
try {
|
||||
await this.setupServiceWorker();
|
||||
await this.loadSiteIndex();
|
||||
} catch (error) {
|
||||
console.error("FetchClient: Initialization failed:", error);
|
||||
this.showError("Failed to initialize fetch client", error);
|
||||
}
|
||||
}
|
||||
|
||||
async setupServiceWorker() {
|
||||
if (!("serviceWorker" in navigator)) {
|
||||
throw new Error("ServiceWorker not supported");
|
||||
}
|
||||
|
||||
// Check if already registered
|
||||
const existing = await navigator.serviceWorker.getRegistration();
|
||||
if (existing) {
|
||||
console.log("ServiceWorker already registered");
|
||||
this.setupServiceWorkerCommunication();
|
||||
return;
|
||||
}
|
||||
|
||||
// Register new ServiceWorker
|
||||
const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" });
|
||||
console.log("ServiceWorker registered:", registration);
|
||||
|
||||
await navigator.serviceWorker.ready;
|
||||
this.setupServiceWorkerCommunication();
|
||||
this.blockFutureRegistrations(); // Block future registrations to prevent site from registering its own SW
|
||||
}
|
||||
|
||||
setupServiceWorkerCommunication() {
|
||||
// Relay JSON-RPC requests from ServiceWorker to parent
|
||||
navigator.serviceWorker.addEventListener("message", (event) => {
|
||||
const { data } = event;
|
||||
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
|
||||
window.parent.postMessage(data, "*");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
blockFutureRegistrations() {
|
||||
navigator.serviceWorker.register = () => {
|
||||
console.log("Blocked ServiceWorker registration attempt");
|
||||
return Promise.resolve({
|
||||
scope: "/",
|
||||
active: navigator.serviceWorker.controller,
|
||||
installing: null,
|
||||
waiting: null,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
async loadSiteIndex() {
|
||||
// Check if we have a stored initial path from a refresh
|
||||
let initialPath = '/';
|
||||
try {
|
||||
const storedPath = sessionStorage.getItem('iframe_initial_path');
|
||||
if (storedPath) {
|
||||
initialPath = storedPath;
|
||||
// Clear the stored path after using it
|
||||
sessionStorage.removeItem('iframe_initial_path');
|
||||
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('loadSiteIndex: Failed to read initial path from sessionStorage:', error);
|
||||
}
|
||||
|
||||
const serializedRequest = {
|
||||
url: `${location.origin}/`,
|
||||
method: "GET",
|
||||
body: null,
|
||||
headers: {},
|
||||
};
|
||||
|
||||
const response = await this.rpcClient.fetch(serializedRequest);
|
||||
|
||||
if (response?.status !== 200) {
|
||||
throw new Error(`Failed to fetch site index: ${response?.status || 'Invalid response from site: ' + response} ${response?.statusText || ''}`);
|
||||
}
|
||||
|
||||
if (response.headers["Content-Type"] !== "text/html") {
|
||||
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
|
||||
const text = new TextDecoder().decode(bytes);
|
||||
|
||||
// Set the initial path on window before replacing the document
|
||||
// This will be available to the NavigationHandler when it initializes
|
||||
if (initialPath && initialPath !== '/') {
|
||||
window.__IFRAME_INITIAL_PATH__ = initialPath;
|
||||
}
|
||||
|
||||
this.replaceDocument(text);
|
||||
}
|
||||
|
||||
replaceDocument(htmlContent) {
|
||||
console.log("replaceDocument: Starting...");
|
||||
|
||||
// Restore the initial path from sessionStorage before replacing document
|
||||
let initialPath = '/';
|
||||
try {
|
||||
const storedPath = sessionStorage.getItem('spa_initial_path');
|
||||
if (storedPath) {
|
||||
initialPath = storedPath;
|
||||
sessionStorage.removeItem('spa_initial_path');
|
||||
console.log('replaceDocument: Restored initial path:', initialPath);
|
||||
// Set it on window for the new document
|
||||
window.__IFRAME_INITIAL_PATH__ = initialPath;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('replaceDocument: Failed to restore initial path:', error);
|
||||
}
|
||||
|
||||
// Create a new document from the HTML content
|
||||
const parser = new DOMParser();
|
||||
const newDoc = parser.parseFromString(htmlContent, "text/html");
|
||||
|
||||
// Extract scripts for re-execution
|
||||
const scripts = [];
|
||||
newDoc.querySelectorAll("script").forEach((script) => {
|
||||
scripts.push({
|
||||
src: script.src,
|
||||
type: script.type,
|
||||
async: script.hasAttribute("async"),
|
||||
defer: script.hasAttribute("defer"),
|
||||
});
|
||||
script.remove();
|
||||
});
|
||||
|
||||
// Replace document content
|
||||
document.head.innerHTML = newDoc.head.innerHTML;
|
||||
document.body.innerHTML = newDoc.body.innerHTML;
|
||||
|
||||
// Re-add scripts to execute them
|
||||
scripts.forEach((script) => {
|
||||
const newScript = document.createElement("script");
|
||||
newScript.src = script.src;
|
||||
newScript.type = script.type;
|
||||
if (script.async) newScript.async = true;
|
||||
if (script.defer) newScript.defer = true;
|
||||
document.body.appendChild(newScript);
|
||||
});
|
||||
|
||||
// Ensure initial navigation after document is loaded
|
||||
this.ensureInitialNavigation();
|
||||
}
|
||||
|
||||
showError(message, error) {
|
||||
console.error(message, error);
|
||||
|
||||
document.body.innerHTML = `
|
||||
<div style="
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
max-width: 600px;
|
||||
margin: 50px auto;
|
||||
padding: 20px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
border-left: 4px solid #dc3545;
|
||||
">
|
||||
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
|
||||
<p><strong>${message}</strong></p>
|
||||
<p style="color: #6c757d;">${error.message || error}</p>
|
||||
<details style="margin-top: 20px;">
|
||||
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
|
||||
<pre style="
|
||||
background: #f1f3f4;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
overflow-x: auto;
|
||||
font-size: 12px;
|
||||
margin-top: 10px;
|
||||
">${error.stack || JSON.stringify(error, null, 2)}</pre>
|
||||
</details>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// Global error handlers
|
||||
const setupGlobalErrorHandlers = () => {
|
||||
window.addEventListener('error', (event) => {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "console",
|
||||
params: {
|
||||
level: "error",
|
||||
message: `Uncaught Error: ${event.message}`,
|
||||
source: event.filename,
|
||||
lineno: event.lineno,
|
||||
colno: event.colno,
|
||||
stack: event.error?.stack
|
||||
}
|
||||
}, "*");
|
||||
} catch {
|
||||
// Ignore postMessage errors
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "console",
|
||||
params: {
|
||||
level: "error",
|
||||
message: "Unhandled Promise Rejection",
|
||||
reason: event.reason,
|
||||
promise: event.promise ? 'Promise object' : 'No promise object'
|
||||
}
|
||||
}, "*");
|
||||
} catch {
|
||||
// Ignore postMessage errors
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Initialize
|
||||
setupGlobalErrorHandlers();
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () => new FetchClient());
|
||||
} else {
|
||||
new FetchClient();
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Site Preview</title>
|
||||
<link rel="stylesheet" href="/_iframe-client.css">
|
||||
<link rel="stylesheet" href="/_iframe-client/client.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="loading">
|
||||
@@ -12,6 +12,6 @@
|
||||
<p>Loading preview...</p>
|
||||
<p><small>Waiting for ServiceWorker and parent communication</small></p>
|
||||
</div>
|
||||
<script src="/_iframe-client.js"></script>
|
||||
<script type="module" src="/_iframe-client/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -48,7 +48,14 @@ function handleJSONRPCResponse(message) {
|
||||
|
||||
// Create response from serialized response
|
||||
const { status, statusText, headers, body } = result;
|
||||
const response = new Response(body, {
|
||||
|
||||
// Decode base64 body if present
|
||||
let decoded = null;
|
||||
if (typeof body === "string") {
|
||||
decoded = new Uint8Array(atob(body).split('').map(c => c.charCodeAt(0)));
|
||||
}
|
||||
|
||||
const response = new Response(decoded, {
|
||||
status: status || 200,
|
||||
statusText: statusText || "OK",
|
||||
headers: headers || {},
|
||||
@@ -61,22 +68,37 @@ async function requestViaJSONRPC(request) {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const id = ++requestIdCounter;
|
||||
|
||||
// Serialize the fetch request
|
||||
let body = null;
|
||||
if (request.body) {
|
||||
try {
|
||||
// Convert body to string (JSON-serializable)
|
||||
body = await request.text();
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||
return;
|
||||
// Check if request is a plain object or Request object
|
||||
let url, method, headers, body;
|
||||
|
||||
if (request instanceof Request) {
|
||||
// Handle Request object
|
||||
url = request.url;
|
||||
method = request.method;
|
||||
headers = Object.fromEntries(request.headers.entries());
|
||||
|
||||
if (request.body) {
|
||||
try {
|
||||
// Convert body to Uint8Array then base64 encode
|
||||
const bytes = await request.bytes();
|
||||
body = btoa(String.fromCharCode(...bytes));
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Handle plain request object
|
||||
url = request.url;
|
||||
method = request.method || 'GET';
|
||||
headers = request.headers || {};
|
||||
body = request.body || null;
|
||||
}
|
||||
|
||||
const serializedRequest = {
|
||||
url: request.url,
|
||||
method: request.method,
|
||||
headers: Object.fromEntries(request.headers.entries()),
|
||||
url: url,
|
||||
method: method,
|
||||
headers: headers,
|
||||
body: body,
|
||||
};
|
||||
|
||||
@@ -101,7 +123,7 @@ async function requestViaJSONRPC(request) {
|
||||
setTimeout(() => {
|
||||
if (pendingRequests.has(id)) {
|
||||
pendingRequests.delete(id);
|
||||
reject(new Error(`Timeout requesting: ${request.url}`));
|
||||
reject(new Error(`Timeout requesting: ${url}`));
|
||||
}
|
||||
}, 10000);
|
||||
});
|
||||
@@ -126,6 +148,38 @@ self.addEventListener("fetch", (event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Let iframe client assets be handled normally (anything in _iframe-client directory and common assets)
|
||||
if (url.pathname.startsWith("/_iframe-client/") ||
|
||||
url.pathname === "/favicon.ico" ||
|
||||
url.pathname === "/manifest.webmanifest") {
|
||||
return;
|
||||
}
|
||||
|
||||
// For SPA routes, check if this is a navigation request (HTML page request)
|
||||
// But first check if we need to load the iframe client (this happens during refresh)
|
||||
if (event.request.mode === "navigate" &&
|
||||
(event.request.headers.get("accept") || "").includes("text/html")) {
|
||||
|
||||
// Check if this is a request for the iframe client itself
|
||||
// We need to serve the iframe client HTML first, which will then load the SPA
|
||||
if (url.pathname !== "/") {
|
||||
// Redirect to root to load the iframe client, which will then navigate to the target path
|
||||
const response = Response.redirect(new URL("/", event.request.url).href, 302);
|
||||
event.respondWith(response);
|
||||
return;
|
||||
}
|
||||
|
||||
// This is a request for the root path, serve the site's index.html via JSON-RPC
|
||||
const rootRequest = {
|
||||
url: new URL("/", event.request.url).href,
|
||||
method: event.request.method,
|
||||
headers: Object.fromEntries(event.request.headers.entries()),
|
||||
body: event.request.body
|
||||
};
|
||||
event.respondWith(handleRequest(rootRequest));
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle all other requests through JSON-RPC communication
|
||||
event.respondWith(handleRequest(event.request));
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
export default {
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
const target = url.searchParams.get("url");
|
||||
|
||||
if (!target) {
|
||||
return new Response("Include a `url` query parameter", { status: 400 });
|
||||
}
|
||||
|
||||
// Handle CORS preflight requests
|
||||
if (request.method === "OPTIONS") {
|
||||
return new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
|
||||
"Access-Control-Allow-Headers": "*", // Or specify specific headers
|
||||
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('User-Agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
||||
|
||||
const targetResponse = await fetch(target, {
|
||||
method: request.method,
|
||||
headers: headers,
|
||||
body: request.body,
|
||||
});
|
||||
|
||||
const response = new Response(targetResponse.body, targetResponse);
|
||||
|
||||
response.headers.set("Access-Control-Allow-Origin", "*");
|
||||
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS");
|
||||
response.headers.set("Access-Control-Allow-Headers", "*");
|
||||
|
||||
return response;
|
||||
}
|
||||
};
|
||||
@@ -1,8 +1,11 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { test } from 'vitest';
|
||||
import { test, expect } from 'vitest';
|
||||
|
||||
import App from './App';
|
||||
|
||||
test('App', () => {
|
||||
render(<App />);
|
||||
const { container } = render(<App />);
|
||||
|
||||
// Basic smoke test to ensure App renders without crashing
|
||||
expect(container).toBeInTheDocument();
|
||||
})
|
||||
@@ -4,20 +4,31 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createHead, UnheadProvider } from '@unhead/react/client';
|
||||
import { InferSeoMetaPlugin } from '@unhead/addons';
|
||||
import { Suspense } from 'react';
|
||||
import { Suspense, useEffect } from 'react';
|
||||
import LightningFS from '@isomorphic-git/lightning-fs';
|
||||
import NostrProvider from '@/components/NostrProvider';
|
||||
import { NostrSync } from '@/components/NostrSync';
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { Toaster as Sonner } from "@/components/ui/sonner";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { SentryProvider } from '@/components/SentryProvider';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { JSRuntimeProvider } from '@/components/JSRuntimeProvider';
|
||||
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { WebContainerAdapter } from '@/lib/WebContainerAdapter';
|
||||
import { ElectronFSAdapter } from '@/lib/ElectronFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
import { DynamicFavicon } from '@/components/DynamicFavicon';
|
||||
import { OfflineIndicator } from '@/components/OfflineIndicator';
|
||||
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
|
||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
const head = createHead({
|
||||
@@ -36,50 +47,142 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
});
|
||||
|
||||
// Get OS-specific default paths for Electron
|
||||
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } {
|
||||
if (!globalThis.electron) {
|
||||
// Browser defaults - use virtual filesystem paths
|
||||
return {
|
||||
fsPathProjects: "/projects",
|
||||
fsPathConfig: "/config",
|
||||
fsPathTmp: "/tmp",
|
||||
fsPathPlugins: "/plugins",
|
||||
fsPathTemplates: "/templates",
|
||||
};
|
||||
}
|
||||
|
||||
// Electron defaults - use OS-specific paths
|
||||
// Note: The ~ will be expanded by the Electron main process
|
||||
const platform = navigator.platform.toLowerCase();
|
||||
|
||||
if (platform.includes('win')) {
|
||||
// Windows
|
||||
return {
|
||||
fsPathProjects: "~/Documents/Projects",
|
||||
fsPathConfig: "~/AppData/Local/shakespeare",
|
||||
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
|
||||
fsPathPlugins: "~/AppData/Local/shakespeare/plugins",
|
||||
fsPathTemplates: "~/AppData/Local/shakespeare/templates",
|
||||
};
|
||||
} else if (platform.includes('mac')) {
|
||||
// macOS
|
||||
return {
|
||||
fsPathProjects: "~/Projects",
|
||||
fsPathConfig: "~/Library/Application Support/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
fsPathPlugins: "~/Library/Application Support/shakespeare/plugins",
|
||||
fsPathTemplates: "~/Library/Application Support/shakespeare/templates",
|
||||
};
|
||||
} else {
|
||||
// Linux and other Unix-like systems
|
||||
return {
|
||||
fsPathProjects: "~/Projects",
|
||||
fsPathConfig: "~/.config/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
fsPathPlugins: "~/.config/shakespeare/plugins",
|
||||
fsPathTemplates: "~/.config/shakespeare/templates",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const electronPaths = getElectronDefaultPaths();
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
theme: "system",
|
||||
relayMetadata: {
|
||||
relays: [
|
||||
{ url: 'wss://relay.ditto.pub', read: true, write: true },
|
||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||
{ url: 'wss://relay.primal.net', read: true, write: true },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
|
||||
esmUrl: "https://esm.sh",
|
||||
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
|
||||
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
|
||||
previewDomain: "local-shakespeare.dev",
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
|
||||
ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"],
|
||||
fsPathProjects: electronPaths.fsPathProjects,
|
||||
fsPathConfig: electronPaths.fsPathConfig,
|
||||
fsPathTmp: electronPaths.fsPathTmp,
|
||||
fsPathPlugins: electronPaths.fsPathPlugins,
|
||||
fsPathTemplates: electronPaths.fsPathTemplates,
|
||||
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
|
||||
sentryEnabled: true,
|
||||
};
|
||||
|
||||
const presetRelays = [
|
||||
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
|
||||
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
|
||||
{ url: 'wss://relay.damus.io', name: 'Damus' },
|
||||
{ url: 'wss://relay.primal.net', name: 'Primal' },
|
||||
];
|
||||
// Initialize filesystem adapter based on environment
|
||||
// In Electron, use Electron filesystem at ~/shakespeare
|
||||
// In browser, use LightningFS (IndexedDB-backed virtual filesystem)
|
||||
const fs = globalThis.electron
|
||||
? new ElectronFSAdapter()
|
||||
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
|
||||
|
||||
// Initialize LightningFS
|
||||
const lightningFS = new LightningFS('shakespeare-fs');
|
||||
const fs = new LightningFSAdapter(lightningFS.promises);
|
||||
// Component to handle filesystem cleanup on startup
|
||||
// Automatically removes files older than 1 hour from tmp directory
|
||||
function FSCleanupHandler() {
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Initialize JSRuntime with WebContainer adapter
|
||||
const jsRuntime = new WebContainerAdapter();
|
||||
useEffect(() => {
|
||||
// Run cleanup on application startup to remove stale temporary files
|
||||
// This helps prevent the VFS from accumulating old files over time
|
||||
cleanupTmpDirectory(fs, config.fsPathTmp).catch(console.error);
|
||||
}, [config.fsPathTmp]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<UnheadProvider head={head}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<JSRuntimeProvider runtime={jsRuntime}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Sonner />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</QueryClientProvider>
|
||||
</JSRuntimeProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</UnheadProvider>
|
||||
<ErrorBoundary>
|
||||
<UnheadProvider head={head}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
|
||||
<SentryProvider>
|
||||
<FSProvider fs={fs}>
|
||||
<ConsoleErrorProvider>
|
||||
<FSCleanupHandler />
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NostrSync />
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
</FSProvider>
|
||||
</SentryProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
</UnheadProvider>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +1,62 @@
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
import { SessionMonitor } from "./components/SessionMonitor";
|
||||
import { URLFragmentHandler } from "./components/URLFragmentHandler";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
import Settings from "./pages/Settings";
|
||||
import Preferences from "./pages/Preferences";
|
||||
import NostrSettings from "./pages/NostrSettings";
|
||||
import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DeploySettings from "./pages/DeploySettings";
|
||||
import SystemSettings from "./pages/SystemSettings";
|
||||
import StorageSettings from "./pages/StorageSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||
import VercelOAuth from "./pages/VercelOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
import { SettingsLayout } from "./components/SettingsLayout";
|
||||
|
||||
export function AppRouter() {
|
||||
// Use HashRouter in Electron, BrowserRouter in web
|
||||
const Router = globalThis.electron ? HashRouter : BrowserRouter;
|
||||
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Router>
|
||||
<ScrollToTop />
|
||||
<SessionMonitor />
|
||||
<URLFragmentHandler />
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/giftcard" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="preferences" element={<Preferences />} />
|
||||
<Route path="nostr" element={<NostrSettings />} />
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="deploy" element={<DeploySettings />} />
|
||||
<Route path="system" element={<SystemSettings />} />
|
||||
<Route path="storage" element={<StorageSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
<Route path="/:nip19" element={<NIP19Page />} />
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
export default AppRouter;
|
||||
@@ -0,0 +1,114 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="500px" height="500px" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 1.5,10.5 C 2.83333,11.1667 2.83333,11.1667 1.5,10.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 287.5,14.5 C 288.833,15.1667 288.833,15.1667 287.5,14.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 393.5,19.5 C 394.833,20.1667 394.833,20.1667 393.5,19.5 Z"/></g>
|
||||
<g><path style="opacity:0.067" fill="#d8d5d1" d="M 257.5,33.5 C 252.167,33.5 246.833,33.5 241.5,33.5C 246.567,32.8118 251.733,32.1451 257,31.5C 257.464,32.0944 257.631,32.7611 257.5,33.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 304.5,37.5 C 305.833,38.1667 305.833,38.1667 304.5,37.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 199.5,52.5 C 198.833,51.1667 198.833,51.1667 199.5,52.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#272422" d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z"/></g>
|
||||
<g><path style="opacity:0.435" fill="#9b9895" d="M 195.5,57.5 C 195.573,59.0269 194.906,60.0269 193.5,60.5C 193.427,58.9731 194.094,57.9731 195.5,57.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 404.5,60.5 C 405.833,61.1667 405.833,61.1667 404.5,60.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 92.5,61.5 C 93.8333,62.1667 93.8333,62.1667 92.5,61.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#1c1a18" d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 448.5,63.5 C 449.833,64.1667 449.833,64.1667 448.5,63.5 Z"/></g>
|
||||
<g><path style="opacity:0.141" fill="#b0abaa" d="M 291.5,64.5 C 293.104,65.287 293.771,66.6203 293.5,68.5C 292.326,67.4863 291.66,66.153 291.5,64.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 426.5,69.5 C 427.833,70.1667 427.833,70.1667 426.5,69.5 Z"/></g>
|
||||
<g><path style="opacity:0.09" fill="#c3bbb9" d="M 187.5,70.5 C 187.573,72.0269 186.906,73.0269 185.5,73.5C 185.427,71.9731 186.094,70.9731 187.5,70.5 Z"/></g>
|
||||
<g><path style="opacity:0.824" fill="#726e69" d="M 312.5,71.5 C 314.729,74.3538 316.062,77.6871 316.5,81.5C 315.043,79.7582 313.876,77.7582 313,75.5C 312.51,74.2068 312.343,72.8734 312.5,71.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 487.5,76.5 C 488.833,77.1667 488.833,77.1667 487.5,76.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 387.5,78.5 C 388.833,79.1667 388.833,79.1667 387.5,78.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#1e1d1b" d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 20.5,86.5 C 21.8333,87.1667 21.8333,87.1667 20.5,86.5 Z"/></g>
|
||||
<g><path style="opacity:0.792" fill="#97938f" d="M 272.5,96.5 C 275.189,97.1894 276.856,98.856 277.5,101.5C 275.451,100.118 273.785,98.4516 272.5,96.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#23201e" d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#d7d2ce" d="M 269.5,104.5 C 270.5,104.833 271.167,105.5 271.5,106.5C 270.167,106.5 269.5,105.833 269.5,104.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#242220" d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#272422" d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z"/></g>
|
||||
<g><path style="opacity:0.137" fill="#a59b96" d="M 163.5,112.5 C 163.573,114.027 162.906,115.027 161.5,115.5C 161.427,113.973 162.094,112.973 163.5,112.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 89.5,117.5 C 90.8333,118.167 90.8333,118.167 89.5,117.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 437.5,118.5 C 438.833,119.167 438.833,119.167 437.5,118.5 Z"/></g>
|
||||
<g><path style="opacity:0.992" fill="#72716a" d="M 216.5,118.5 C 216.167,120.833 214.833,122.167 212.5,122.5C 213.09,121.234 213.59,119.901 214,118.5C 214.77,119.598 215.603,119.598 216.5,118.5 Z"/></g>
|
||||
<g><path style="opacity:0.098" fill="#bfb8b7" d="M 339.5,117.5 C 340.906,117.973 341.573,118.973 341.5,120.5C 340.094,120.027 339.427,119.027 339.5,117.5 Z"/></g>
|
||||
<g><path style="opacity:0.508" fill="#7f7a74" d="M 203.5,121.5 C 206.43,122.299 209.43,122.632 212.5,122.5C 210.034,123.634 207.367,123.801 204.5,123C 203.944,122.617 203.611,122.117 203.5,121.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 408.5,124.5 C 409.833,125.167 409.833,125.167 408.5,124.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 424.5,133.5 C 425.833,134.167 425.833,134.167 424.5,133.5 Z"/></g>
|
||||
<g><path style="opacity:0.333" fill="#9e9894" d="M 344.5,127.5 C 345.954,130.718 346.621,134.218 346.5,138C 346.496,140.361 346.163,142.527 345.5,144.5C 345.553,138.804 345.22,133.138 344.5,127.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 140.5,135.5 C 141.833,136.167 141.833,136.167 140.5,135.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 53.5,137.5 C 54.8333,138.167 54.8333,138.167 53.5,137.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 353.5,140.5 C 354.833,141.167 354.833,141.167 353.5,140.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 493.5,141.5 C 494.833,142.167 494.833,142.167 493.5,141.5 Z"/></g>
|
||||
<g><path style="opacity:0.455" fill="#918f8b" d="M 243.5,143.5 C 242.135,145.794 240.135,147.461 237.5,148.5C 239.385,146.947 240.385,144.947 240.5,142.5C 241.791,142.263 242.791,142.596 243.5,143.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 437.5,153.5 C 438.833,154.167 438.833,154.167 437.5,153.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 438.5,183.5 C 439.833,184.167 439.833,184.167 438.5,183.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 446.5,183.5 C 447.833,184.167 447.833,184.167 446.5,183.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 123.5,185.5 C 124.833,186.167 124.833,186.167 123.5,185.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 129.5,186.5 C 130.833,187.167 130.833,187.167 129.5,186.5 Z"/></g>
|
||||
<g><path style="opacity:0.839" fill="#756a67" d="M 333.5,187.5 C 333.346,189.97 332.346,191.97 330.5,193.5C 330.455,190.923 331.455,188.923 333.5,187.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#262321" d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 26.5,198.5 C 27.8333,199.167 27.8333,199.167 26.5,198.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 413.5,204.5 C 414.833,205.167 414.833,205.167 413.5,204.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 74.5,209.5 C 75.8333,210.167 75.8333,210.167 74.5,209.5 Z"/></g>
|
||||
<g><path style="opacity:0.965" fill="#272422" d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z"/></g>
|
||||
<g><path style="opacity:0.129" fill="#b5b4af" d="M 206.5,184.5 C 207.906,184.973 208.573,185.973 208.5,187.5C 207.094,187.027 206.427,186.027 206.5,184.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#35312f" d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#171513" d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#413d38" d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z"/></g>
|
||||
<g><path style="opacity:0.098" fill="#cecbc4" d="M 177.5,212.5 C 181.151,211.835 184.985,211.501 189,211.5C 195.725,211.4 202.225,212.066 208.5,213.5C 198.183,212.774 187.85,212.44 177.5,212.5 Z"/></g>
|
||||
<g><path style="opacity:0.149" fill="#adaaa7" d="M 150.5,210.5 C 150.573,212.027 149.906,213.027 148.5,213.5C 148.427,211.973 149.094,210.973 150.5,210.5 Z"/></g>
|
||||
<g><path style="opacity:0.122" fill="#c4b9b8" d="M 217.5,211.5 C 217.5,212.167 217.5,212.833 217.5,213.5C 215.833,214.833 214.167,214.833 212.5,213.5C 214.554,213.635 216.221,212.968 217.5,211.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#181614" d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z"/></g>
|
||||
<g><path style="opacity:0.047" fill="#e0dfd7" d="M 198.5,219.5 C 198.5,219.833 198.5,220.167 198.5,220.5C 195.287,220.19 192.287,220.523 189.5,221.5C 188.957,221.44 188.624,221.107 188.5,220.5C 191.768,219.513 195.102,219.18 198.5,219.5 Z"/></g>
|
||||
<g><path style="opacity:0.592" fill="#7d7976" d="M 299.5,222.5 C 298.833,224.167 298.167,225.833 297.5,227.5C 296.833,227.5 296.167,227.5 295.5,227.5C 296.124,225.246 297.457,223.579 299.5,222.5 Z"/></g>
|
||||
<g><path style="opacity:0.592" fill="#94908e" d="M 189.5,221.5 C 190.377,223.728 191.71,225.728 193.5,227.5C 190.224,226.878 188.891,224.878 189.5,221.5 Z"/></g>
|
||||
<g><path style="opacity:0.247" fill="#837f7a" d="M 201.5,225.5 C 201.423,226.75 200.756,227.583 199.5,228C 197.288,228.789 195.288,228.622 193.5,227.5C 196.421,227.717 199.087,227.051 201.5,225.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 32.5,229.5 C 33.8333,230.167 33.8333,230.167 32.5,229.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#252421" d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 490.5,245.5 C 491.833,246.167 491.833,246.167 490.5,245.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 230.5,246.5 C 231.833,247.167 231.833,247.167 230.5,246.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 223.5,250.5 C 224.833,251.167 224.833,251.167 223.5,250.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 485.5,254.5 C 486.833,255.167 486.833,255.167 485.5,254.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 411.5,255.5 C 412.833,256.167 412.833,256.167 411.5,255.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 144.5,270.5 C 145.833,271.167 145.833,271.167 144.5,270.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#22201e" d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z"/></g>
|
||||
<g><path style="opacity:0.184" fill="#a6a29e" d="M 278.5,242.5 C 280.027,242.427 281.027,243.094 281.5,244.5C 279.973,244.573 278.973,243.906 278.5,242.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 257.5,237.5 C 258.833,238.167 258.833,238.167 257.5,237.5 Z"/></g>
|
||||
<g><path style="opacity:0.247" fill="#aca7a5" d="M 295.5,227.5 C 295.573,229.027 294.906,230.027 293.5,230.5C 293.427,228.973 294.094,227.973 295.5,227.5 Z"/></g>
|
||||
<g><path style="opacity:0.306" fill="#7f7772" d="M 244.5,228.5 C 246.167,228.5 247.833,228.5 249.5,228.5C 249.598,230.553 248.931,232.22 247.5,233.5C 247.33,232.178 247.663,231.011 248.5,230C 246.942,229.79 245.609,229.29 244.5,228.5 Z"/></g>
|
||||
<g><path style="opacity:0.114" fill="#bcb6b2" d="M 213.5,222.5 C 212.523,225.287 212.19,228.287 212.5,231.5C 211.833,231.5 211.5,231.167 211.5,230.5C 211.183,227.428 211.516,224.428 212.5,221.5C 213.107,221.624 213.44,221.957 213.5,222.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 202.5,272.5 C 203.833,273.167 203.833,273.167 202.5,272.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 32.5,280.5 C 33.8333,281.167 33.8333,281.167 32.5,280.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 255.5,283.5 C 256.833,284.167 256.833,284.167 255.5,283.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 239.5,290.5 C 240.833,291.167 240.833,291.167 239.5,290.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 110.5,295.5 C 111.833,296.167 111.833,296.167 110.5,295.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 405.5,295.5 C 406.833,296.167 406.833,296.167 405.5,295.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 330.5,302.5 C 331.833,303.167 331.833,303.167 330.5,302.5 Z"/></g>
|
||||
<g><path style="opacity:0.342" fill="#837e7a" d="M 172.5,220.5 C 172.5,220.167 172.5,219.833 172.5,219.5C 175.167,219.5 177.833,219.5 180.5,219.5C 180.5,273.833 180.5,328.167 180.5,382.5C 179.501,328.669 179.168,274.669 179.5,220.5C 177.167,220.5 174.833,220.5 172.5,220.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 394.5,307.5 C 395.833,308.167 395.833,308.167 394.5,307.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 406.5,308.5 C 407.833,309.167 407.833,309.167 406.5,308.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 63.5,320.5 C 64.8333,321.167 64.8333,321.167 63.5,320.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 105.5,321.5 C 106.833,322.167 106.833,322.167 105.5,321.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 400.5,323.5 C 401.833,324.167 401.833,324.167 400.5,323.5 Z"/></g>
|
||||
<g><path style="opacity:0.224" fill="#6b6662" d="M 200.5,235.5 C 198.735,236.461 196.735,236.795 194.5,236.5C 194.185,286.857 194.518,337.19 195.5,387.5C 194.732,386.737 194.232,385.737 194,384.5C 193.5,334.834 193.333,285.168 193.5,235.5C 195.833,235.5 198.167,235.5 200.5,235.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 492.5,372.5 C 493.833,373.167 493.833,373.167 492.5,372.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#706d68" d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z"/></g>
|
||||
<g><path style="opacity:0.471" fill="#89837d" d="M 262.5,374.5 C 260.321,375.926 257.821,376.592 255,376.5C 253.293,376.492 251.793,376.158 250.5,375.5C 254.534,375.495 258.534,375.162 262.5,374.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 308.5,385.5 C 309.833,386.167 309.833,386.167 308.5,385.5 Z"/></g>
|
||||
<g><path style="opacity:0.039" fill="#cdc9c7" d="M 308.5,397.5 C 308.573,399.027 307.906,400.027 306.5,400.5C 306.427,398.973 307.094,397.973 308.5,397.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 384.5,401.5 C 385.833,402.167 385.833,402.167 384.5,401.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 130.5,431.5 C 131.833,432.167 131.833,432.167 130.5,431.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 129.5,437.5 C 130.833,438.167 130.833,438.167 129.5,437.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 172.5,437.5 C 173.833,438.167 173.833,438.167 172.5,437.5 Z"/></g>
|
||||
<g><path style="opacity:0.998" fill="#1f1d1b" d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z"/></g>
|
||||
<g><path style="opacity:0.755" fill="#706a67" d="M 266.5,434.5 C 266.082,435.222 265.416,435.722 264.5,436C 258.984,436.817 253.65,436.651 248.5,435.5C 254.545,435.697 260.545,435.363 266.5,434.5 Z"/></g>
|
||||
<g><path style="opacity:0.165" fill="#a6a19f" d="M 276.5,445.5 C 275.22,446.931 273.553,447.598 271.5,447.5C 272.78,446.069 274.447,445.402 276.5,445.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 496.5,448.5 C 497.833,449.167 497.833,449.167 496.5,448.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 485.5,449.5 C 486.833,450.167 486.833,450.167 485.5,449.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 295.5,468.5 C 296.833,469.167 296.833,469.167 295.5,468.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 31.5,477.5 C 32.8333,478.167 32.8333,478.167 31.5,477.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 78.5,478.5 C 79.8333,479.167 79.8333,479.167 78.5,478.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 135.5,485.5 C 136.833,486.167 136.833,486.167 135.5,485.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 67.5,492.5 C 68.8333,493.167 68.8333,493.167 67.5,492.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 11.5,495.5 C 12.8333,496.167 12.8333,496.167 11.5,495.5 Z"/></g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 29 KiB |
@@ -0,0 +1,458 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs, Send, Puzzle } from 'lucide-react';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { UserMessage } from '@/components/UserMessage';
|
||||
import OpenAI from 'openai';
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { isEmptyMessage } from '@/lib/isEmptyMessage';
|
||||
import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
|
||||
// Type guard to check if message has reasoning content
|
||||
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
|
||||
return message.role === 'assistant' && 'reasoning_content' in message && typeof (message as { reasoning_content?: unknown }).reasoning_content === 'string';
|
||||
}
|
||||
|
||||
interface AIMessageItemProps {
|
||||
message: AIMessage;
|
||||
isCurrentlyLoading?: boolean;
|
||||
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
|
||||
}
|
||||
|
||||
export const AIMessageItem = memo(({
|
||||
message,
|
||||
isCurrentlyLoading = false,
|
||||
toolCall,
|
||||
}: AIMessageItemProps) => {
|
||||
const [isToolExpanded, setIsToolExpanded] = useState(false);
|
||||
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
|
||||
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
|
||||
const { displayTheme } = useTheme();
|
||||
|
||||
// Get content to display
|
||||
const getContent = () => {
|
||||
if (typeof message.content === 'string') {
|
||||
return message.content;
|
||||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
// Handle array content (like images, text blocks)
|
||||
return message.content
|
||||
.map(item => {
|
||||
if (typeof item === 'string') return item;
|
||||
if (item.type === 'text') return item.text;
|
||||
if (item.type === 'image_url') return `[Image: ${item.image_url.url}]`;
|
||||
return '[Unknown content]';
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
// Get tool info including icon and title
|
||||
const getToolInfo = () => {
|
||||
if (message.role === 'tool' && toolCall) {
|
||||
if (toolCall.type === 'function') {
|
||||
const toolName = toolCall.function.name;
|
||||
let args;
|
||||
|
||||
try {
|
||||
args = JSON.parse(toolCall.function.arguments);
|
||||
} catch {
|
||||
args = {};
|
||||
}
|
||||
|
||||
// Generate icons and titles based on tool name and arguments
|
||||
switch (toolName) {
|
||||
case 'shell':
|
||||
return {
|
||||
icon: Terminal,
|
||||
title: args.command ? args.command : 'Shell Command'
|
||||
};
|
||||
case 'text_editor_view': {
|
||||
const title = args.path
|
||||
? (args.start_line || args.end_line
|
||||
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
|
||||
: `Viewed ${args.path}`)
|
||||
: 'Viewed File';
|
||||
return { icon: Eye, title };
|
||||
}
|
||||
case 'text_editor_write':
|
||||
return {
|
||||
icon: FileText,
|
||||
title: args.path ? `Wrote ${args.path}` : 'Wrote File'
|
||||
};
|
||||
case 'text_editor_str_replace':
|
||||
return {
|
||||
icon: Edit,
|
||||
title: args.path ? `Edited ${args.path}` : 'Edited File'
|
||||
};
|
||||
case 'npm_add_package': {
|
||||
const installTitle = args.name
|
||||
? (args.dev ? `Installed ${args.name} (dev)` : `Installed ${args.name}`)
|
||||
: 'Installed Package';
|
||||
return { icon: Package, title: installTitle };
|
||||
}
|
||||
case 'npm_remove_package':
|
||||
return {
|
||||
icon: PackageMinus,
|
||||
title: args.name ? `Removed ${args.name}` : 'Removed Package'
|
||||
};
|
||||
case 'git_commit':
|
||||
return {
|
||||
icon: GitCommit,
|
||||
title: args.message ? `Committed: ${args.message}` : 'Committed Changes'
|
||||
};
|
||||
case 'build_project':
|
||||
return {
|
||||
icon: Package,
|
||||
title: 'Built Project'
|
||||
};
|
||||
case 'nostr_read_nip':
|
||||
return {
|
||||
icon: BookOpen,
|
||||
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP'
|
||||
};
|
||||
case 'nostr_fetch_event':
|
||||
return {
|
||||
icon: Download,
|
||||
title: args.identifier ? `Fetched ${args.identifier.slice(0, 16)}...` : 'Fetched Event'
|
||||
};
|
||||
case 'nostr_read_kind':
|
||||
return {
|
||||
icon: Hash,
|
||||
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind'
|
||||
};
|
||||
case 'nostr_read_tag':
|
||||
return {
|
||||
icon: Tag,
|
||||
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag'
|
||||
};
|
||||
case 'nostr_read_protocol':
|
||||
return {
|
||||
icon: Network,
|
||||
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol'
|
||||
};
|
||||
case 'nostr_read_nips_index':
|
||||
return {
|
||||
icon: List,
|
||||
title: 'Read NIPs Index'
|
||||
};
|
||||
case 'nostr_generate_kind':
|
||||
return {
|
||||
icon: Plus,
|
||||
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind'
|
||||
};
|
||||
case 'nostr_publish_events': {
|
||||
const eventCount = args.events?.length || 0;
|
||||
return {
|
||||
icon: Send,
|
||||
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event'
|
||||
};
|
||||
}
|
||||
case 'deploy_project':
|
||||
return {
|
||||
icon: Globe,
|
||||
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project'
|
||||
};
|
||||
case 'typecheck':
|
||||
return {
|
||||
icon: CheckCircle,
|
||||
title: 'TypeScript'
|
||||
};
|
||||
case 'read_console_messages':
|
||||
return {
|
||||
icon: Logs,
|
||||
title: 'Read Console'
|
||||
};
|
||||
case 'skill':
|
||||
return {
|
||||
icon: Puzzle,
|
||||
title: args.name ? `Skill: ${args.name}` : 'Skill'
|
||||
};
|
||||
default:
|
||||
return {
|
||||
icon: Wrench,
|
||||
title: toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to extracting from content
|
||||
if (message.role === 'tool') {
|
||||
const content = getContent();
|
||||
const lines = content.split('\n');
|
||||
const firstLine = lines[0];
|
||||
|
||||
if (firstLine && firstLine.length < 100) {
|
||||
return {
|
||||
icon: Wrench,
|
||||
title: firstLine.replace(/^(Error |Tool |Executing |Result: )/i, '').trim()
|
||||
};
|
||||
}
|
||||
|
||||
return { icon: Wrench, title: 'Tool Result' };
|
||||
}
|
||||
|
||||
return { icon: Wrench, title: 'Tool' };
|
||||
};
|
||||
|
||||
// Special rendering for tool messages
|
||||
if (message.role === 'tool') {
|
||||
const content = getContent();
|
||||
const toolInfo = getToolInfo();
|
||||
const IconComponent = toolInfo.icon;
|
||||
|
||||
// Get tool call arguments for special rendering
|
||||
let toolArgs: Record<string, unknown> = {};
|
||||
let toolName = '';
|
||||
if (toolCall?.type === 'function') {
|
||||
toolName = toolCall.function.name;
|
||||
try {
|
||||
toolArgs = JSON.parse(toolCall.function.arguments);
|
||||
} catch {
|
||||
toolArgs = {};
|
||||
}
|
||||
}
|
||||
|
||||
// Special rendering for tools
|
||||
const renderSpecialContent = () => {
|
||||
if (toolName === 'text_editor_write' && toolArgs.file_text) {
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{toolArgs.file_text as string}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (toolName === 'text_editor_str_replace' && toolArgs.old_str && toolArgs.new_str) {
|
||||
const oldLines = (toolArgs.old_str as string).split('\n');
|
||||
const newLines = (toolArgs.new_str as string).split('\n');
|
||||
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
|
||||
<div className="space-y-1">
|
||||
{/* Old content (removed) */}
|
||||
<div className="space-y-0">
|
||||
{oldLines.map((line, index) => (
|
||||
<div key={`old-${index}`} className="flex">
|
||||
<span className="text-red-500 select-none mr-2">-</span>
|
||||
<span className="bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-300 flex-1 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* New content (added) */}
|
||||
<div className="space-y-0">
|
||||
{newLines.map((line, index) => (
|
||||
<div key={`new-${index}`} className="flex">
|
||||
<span className="text-green-500 select-none mr-2">+</span>
|
||||
<span className="bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-300 flex-1 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Default rendering for other tools
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{content}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Regular tool message rendering
|
||||
return (
|
||||
<div className="-mt-2"> {/* -mt-2 to make it snug with the previous assistant message */}
|
||||
<button
|
||||
onClick={() => setIsToolExpanded(!isToolExpanded)}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-2 px-2 py-1 text-xs",
|
||||
"hover:bg-muted/30 rounded transition-colors duration-200"
|
||||
)}
|
||||
>
|
||||
<IconComponent className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
<span className="text-muted-foreground font-medium truncate flex-1 text-left">
|
||||
{toolInfo.title}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{isToolExpanded && renderSpecialContent()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Regular rendering for non-tool messages
|
||||
if (message.role === 'user') {
|
||||
// User messages: right-aligned bubble without avatar/name
|
||||
// Extract text and image parts from message content
|
||||
const contentArray = Array.isArray(message.content) ? message.content : null;
|
||||
const textParts = contentArray
|
||||
? contentArray.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
|
||||
: [];
|
||||
const userContent = typeof message.content === 'string'
|
||||
? message.content
|
||||
: textParts.length > 0
|
||||
? textParts.map(part => part.text).join('\n')
|
||||
: '';
|
||||
|
||||
// Extract image URLs from content array
|
||||
const imageUrls = contentArray
|
||||
? contentArray
|
||||
.filter(part => part.type === 'image_url')
|
||||
.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-end py-6">
|
||||
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
|
||||
<div className="text-sm break-words space-y-2">
|
||||
{/* Render text content and attachments first */}
|
||||
{userContent && <UserMessage content={userContent} />}
|
||||
{/* Render images after text and attachments */}
|
||||
{imageUrls.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{imageUrls.map((url, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="rounded-lg overflow-hidden border border-border cursor-pointer hover:opacity-90 transition-opacity"
|
||||
onClick={() => setExpandedImageUrl(url)}
|
||||
>
|
||||
<img
|
||||
src={url}
|
||||
alt={`User uploaded image ${index + 1}`}
|
||||
className="max-w-full h-auto max-h-96 object-contain"
|
||||
loading="lazy"
|
||||
onError={(e) => {
|
||||
// Fallback if image fails to load
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
const fallback = document.createElement('div');
|
||||
fallback.className = 'p-2 text-xs text-muted-foreground bg-muted rounded';
|
||||
fallback.textContent = `Image failed to load: ${url}`;
|
||||
target.parentElement?.appendChild(fallback);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image expansion dialog */}
|
||||
<Dialog open={!!expandedImageUrl} onOpenChange={(open) => !open && setExpandedImageUrl(null)}>
|
||||
<DialogPortal>
|
||||
<DialogOverlay className="bg-black/95" />
|
||||
<DialogPrimitive.Content
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 max-w-[95vw] max-h-[95vh] translate-x-[-50%] translate-y-[-50%] p-0 bg-transparent border-0 shadow-none",
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out",
|
||||
"data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
|
||||
)}
|
||||
onPointerDownOutside={() => setExpandedImageUrl(null)}
|
||||
onEscapeKeyDown={() => setExpandedImageUrl(null)}
|
||||
>
|
||||
{expandedImageUrl && (
|
||||
<div className="relative flex items-center justify-center">
|
||||
<img
|
||||
src={expandedImageUrl}
|
||||
alt="Expanded image"
|
||||
className="max-w-full max-h-[95vh] w-auto h-auto object-contain rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (message.role !== 'assistant') {
|
||||
return null; // Only render assistant and user messages
|
||||
}
|
||||
|
||||
// If the message is empty (no content or reasoning), render nothing
|
||||
if (isEmptyMessage({ ...message, tool_calls: [] })) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Assistant messages: left-aligned without avatar/name
|
||||
return (
|
||||
<div className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm space-y-3">
|
||||
{/* Reasoning content display */}
|
||||
{hasReasoningContent(message) && message.reasoning_content.trim() && (
|
||||
<div>
|
||||
<button
|
||||
onClick={() => setIsReasoningExpanded(!isReasoningExpanded)}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-2 px-2 py-1 text-xs",
|
||||
"hover:bg-muted/30 rounded transition-colors duration-200"
|
||||
)}
|
||||
>
|
||||
{!getContent().trim() && isCurrentlyLoading ? (
|
||||
<Loader2 className="h-3 w-3 text-muted-foreground flex-shrink-0 animate-spin" />
|
||||
) : (
|
||||
<Lightbulb className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
)}
|
||||
<span className="text-muted-foreground font-medium flex-1 text-left">
|
||||
Thinking
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{isReasoningExpanded && (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<Streamdown
|
||||
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
|
||||
parseIncompleteMarkdown={isCurrentlyLoading}
|
||||
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
|
||||
>
|
||||
{message.reasoning_content}
|
||||
</Streamdown>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main content display */}
|
||||
{getContent().trim() && (
|
||||
<div className="break-words">
|
||||
<Streamdown
|
||||
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
|
||||
parseIncompleteMarkdown={isCurrentlyLoading}
|
||||
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
|
||||
>
|
||||
{getContent()}
|
||||
</Streamdown>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tool calls are now hidden from assistant messages */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
AIMessageItem.displayName = 'AIMessageItem';
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import React from 'react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock localStorage
|
||||
const localStorageMock = {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
};
|
||||
|
||||
Object.defineProperty(window, 'localStorage', {
|
||||
value: localStorageMock,
|
||||
});
|
||||
|
||||
// Mock the config utils
|
||||
vi.mock('@/lib/configUtils', () => ({
|
||||
readAISettings: vi.fn(),
|
||||
writeAISettings: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('AISettingsProvider', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
localStorageMock.getItem.mockReturnValue(null);
|
||||
|
||||
// Mock the read function to return default settings
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue({
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should initialize with empty recentlyUsedModels array', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it('should add recently used models correctly', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
|
||||
});
|
||||
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([
|
||||
'openrouter/anthropic/claude-3.5-sonnet'
|
||||
]);
|
||||
});
|
||||
|
||||
it('should move existing model to front when used again', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
// Add multiple models
|
||||
act(() => {
|
||||
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
|
||||
result.current.addRecentlyUsedModel('openrouter/openai/gpt-4');
|
||||
result.current.addRecentlyUsedModel('openrouter/google/gemini-pro');
|
||||
});
|
||||
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([
|
||||
'openrouter/google/gemini-pro',
|
||||
'openrouter/openai/gpt-4',
|
||||
'openrouter/anthropic/claude-3.5-sonnet'
|
||||
]);
|
||||
|
||||
// Use the first model again - it should move to front
|
||||
act(() => {
|
||||
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
|
||||
});
|
||||
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([
|
||||
'openrouter/anthropic/claude-3.5-sonnet',
|
||||
'openrouter/google/gemini-pro',
|
||||
'openrouter/openai/gpt-4'
|
||||
]);
|
||||
});
|
||||
|
||||
it('should limit recently used models to 10 items', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
// Add 12 models
|
||||
act(() => {
|
||||
for (let i = 1; i <= 12; i++) {
|
||||
result.current.addRecentlyUsedModel(`provider/model-${i}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Should only keep the last 10
|
||||
expect(result.current.settings.recentlyUsedModels).toHaveLength(10);
|
||||
expect(result.current.settings.recentlyUsedModels[0]).toBe('provider/model-12');
|
||||
expect(result.current.settings.recentlyUsedModels[9]).toBe('provider/model-3');
|
||||
});
|
||||
|
||||
it('should migrate old settings without recentlyUsedModels', async () => {
|
||||
const oldSettings = {
|
||||
providers: [
|
||||
{
|
||||
id: 'openrouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
],
|
||||
recentlyUsedModels: []
|
||||
};
|
||||
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue(oldSettings);
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
expect(result.current.settings.providers).toEqual(oldSettings.providers);
|
||||
});
|
||||
});
|
||||
|
||||
it('should invalidate provider-models query when updateSettings is called with providers', async () => {
|
||||
// Mock the QueryClient.invalidateQueries method
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
// Create a custom TestApp that mocks the query client
|
||||
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
|
||||
const queryClient = useQueryClient();
|
||||
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => (
|
||||
<TestApp>
|
||||
<MockedTestApp>{children}</MockedTestApp>
|
||||
</TestApp>
|
||||
),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.updateSettings({
|
||||
providers: [
|
||||
{
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-models'] });
|
||||
});
|
||||
});
|
||||
@@ -1,44 +1,166 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { AISettingsContext, type AISettings, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||
|
||||
interface AISettingsProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: AISettings = {
|
||||
apiKey: '',
|
||||
baseUrl: 'https://openrouter.ai/api/v1',
|
||||
model: 'anthropic/claude-sonnet-4',
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'ai-settings';
|
||||
|
||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
const [settings, setSettings] = useState<AISettings>(() => {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored) {
|
||||
try {
|
||||
return { ...DEFAULT_SETTINGS, ...JSON.parse(stored) };
|
||||
} catch {
|
||||
return DEFAULT_SETTINGS;
|
||||
}
|
||||
}
|
||||
return DEFAULT_SETTINGS;
|
||||
});
|
||||
const queryClient = useQueryClient();
|
||||
const { fs } = useFS();
|
||||
const { configPath } = useFSPaths();
|
||||
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// Initialize settings from VFS on mount
|
||||
useEffect(() => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
|
||||
}, [settings]);
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readAISettings(fs, configPath);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize AI settings:', error);
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
};
|
||||
|
||||
initializeSettings();
|
||||
}, [fs, configPath]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeAISettings(fs, settings, configPath);
|
||||
} catch (error) {
|
||||
console.error('Failed to save AI settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized, configPath]);
|
||||
|
||||
const updateSettings = (newSettings: Partial<AISettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
|
||||
// If providers are being updated, invalidate the provider-models query
|
||||
if ('providers' in newSettings) {
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
}
|
||||
};
|
||||
|
||||
const isConfigured = Boolean(settings.apiKey);
|
||||
const setProvider = (provider: AIProvider) => {
|
||||
setSettings(prev => {
|
||||
const existingIndex = prev.providers.findIndex(p => p.id === provider.id);
|
||||
if (existingIndex >= 0) {
|
||||
// Update existing provider
|
||||
return {
|
||||
...prev,
|
||||
providers: prev.providers.map(p =>
|
||||
p.id === provider.id ? provider : p
|
||||
),
|
||||
};
|
||||
} else {
|
||||
// Add new provider
|
||||
return {
|
||||
...prev,
|
||||
providers: [...prev.providers, provider],
|
||||
};
|
||||
}
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
};
|
||||
|
||||
const removeProvider = (id: string) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers: prev.providers.filter(provider => provider.id !== id),
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
};
|
||||
|
||||
const setProviders = (providers: AIProvider[]) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers,
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
|
||||
};
|
||||
|
||||
const addRecentlyUsedModel = (modelId: string) => {
|
||||
setSettings(prev => {
|
||||
const existingIndex = prev.recentlyUsedModels.indexOf(modelId);
|
||||
if (existingIndex === 0) {
|
||||
return prev;
|
||||
} else if (existingIndex === -1) {
|
||||
// Add new model to front, keep only last 10
|
||||
return {
|
||||
...prev,
|
||||
recentlyUsedModels: [modelId, ...prev.recentlyUsedModels].slice(0, 10),
|
||||
}
|
||||
} else {
|
||||
// Move existing model to front
|
||||
return {
|
||||
...prev,
|
||||
recentlyUsedModels: [
|
||||
modelId,
|
||||
...prev.recentlyUsedModels.filter((_, index) => index !== existingIndex)
|
||||
]
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const setMCPServer = (name: string, server: MCPServer) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
mcpServers: {
|
||||
...(prev.mcpServers || {}),
|
||||
[name]: server,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const removeMCPServer = (name: string) => {
|
||||
setSettings(prev => {
|
||||
const newMCPServers = { ...(prev.mcpServers || {}) };
|
||||
delete newMCPServers[name];
|
||||
return {
|
||||
...prev,
|
||||
mcpServers: newMCPServers,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const isConfigured = settings.providers.length > 0;
|
||||
|
||||
const contextValue: AISettingsContextType = {
|
||||
settings,
|
||||
updateSettings,
|
||||
setProvider,
|
||||
removeProvider,
|
||||
setProviders,
|
||||
addRecentlyUsedModel,
|
||||
setMCPServer,
|
||||
removeMCPServer,
|
||||
isConfigured,
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ArrowRight, ArrowLeft, Download, Upload, ExternalLink, Sparkles } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { getShakespeareProvider } from '@/lib/aiProviderPresets';
|
||||
|
||||
interface Act1DialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
|
||||
|
||||
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
const [step, setStep] = useState<DialogStep>('welcome');
|
||||
const { data: creditsData } = useAICredits(getShakespeareProvider());
|
||||
|
||||
const handleGetStarted = async () => {
|
||||
try {
|
||||
setStep('migration');
|
||||
} catch (error) {
|
||||
console.error('Failed to configure Shakespeare provider:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleContinue = () => {
|
||||
setStep('credits');
|
||||
};
|
||||
|
||||
const handleCreditsNext = () => {
|
||||
setStep('conclusion');
|
||||
};
|
||||
|
||||
const handleFinish = () => {
|
||||
// Mark that the user is a previous Act 1 user
|
||||
localStorage.setItem('act1', 'true');
|
||||
// Remove the selectedNSPAddr from localStorage
|
||||
localStorage.removeItem('selectedNSPAddr');
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleVisitAct1 = () => {
|
||||
window.open('https://act1.shakespeare.diy', '_blank');
|
||||
};
|
||||
|
||||
// Reset state when dialog opens/closes
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setStep('welcome');
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{step === 'migration' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('welcome')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'credits' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('migration')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'conclusion' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('credits')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="overflow-y-auto max-h-[calc(90vh-120px)] pr-2">
|
||||
<div className="space-y-6 py-4">
|
||||
{step === 'welcome' && (
|
||||
<div className="text-center space-y-6">
|
||||
<div className="text-6xl mb-4">🎭✨</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Welcome to Act 2!
|
||||
</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-lg mx-auto">
|
||||
We're excited to see you again! Shakespeare has been completely rebuilt
|
||||
with new features, improved performance, and a better development experience.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-lg mx-auto text-left">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<span className="text-2xl">🔄</span>
|
||||
What's Changed
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<Badge variant="secondary" className="mt-0.5">New</Badge>
|
||||
<div>
|
||||
<p className="font-medium">Use any AI Provider</p>
|
||||
<p className="text-sm text-muted-foreground">Your browser connects to AI providers directly</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<Badge variant="secondary" className="mt-0.5">New</Badge>
|
||||
<div>
|
||||
<p className="font-medium">Git Integration</p>
|
||||
<p className="text-sm text-muted-foreground">Push to GitHub, Nostr relays, and more</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<Badge variant="secondary" className="mt-0.5">New</Badge>
|
||||
<div>
|
||||
<p className="font-medium">Your Files</p>
|
||||
<p className="text-sm text-muted-foreground">Files are stored on your device directly in your browser</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 max-w-lg mx-auto">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="text-amber-600 dark:text-amber-400 text-lg">⚠️</span>
|
||||
<div className="text-left">
|
||||
<p className="font-medium text-amber-800 dark:text-amber-200">Act 2 is in Development</p>
|
||||
<p className="text-sm text-amber-700 dark:text-amber-300">
|
||||
While we're working hard to make Act 2 stable, you may encounter bugs.
|
||||
Your Act 1 projects remain safe and accessible.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleGetStarted}
|
||||
size="lg"
|
||||
className="gap-2"
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'migration' && (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center space-y-3">
|
||||
<h2 className="text-xl font-bold">Your Act 1 Projects & Credits</h2>
|
||||
<p className="text-muted-foreground max-w-lg mx-auto">
|
||||
All your Act 1 projects and credits are safe and still accessible.
|
||||
Here's how to work with them in Act 2.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleVisitAct1}
|
||||
className="gap-2"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
Visit Act 1
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Download className="h-5 w-5 text-green-500" />
|
||||
Export from Act 1
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
In Act 1, you can export your projects as ZIP files using the project menu.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Upload className="h-5 w-5 text-purple-500" />
|
||||
Import to Act 2
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
In Act 2, use the "Import Project" option in the sidebar to upload your exported ZIP files.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
className="gap-2"
|
||||
>
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'credits' && (
|
||||
<div className="text-center space-y-6">
|
||||
<div className="text-6xl mb-4">💳</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">Your Credits</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-md mx-auto">
|
||||
Your Act 1 credits are still available through the Shakespeare AI provider.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-md mx-auto">
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
|
||||
${(creditsData?.amount ?? 0).toFixed(2)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Available credits
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
|
||||
<p className="text-sm text-green-800 dark:text-green-200">
|
||||
✅ You're all set! We've configured the premium Shakespeare model for you.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-end pt-4">
|
||||
<Button
|
||||
onClick={handleCreditsNext}
|
||||
className="gap-2"
|
||||
>
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'conclusion' && (
|
||||
<div className="text-center space-y-6">
|
||||
<div className="text-5xl mb-4">🎉</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">Welcome to the Future!</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-md mx-auto">
|
||||
You're all up to speed with Act 2! Get ready to build amazing Nostr applications.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button onClick={handleFinish} size="lg" className="gap-2">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Start Building in Act 2
|
||||
</Button>
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Remember: You can always access Act 1 at{' '}
|
||||
<button
|
||||
onClick={handleVisitAct1}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
act1.shakespeare.diy
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
GitBranch,
|
||||
MoreHorizontal,
|
||||
MessageSquarePlus,
|
||||
History,
|
||||
Folder,
|
||||
Rocket,
|
||||
} from 'lucide-react';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
|
||||
interface ActionsMenuProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
onNewChat: () => void;
|
||||
onProjectDetails?: () => void;
|
||||
isLoading?: boolean;
|
||||
isBuildLoading?: boolean;
|
||||
disabled?: boolean;
|
||||
onFirstInteraction?: () => void;
|
||||
}
|
||||
|
||||
export function ActionsMenu({
|
||||
projectId,
|
||||
projectName,
|
||||
onNewChat,
|
||||
onProjectDetails,
|
||||
isLoading = false,
|
||||
isBuildLoading = false,
|
||||
disabled = false,
|
||||
onFirstInteraction: _onFirstInteraction,
|
||||
}: ActionsMenuProps) {
|
||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||
const [gitDialogOpen, setGitDialogOpen] = useState(false);
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
|
||||
const isAnyLoading = isLoading || isBuildLoading;
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
disabled={disabled}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
<span className="sr-only">Open menu</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={onNewChat}
|
||||
disabled={isLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<MessageSquarePlus className="h-4 w-4" />
|
||||
New Chat
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitHistoryOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<History className="h-4 w-4" />
|
||||
Rollback
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Repository
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setDeployDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Rocket className="h-4 w-4" />
|
||||
Deploy
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onProjectDetails}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Folder className="h-4 w-4" />
|
||||
Project Details
|
||||
</DropdownMenuItem>
|
||||
|
||||
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Dialogs */}
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={gitDialogOpen}
|
||||
onOpenChange={setGitDialogOpen}
|
||||
/>
|
||||
|
||||
<GitHistoryDialog
|
||||
projectId={projectId}
|
||||
open={gitHistoryOpen}
|
||||
onOpenChange={setGitHistoryOpen}
|
||||
/>
|
||||
|
||||
<DeployDialog
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
open={deployDialogOpen}
|
||||
onOpenChange={setDeployDialogOpen}
|
||||
/>
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { AddProviderDialog } from './AddProviderDialog';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
describe('AddProviderDialog', () => {
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'sk-test-key-123',
|
||||
};
|
||||
|
||||
it('renders new provider dialog', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Provider name is used as the heading (fallback to id since it's not in presets)
|
||||
expect(screen.getByRole('heading', { name: 'test-provider' })).toBeInTheDocument();
|
||||
expect(screen.getByText(/Add test-provider to your configuration/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows add provider button for new provider', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// No cancel button, only add provider button
|
||||
expect(screen.queryByRole('button', { name: /cancel/i })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /add provider/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onOpenChange when add provider is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const addButton = screen.getByRole('button', { name: /add provider/i });
|
||||
await user.click(addButton);
|
||||
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('does not display provider details for new provider', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Provider details (API key, base URL, etc.) are not displayed for new providers
|
||||
expect(screen.queryByText('••••••••')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('sk-test-key-123')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('https://api.test.com/v1')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays provider name from presets when available', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
// Use a provider that exists in presets
|
||||
const openrouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'sk-test-123',
|
||||
};
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={openrouterProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show the preset name "OpenRouter" instead of the id
|
||||
expect(screen.getByText(/Add OpenRouter to your configuration/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses provider id as fallback name when not in presets', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
const customProvider: AIProvider = {
|
||||
id: 'my-custom-provider',
|
||||
baseURL: 'https://api.custom.com/v1',
|
||||
};
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={customProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should use the id as the name since it's not in presets
|
||||
expect(screen.getByText(/Add my-custom-provider to your configuration/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Check, Sparkles, ArrowRight, AlertCircle, ExternalLink } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface AddProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
provider: AIProvider;
|
||||
}
|
||||
|
||||
export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderDialogProps) {
|
||||
const scrollableContentRef = useRef<HTMLDivElement>(null);
|
||||
const [agreedToTerms, setAgreedToTerms] = useState(false);
|
||||
|
||||
const { settings, setProvider } = useAISettings();
|
||||
|
||||
// Check if provider already exists and if it's identical
|
||||
const existingProvider = settings.providers.find(p => p.id === provider.id);
|
||||
const isIdentical = existingProvider &&
|
||||
existingProvider.baseURL === provider.baseURL &&
|
||||
existingProvider.apiKey === provider.apiKey &&
|
||||
existingProvider.nostr === provider.nostr &&
|
||||
existingProvider.proxy === provider.proxy;
|
||||
|
||||
// Get provider preset if available
|
||||
const preset = AI_PROVIDER_PRESETS.find(
|
||||
p => p.id === provider.id && p.baseURL === provider.baseURL
|
||||
);
|
||||
const providerName = preset?.name || provider.id;
|
||||
|
||||
const handleAddProvider = () => {
|
||||
setProvider(provider);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
// Reset agreed to terms when dialog opens or provider changes
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setAgreedToTerms(false);
|
||||
if (scrollableContentRef.current) {
|
||||
scrollableContentRef.current.scrollTop = 0;
|
||||
}
|
||||
}
|
||||
}, [open, provider.id]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl h-dvh-safe sm:h-auto sm:max-h-[90vh] flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<span className="text-xl">Add Provider</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0">
|
||||
<div className="space-y-6 py-4">
|
||||
{isIdentical ? (
|
||||
// Provider already exists with identical configuration
|
||||
<div className="text-center space-y-6">
|
||||
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<Check className="h-8 w-8 text-primary" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-2xl font-bold">Already Configured</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
You already have {providerName} configured with the same settings.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => onOpenChange(false)} className="gap-2">
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
) : existingProvider ? (
|
||||
// Provider exists but with different configuration
|
||||
<div className="space-y-6">
|
||||
<div className="mx-auto w-16 h-16 rounded-full bg-yellow-500/10 flex items-center justify-center">
|
||||
<AlertCircle className="h-8 w-8 text-yellow-500" />
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<h2 className="text-2xl font-bold">Provider Already Exists</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
A provider with this ID already exists but with different settings. Would you like to overwrite it?
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-2xl mx-auto">
|
||||
<div className="space-y-2 p-4 rounded-lg border">
|
||||
<h3 className="font-semibold text-sm">Current Settings</h3>
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
<div>
|
||||
<span className="font-medium">Base URL:</span>
|
||||
<div className="font-mono break-all">{existingProvider.baseURL}</div>
|
||||
</div>
|
||||
{existingProvider.apiKey && (
|
||||
<div>
|
||||
<span className="font-medium">API Key:</span>
|
||||
<div className="font-mono">••••••••</div>
|
||||
</div>
|
||||
)}
|
||||
{existingProvider.nostr && (
|
||||
<div>
|
||||
<span className="font-medium">Nostr Auth:</span> Enabled
|
||||
</div>
|
||||
)}
|
||||
{existingProvider.proxy && (
|
||||
<div>
|
||||
<span className="font-medium">Proxy:</span> Enabled
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 p-4 rounded-lg border border-primary">
|
||||
<h3 className="font-semibold text-sm">New Settings</h3>
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
<div>
|
||||
<span className="font-medium">Base URL:</span>
|
||||
<div className="font-mono break-all">{provider.baseURL}</div>
|
||||
</div>
|
||||
{provider.apiKey && (
|
||||
<div>
|
||||
<span className="font-medium">API Key:</span>
|
||||
<div className="font-mono">••••••••</div>
|
||||
</div>
|
||||
)}
|
||||
{provider.nostr && (
|
||||
<div>
|
||||
<span className="font-medium">Nostr Auth:</span> Enabled
|
||||
</div>
|
||||
)}
|
||||
{provider.proxy && (
|
||||
<div>
|
||||
<span className="font-medium">Proxy:</span> Enabled
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center gap-3">
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleAddProvider} className="gap-2">
|
||||
Overwrite Provider
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
// New provider
|
||||
<div className="space-y-6">
|
||||
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<Sparkles className="h-8 w-8 text-primary" />
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<h2 className="text-2xl font-bold">{providerName}</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
Add {providerName} to your configuration?
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Terms of Service Agreement */}
|
||||
{preset?.tosURL && (
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Checkbox
|
||||
id="agree-provider-terms"
|
||||
checked={agreedToTerms}
|
||||
onCheckedChange={(checked) => setAgreedToTerms(checked === true)}
|
||||
/>
|
||||
<label
|
||||
htmlFor="agree-provider-terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
I agree to {providerName}'s{' '}
|
||||
<a
|
||||
href={preset.tosURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary underline hover:no-underline inline-flex items-center gap-1"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
Terms of Service
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleAddProvider}
|
||||
disabled={preset?.tosURL ? !agreedToTerms : false}
|
||||
>
|
||||
Add Provider
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Menu } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
|
||||
interface AppLayoutProps {
|
||||
children: React.ReactNode;
|
||||
selectedProject?: Project | null;
|
||||
title?: string;
|
||||
showSidebar?: boolean;
|
||||
headerContent?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function AppLayout({
|
||||
children,
|
||||
selectedProject = null,
|
||||
showSidebar = true,
|
||||
headerContent
|
||||
}: AppLayoutProps) {
|
||||
const [_projects, setProjects] = useState<Project[]>([]);
|
||||
const projectsManager = useProjectsManager();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
|
||||
|
||||
// Track if we've set the initial state based on projects
|
||||
const [hasSetInitialState, setHasSetInitialState] = useState(false);
|
||||
|
||||
const loadProjects = useCallback(async () => {
|
||||
try {
|
||||
await projectsManager.init();
|
||||
const projectList = await projectsManager.getProjects();
|
||||
setProjects(projectList);
|
||||
|
||||
// Set initial sidebar state based on projects and device type
|
||||
if (!hasSetInitialState && !isMobile) {
|
||||
// On desktop, show sidebar if there are projects
|
||||
setIsSidebarVisible(projectList.length > 0);
|
||||
setHasSetInitialState(true);
|
||||
} else if (!hasSetInitialState && isMobile) {
|
||||
// On mobile, always start hidden
|
||||
setIsSidebarVisible(false);
|
||||
setHasSetInitialState(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
if (!hasSetInitialState) {
|
||||
setHasSetInitialState(true);
|
||||
}
|
||||
}
|
||||
}, [projectsManager, hasSetInitialState, isMobile]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProjects();
|
||||
}, [loadProjects]);
|
||||
|
||||
const handleProjectSelect = (project: Project | null) => {
|
||||
if (project) {
|
||||
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
|
||||
navigate(`/project/${project.id}`);
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
};
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5">
|
||||
{/* Mobile Header */}
|
||||
<header className="bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur pt-safe">
|
||||
<div className="h-12 px-4 py-3 flex items-center justify-between border-b">
|
||||
<div className="flex items-center space-x-2">
|
||||
{showSidebar && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{headerContent}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */}
|
||||
{showSidebar && isSidebarVisible && (
|
||||
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
|
||||
{/* Backdrop - only covers the area not occupied by the sidebar */}
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
onClick={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
{/* Sidebar - positioned above the backdrop */}
|
||||
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={(project) => {
|
||||
setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation
|
||||
handleProjectSelect(project);
|
||||
}}
|
||||
onClose={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="container mx-auto px-4 py-6 md:py-8">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex bg-background">
|
||||
{/* Fixed Sidebar - show if showSidebar is true and sidebar is visible */}
|
||||
{showSidebar && isSidebarVisible && (
|
||||
<div className="w-80 border-r bg-sidebar transition-all duration-300">
|
||||
<ProjectSidebar
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={handleProjectSelect}
|
||||
className="h-screen sticky top-0"
|
||||
onToggleSidebar={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 flex flex-col bg-background">
|
||||
<div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5 relative">
|
||||
{/* Show open button when sidebar is collapsed */}
|
||||
{showSidebar && !isSidebarVisible && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(true)}
|
||||
className="absolute top-2 left-4 h-8 w-8 p-0 z-10 bg-transparent backdrop-blur-sm hover:bg-transparent text-foreground/70 hover:text-foreground"
|
||||
aria-label="Open sidebar"
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="container mx-auto px-4 py-6 md:py-8">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { ReactNode, useEffect } from 'react';
|
||||
import { z } from 'zod';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
|
||||
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
|
||||
import i18n from '@/lib/i18n';
|
||||
|
||||
interface AppProviderProps {
|
||||
children: ReactNode;
|
||||
@@ -9,51 +10,87 @@ interface AppProviderProps {
|
||||
storageKey: string;
|
||||
/** Default app configuration */
|
||||
defaultConfig: AppConfig;
|
||||
/** Optional list of preset relays to display in the RelaySelector */
|
||||
presetRelays?: { name: string; url: string }[];
|
||||
}
|
||||
|
||||
// Zod schema for RelayMetadata
|
||||
const RelayMetadataSchema = z.object({
|
||||
relays: z.array(z.object({
|
||||
url: z.string().url(),
|
||||
read: z.boolean(),
|
||||
write: z.boolean(),
|
||||
})),
|
||||
updatedAt: z.number(),
|
||||
}) satisfies z.ZodType<RelayMetadata>;
|
||||
|
||||
// Zod schema for AppConfig validation
|
||||
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
|
||||
const AppConfigSchema = z.object({
|
||||
theme: z.enum(['dark', 'light', 'system']),
|
||||
relayUrl: z.string().url(),
|
||||
});
|
||||
relayMetadata: RelayMetadataSchema,
|
||||
projectTemplate: z.string().url(),
|
||||
esmUrl: z.string().url(),
|
||||
corsProxy: z.string().url(),
|
||||
faviconUrl: z.string().url(),
|
||||
previewDomain: z.string().min(1),
|
||||
language: z.string(),
|
||||
showcaseEnabled: z.boolean(),
|
||||
showcaseModerator: z.string(),
|
||||
ngitServers: z.array(z.string()),
|
||||
fsPathProjects: z.string().min(1),
|
||||
fsPathConfig: z.string().min(1),
|
||||
fsPathTmp: z.string().min(1),
|
||||
fsPathPlugins: z.string().min(1),
|
||||
fsPathTemplates: z.string().min(1),
|
||||
sentryDsn: z.string(),
|
||||
sentryEnabled: z.boolean(),
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
const {
|
||||
children,
|
||||
storageKey,
|
||||
defaultConfig,
|
||||
presetRelays,
|
||||
} = props;
|
||||
|
||||
// App configuration state with localStorage persistence
|
||||
const [config, setConfig] = useLocalStorage<AppConfig>(
|
||||
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
|
||||
storageKey,
|
||||
defaultConfig,
|
||||
{},
|
||||
{
|
||||
serialize: JSON.stringify,
|
||||
deserialize: (value: string) => {
|
||||
const parsed = JSON.parse(value);
|
||||
return AppConfigSchema.parse(parsed);
|
||||
return AppConfigSchema.partial().parse(parsed);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Generic config updater with callback pattern
|
||||
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
|
||||
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
|
||||
setConfig(updater);
|
||||
};
|
||||
|
||||
// Merge default config with stored config
|
||||
const config = { ...defaultConfig, ...rawConfig };
|
||||
|
||||
// Expand filesystem paths
|
||||
config.fsPathConfig = expandPath(config.fsPathConfig);
|
||||
config.fsPathProjects = expandPath(config.fsPathProjects);
|
||||
config.fsPathTmp = expandPath(config.fsPathTmp);
|
||||
config.fsPathPlugins = expandPath(config.fsPathPlugins);
|
||||
config.fsPathTemplates = expandPath(config.fsPathTemplates);
|
||||
|
||||
const appContextValue: AppContextType = {
|
||||
config,
|
||||
defaultConfig,
|
||||
updateConfig,
|
||||
presetRelays,
|
||||
};
|
||||
|
||||
// Apply theme effects to document
|
||||
useApplyTheme(config.theme);
|
||||
|
||||
// Apply language effects to i18n
|
||||
useApplyLanguage(config.language);
|
||||
|
||||
return (
|
||||
<AppContext.Provider value={appContextValue}>
|
||||
{children}
|
||||
@@ -88,11 +125,11 @@ function useApplyTheme(theme: Theme) {
|
||||
if (theme !== 'system') return;
|
||||
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
|
||||
|
||||
const handleChange = () => {
|
||||
const root = window.document.documentElement;
|
||||
root.classList.remove('light', 'dark');
|
||||
|
||||
|
||||
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
|
||||
root.classList.add(systemTheme);
|
||||
};
|
||||
@@ -100,4 +137,27 @@ function useApplyTheme(theme: Theme) {
|
||||
mediaQuery.addEventListener('change', handleChange);
|
||||
return () => mediaQuery.removeEventListener('change', handleChange);
|
||||
}, [theme]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to apply language changes to i18n
|
||||
*/
|
||||
function useApplyLanguage(language?: string): void {
|
||||
useEffect(() => {
|
||||
i18n.changeLanguage(language ?? navigator.language);
|
||||
}, [language]);
|
||||
}
|
||||
|
||||
/** Expand FS paths with the user's home directory, if available. */
|
||||
function expandPath(path: string): string {
|
||||
const homedir = window.electron?.homedir;
|
||||
if (!homedir) {
|
||||
return path;
|
||||
} else if (path.startsWith('~/')) {
|
||||
return homedir + path.slice(1);
|
||||
} else if (path === '~') {
|
||||
return homedir;
|
||||
} else {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import React, { useState, useMemo } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useAppSubmissions } from "@/hooks/useAppSubmissions";
|
||||
import { AppShowcaseCard } from "@/components/AppShowcaseCard";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "@/components/ui/collapsible";
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { shuffleArray } from "@/lib/utils";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Settings } from 'lucide-react';
|
||||
|
||||
export function AppShowcase() {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const { data: submissions = [], isLoading } = useAppSubmissions();
|
||||
const [showAllApps, setShowAllApps] = useState(false);
|
||||
|
||||
// Get moderator hex from config
|
||||
const MODERATOR_HEX = useMemo(() => {
|
||||
try {
|
||||
const decoded = nip19.decode(config.showcaseModerator);
|
||||
return decoded.type === 'npub' ? decoded.data : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}, [config.showcaseModerator]);
|
||||
const isModerator = user?.pubkey === MODERATOR_HEX;
|
||||
|
||||
// Filter and shuffle submissions - memoized with stable dependency
|
||||
const { templateApps, featuredApps, approvedApps } = useMemo(() => {
|
||||
// Filter visible submissions
|
||||
const visibleSubmissions = submissions.filter(app => !app.isHidden);
|
||||
|
||||
// Separate template apps from other apps
|
||||
const templates = shuffleArray(visibleSubmissions.filter(app => app.appTags.includes('Template')));
|
||||
const nonTemplateSubmissions = visibleSubmissions.filter(app => !app.appTags.includes('Template'));
|
||||
|
||||
// Shuffle featured and approved apps for random display order
|
||||
const featured = shuffleArray(nonTemplateSubmissions.filter(app => app.isFeatured));
|
||||
const approved = shuffleArray(nonTemplateSubmissions.filter(app => app.isApproved && !app.isFeatured));
|
||||
|
||||
return {
|
||||
templateApps: templates,
|
||||
featuredApps: featured,
|
||||
approvedApps: approved,
|
||||
};
|
||||
}, [submissions]); // Only depend on submissions, not intermediate filtered arrays
|
||||
|
||||
// Don't show showcase if disabled in settings
|
||||
if (!config.showcaseEnabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Don't show showcase if no apps exist
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="mt-16 max-w-7xl mx-auto">
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i} className="h-full flex flex-col">
|
||||
<Skeleton className="aspect-video rounded-t-lg" />
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<Skeleton className="w-12 h-12 rounded-lg" />
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
<Skeleton className="h-3 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
<div className="flex gap-1 mb-4">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<div className="mt-auto flex gap-2">
|
||||
<Skeleton className="h-6 flex-1" />
|
||||
<Skeleton className="h-8 w-8" />
|
||||
<Skeleton className="h-8 w-8" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!submissions.length) {
|
||||
return (
|
||||
<div className="mt-16 max-w-7xl mx-auto">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
{t('noAppsFound')}
|
||||
</p>
|
||||
<Button asChild variant="outline" className="w-full">
|
||||
<Link to="/settings/nostr">
|
||||
<Settings className="h-4 w-4 mr-2" />
|
||||
{t('relayConfiguration')}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-16 max-w-7xl mx-auto">
|
||||
{/* Apps Grid */}
|
||||
<div className="space-y-12">
|
||||
{/* Featured Apps */}
|
||||
{featuredApps.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-start gap-3 mb-6">
|
||||
<div className="flex-none w-8 h-8 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center">
|
||||
<span className="text-sm">⭐</span>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-foreground">{t('featuredApps')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('featuredAppsDescription')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{featuredApps.slice(0, 6).map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
showModerationControls={isModerator}
|
||||
hideApprovalStatus={true}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Templates Section */}
|
||||
{templateApps.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-start gap-3 mb-6">
|
||||
<div className="flex-none w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
|
||||
<span className="text-sm">📋</span>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-foreground">{t('templates')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('templatesDescription')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{templateApps.slice(0, 6).map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
showModerationControls={isModerator}
|
||||
hideApprovalStatus={true}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* More Apps (Approved) - Collapsible */}
|
||||
{approvedApps.length > 0 && (
|
||||
<div>
|
||||
<Collapsible open={showAllApps} onOpenChange={setShowAllApps}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" className="p-0 h-auto mb-6 hover:bg-transparent">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-none w-8 h-8 bg-blue-100 dark:bg-blue-900/50 rounded-lg flex items-center justify-center">
|
||||
<span className="text-sm">📱</span>
|
||||
</div>
|
||||
<div className="text-left">
|
||||
<h3 className="text-xl font-bold text-foreground">
|
||||
{t('moreAppsCount', { count: approvedApps.length })}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{showAllApps ? t('clickToCollapse') : t('clickToViewMore')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{approvedApps.map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
showModerationControls={isModerator}
|
||||
hideApprovalStatus={true}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import {
|
||||
ExternalLink,
|
||||
Edit,
|
||||
Star,
|
||||
StarOff,
|
||||
Eye,
|
||||
EyeOff,
|
||||
MoreVertical,
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
User,
|
||||
Home,
|
||||
Contact
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import type { AppSubmission } from '@/hooks/useAppSubmissions';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
interface AppShowcaseCardProps {
|
||||
app: AppSubmission;
|
||||
onEdit?: (app: AppSubmission) => void;
|
||||
showModerationControls?: boolean;
|
||||
hideApprovalStatus?: boolean; // Hide pending/approval badges
|
||||
}
|
||||
|
||||
export function AppShowcaseCard({ app, onEdit, showModerationControls, hideApprovalStatus: _hideApprovalStatus }: AppShowcaseCardProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { mutate: publishEvent, isPending } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
// Get author pubkey from authorNpub field
|
||||
const authorPubkey = React.useMemo(() => {
|
||||
if (!app.authorNpub) return app.pubkey; // Fallback to event pubkey
|
||||
|
||||
try {
|
||||
// If it's already a hex key, use it directly
|
||||
if (app.authorNpub.length === 64 && /^[0-9a-f]+$/i.test(app.authorNpub)) {
|
||||
return app.authorNpub;
|
||||
}
|
||||
|
||||
// Otherwise try to decode as npub
|
||||
const decoded = nip19.decode(app.authorNpub);
|
||||
return decoded.type === 'npub' ? decoded.data : app.pubkey;
|
||||
} catch {
|
||||
return app.pubkey; // Fallback to event pubkey if decode fails
|
||||
}
|
||||
}, [app.authorNpub, app.pubkey]);
|
||||
|
||||
const { data: authorData } = useAuthor(authorPubkey);
|
||||
const isOwner = user?.pubkey === app.pubkey;
|
||||
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
|
||||
const MODERATOR_HEX = (() => {
|
||||
try {
|
||||
const decoded = nip19.decode(MODERATOR_NPUB);
|
||||
return decoded.type === 'npub' ? decoded.data : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
})();
|
||||
const isModerator = user?.pubkey === MODERATOR_HEX;
|
||||
|
||||
// Check if this is a Halloween submission by looking for Halloween tags
|
||||
const isHalloweenSubmission = app.appTags.includes('Halloween Hackathon 2025');
|
||||
|
||||
// Get contact info from Halloween submissions (these have lightning/email tags)
|
||||
const getContactInfo = () => {
|
||||
if (!isHalloweenSubmission) return null;
|
||||
|
||||
// Look for lightning and email tags in the event tags
|
||||
const lightningTag = app.tags?.find((tag: string[]) => tag[0] === 'lightning')?.[1];
|
||||
const emailTag = app.tags?.find((tag: string[]) => tag[0] === 'email')?.[1];
|
||||
|
||||
return { lightning: lightningTag, email: emailTag };
|
||||
};
|
||||
|
||||
const handleCopyContactInfo = () => {
|
||||
const contactInfo = getContactInfo();
|
||||
if (!contactInfo) return;
|
||||
|
||||
const info: string[] = [];
|
||||
if (contactInfo.lightning) info.push(`Lightning: ${contactInfo.lightning}`);
|
||||
if (contactInfo.email) info.push(`Email: ${contactInfo.email}`);
|
||||
|
||||
const textToCopy = info.join('\n');
|
||||
navigator.clipboard.writeText(textToCopy);
|
||||
|
||||
toast({
|
||||
title: 'Contact Info Copied!',
|
||||
description: `Copied ${info.length} contact method(s) to clipboard`
|
||||
});
|
||||
};
|
||||
|
||||
const handleModerationAction = async (action: 'feature' | 'unfeature' | 'approve' | 'unapprove' | 'hide' | 'unhide' | 'homepage' | 'unhomepage') => {
|
||||
if (!isModerator || !user) return;
|
||||
|
||||
const dTag = app.tags.find(tag => tag[0] === 'd')?.[1];
|
||||
if (!dTag) {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Cannot perform moderation action: missing app identifier',
|
||||
variant: 'destructive'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const appCoordinate = `${app.kind}:${app.pubkey}:${dTag}`;
|
||||
|
||||
try {
|
||||
if (action === 'homepage' || action === 'unhomepage') {
|
||||
// Get current homepage apps list
|
||||
const currentHomepageLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-homepage-apps'],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
|
||||
const currentHomepageList = currentHomepageLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get current homepage app coordinates
|
||||
const currentHomepageApps = new Set<string>();
|
||||
if (currentHomepageList) {
|
||||
currentHomepageList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => currentHomepageApps.add(tag[1]));
|
||||
}
|
||||
|
||||
// Update the homepage set
|
||||
if (action === 'homepage') {
|
||||
currentHomepageApps.add(appCoordinate);
|
||||
} else {
|
||||
currentHomepageApps.delete(appCoordinate);
|
||||
}
|
||||
|
||||
// Publish updated homepage apps list
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox homepage apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-homepage-apps'],
|
||||
['title', 'Soapbox Homepage Apps'],
|
||||
['description', 'Apps displayed on the Soapbox homepage'],
|
||||
...Array.from(currentHomepageApps).map(coord => ['a', coord])
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
|
||||
// If adding to homepage, also ensure it's approved
|
||||
if (action === 'homepage') {
|
||||
// Get current approved apps list
|
||||
const currentApprovedLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get current approved app coordinates
|
||||
const currentApprovedApps = new Set<string>();
|
||||
if (currentApprovedList) {
|
||||
currentApprovedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => currentApprovedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
// Add to approved list if not already there
|
||||
currentApprovedApps.add(appCoordinate);
|
||||
|
||||
// Publish updated approved apps list
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox approved apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-approved-apps'],
|
||||
['title', 'Soapbox Approved Apps'],
|
||||
['description', 'Apps approved for the Soapbox showcase'],
|
||||
...Array.from(currentApprovedApps).map(coord => ['a', coord])
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
}
|
||||
|
||||
} else if (action === 'feature' || action === 'unfeature') {
|
||||
// Get current featured apps list
|
||||
const currentFeaturedLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-featured-apps'],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
|
||||
const currentFeaturedList = currentFeaturedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get current featured app coordinates
|
||||
const currentFeaturedApps = new Set<string>();
|
||||
if (currentFeaturedList) {
|
||||
currentFeaturedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => currentFeaturedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
// Update the featured set
|
||||
if (action === 'feature') {
|
||||
currentFeaturedApps.add(appCoordinate);
|
||||
} else {
|
||||
currentFeaturedApps.delete(appCoordinate);
|
||||
}
|
||||
|
||||
// Publish updated featured apps list
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox featured apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-featured-apps'],
|
||||
['title', 'Soapbox Featured Apps'],
|
||||
['description', 'Apps featured in the Soapbox showcase'],
|
||||
...Array.from(currentFeaturedApps).map(coord => ['a', coord])
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
|
||||
// If featuring an app, also ensure it's approved
|
||||
if (action === 'feature') {
|
||||
// Get current approved apps list
|
||||
const currentApprovedLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get current approved app coordinates
|
||||
const currentApprovedApps = new Set<string>();
|
||||
if (currentApprovedList) {
|
||||
currentApprovedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => currentApprovedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
// Add to approved list if not already there
|
||||
currentApprovedApps.add(appCoordinate);
|
||||
|
||||
// Publish updated approved apps list
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox approved apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-approved-apps'],
|
||||
['title', 'Soapbox Approved Apps'],
|
||||
['description', 'Apps approved for the Soapbox showcase'],
|
||||
...Array.from(currentApprovedApps).map(coord => ['a', coord])
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
}
|
||||
|
||||
} else if (action === 'approve' || action === 'unapprove') {
|
||||
// Get current approved apps list
|
||||
const currentApprovedLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get current approved app coordinates
|
||||
const currentApprovedApps = new Set<string>();
|
||||
if (currentApprovedList) {
|
||||
currentApprovedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => currentApprovedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
// Update the approved set
|
||||
if (action === 'approve') {
|
||||
currentApprovedApps.add(appCoordinate);
|
||||
} else {
|
||||
currentApprovedApps.delete(appCoordinate);
|
||||
}
|
||||
|
||||
// Publish updated approved apps list
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox approved apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-approved-apps'],
|
||||
['title', 'Soapbox Approved Apps'],
|
||||
['description', 'Apps approved for the Soapbox showcase'],
|
||||
...Array.from(currentApprovedApps).map(coord => ['a', coord])
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
|
||||
} else if (action === 'hide' || action === 'unhide') {
|
||||
// Create NIP-56 report event
|
||||
publishEvent({
|
||||
kind: 1984,
|
||||
content: `App ${action}den by moderator: "${app.appName}"`,
|
||||
tags: [
|
||||
['a', appCoordinate, action === 'hide' ? 'spam' : 'other'],
|
||||
['p', app.pubkey],
|
||||
['L', 'soapbox.moderation'],
|
||||
['l', action === 'hide' ? 'hidden' : 'unhidden', 'soapbox.moderation']
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
}
|
||||
|
||||
// Invalidate queries to refresh the data
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
|
||||
// If this is a Halloween app, also invalidate Halloween queries
|
||||
if (isHalloweenSubmission) {
|
||||
queryClient.invalidateQueries({ queryKey: ['halloween-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['halloween-submissions-with-contacts'] });
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Success!',
|
||||
description: `App "${app.appName}" ${action}d successfully`
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Moderation action failed:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: `Failed to ${action} app "${app.appName}"`,
|
||||
variant: 'destructive'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col">
|
||||
<div className="relative">
|
||||
{/* App Screenshot */}
|
||||
<a
|
||||
href={app.websiteUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
|
||||
>
|
||||
{!imageError ? (
|
||||
<img
|
||||
src={app.screenshotUrl}
|
||||
alt={`${app.appName} screenshot`}
|
||||
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
|
||||
onError={() => setImageError(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
|
||||
<div className="text-center">
|
||||
<div className="w-16 h-16 mx-auto mb-2 bg-muted rounded-lg flex items-center justify-center">
|
||||
<ExternalLink className="w-8 h-8" />
|
||||
</div>
|
||||
<p className="text-sm">Screenshot unavailable</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</a>
|
||||
|
||||
{/* Actions Menu */}
|
||||
{(isOwner || showModerationControls) && (
|
||||
<div className="absolute top-3 right-3">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="secondary" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{isOwner && (
|
||||
<DropdownMenuItem onClick={() => onEdit?.(app)}>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Edit App
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{showModerationControls && isModerator && (
|
||||
<>
|
||||
{isHalloweenSubmission && getContactInfo() && (getContactInfo()?.lightning || getContactInfo()?.email) && (
|
||||
<DropdownMenuItem
|
||||
onClick={handleCopyContactInfo}
|
||||
>
|
||||
<Contact className="w-4 h-4 mr-2" />
|
||||
View Contact Info
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{!app.isApproved && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction('approve')}
|
||||
disabled={isPending}
|
||||
>
|
||||
<CheckCircle className="w-4 h-4 mr-2" />
|
||||
Approve
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{app.isApproved && !app.isFeatured && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction('unapprove')}
|
||||
disabled={isPending}
|
||||
>
|
||||
<XCircle className="w-4 h-4 mr-2" />
|
||||
Unapprove
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction(app.isFeatured ? 'unfeature' : 'feature')}
|
||||
disabled={isPending}
|
||||
>
|
||||
{app.isFeatured ? (
|
||||
<>
|
||||
<StarOff className="w-4 h-4 mr-2" />
|
||||
Un-feature
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Star className="w-4 h-4 mr-2" />
|
||||
Feature
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction(app.isHomepage ? 'unhomepage' : 'homepage')}
|
||||
disabled={isPending}
|
||||
>
|
||||
{app.isHomepage ? (
|
||||
<>
|
||||
<Home className="w-4 h-4 mr-2" />
|
||||
Remove from Homepage
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Home className="w-4 h-4 mr-2" />
|
||||
Add to Homepage
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction(app.isHidden ? 'unhide' : 'hide')}
|
||||
disabled={isPending}
|
||||
>
|
||||
{app.isHidden ? (
|
||||
<>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Unhide
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<EyeOff className="w-4 h-4 mr-2" />
|
||||
Hide
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-3">
|
||||
{/* App Icon */}
|
||||
<div className="w-12 h-12 rounded-lg overflow-hidden bg-muted flex-shrink-0">
|
||||
<img
|
||||
src={app.appIconUrl}
|
||||
alt={`${app.appName} icon`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold text-foreground mb-1" title={app.appName}>
|
||||
{app.appName.length > 50 ? `${app.appName.slice(0, 50)}...` : app.appName}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-muted-foreground mb-3 line-clamp-3">{app.description}</p>
|
||||
|
||||
{/* Author Information */}
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<div className="w-6 h-6 rounded-full overflow-hidden bg-muted flex-shrink-0">
|
||||
{authorData?.metadata?.picture ? (
|
||||
<img
|
||||
src={authorData.metadata.picture}
|
||||
alt={`${authorData.metadata.name || 'Author'} avatar`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
target.parentElement!.innerHTML = '<div class="w-full h-full flex items-center justify-center"><svg class="w-3 h-3 text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path></svg></div>';
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center">
|
||||
<User className="w-3 h-3 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
by{' '}
|
||||
<a
|
||||
href={`https://ditto.pub/${app.authorNpub || nip19.npubEncode(authorPubkey)}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:text-primary/80 transition-colors hover:underline"
|
||||
>
|
||||
{authorData?.metadata?.name || authorData?.metadata?.display_name || 'Anonymous'}
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Spacer to push action links to bottom */}
|
||||
<div className="flex-1"></div>
|
||||
|
||||
{/* Action Links */}
|
||||
<div className="flex items-center gap-2 mt-auto">
|
||||
<Link
|
||||
to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`}
|
||||
className="flex-1"
|
||||
>
|
||||
<img
|
||||
src="/badge.svg"
|
||||
alt="Edit with Shakespeare"
|
||||
className="h-6 hover:opacity-80 transition-opacity"
|
||||
/>
|
||||
</Link>
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a
|
||||
href={app.websiteUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title="Visit app"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { ReactNode } from 'react';
|
||||
import { ConsoleErrorProvider } from './ConsoleErrorProvider';
|
||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||
import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
|
||||
// Wrapper component for testing
|
||||
function TestWrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<ConsoleErrorProvider>
|
||||
{children}
|
||||
</ConsoleErrorProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ConsoleErrorProvider', () => {
|
||||
beforeEach(() => {
|
||||
clearConsoleMessages();
|
||||
});
|
||||
|
||||
it('should provide initial state with no errors', () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
});
|
||||
|
||||
it('should update hasErrors when console error is added', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
|
||||
// Add an error message
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(true);
|
||||
expect(result.current.consoleError).toBeInstanceOf(ProjectPreviewConsoleError);
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: Test error message');
|
||||
});
|
||||
|
||||
it('should not update hasErrors for non-error messages', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add non-error messages
|
||||
act(() => {
|
||||
addConsoleMessage('log', 'Test log message');
|
||||
addConsoleMessage('warn', 'Test warning message');
|
||||
addConsoleMessage('info', 'Test info message');
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
});
|
||||
|
||||
it('should update consoleError with latest error message', () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add first error
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'First error');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: First error');
|
||||
|
||||
// Add second error - should update to show latest error
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Second error');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: Second error');
|
||||
expect(result.current.consoleError?.logs).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should clear errors when clearErrors is called', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add error to set state
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(true);
|
||||
expect(result.current.consoleError).not.toBeNull();
|
||||
|
||||
// Clear errors
|
||||
act(() => {
|
||||
result.current.clearErrors();
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
});
|
||||
|
||||
it('should dismiss console error when dismissConsoleError is called', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add error to create console error
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError).not.toBeNull();
|
||||
|
||||
// Dismiss console error (this only clears the Quilly error, not the global state)
|
||||
act(() => {
|
||||
result.current.dismissConsoleError();
|
||||
});
|
||||
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
// hasErrors should still be true since we only dismissed the Quilly display
|
||||
expect(result.current.hasErrors).toBe(true);
|
||||
});
|
||||
|
||||
it('should include all error messages in console error logs', () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add multiple errors and non-errors
|
||||
act(() => {
|
||||
addConsoleMessage('log', 'Log message');
|
||||
addConsoleMessage('error', 'First error');
|
||||
addConsoleMessage('warn', 'Warning message');
|
||||
addConsoleMessage('error', 'Second error');
|
||||
addConsoleMessage('info', 'Info message');
|
||||
addConsoleMessage('error', 'Third error');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: Third error');
|
||||
expect(result.current.consoleError?.logs).toHaveLength(3);
|
||||
expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([
|
||||
'First error',
|
||||
'Second error',
|
||||
'Third error'
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useState, useEffect, useCallback, ReactNode } from 'react';
|
||||
import {
|
||||
addConsoleMessageListener,
|
||||
removeConsoleMessageListener,
|
||||
getHasConsoleErrors,
|
||||
getConsoleMessages,
|
||||
clearConsoleMessages,
|
||||
ProjectPreviewConsoleError
|
||||
} from '@/lib/consoleMessages';
|
||||
import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext';
|
||||
|
||||
interface ConsoleErrorProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) {
|
||||
const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors());
|
||||
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
|
||||
|
||||
const updateState = useCallback(() => {
|
||||
const hasConsoleErrors = getHasConsoleErrors();
|
||||
setHasErrors(hasConsoleErrors);
|
||||
|
||||
if (hasConsoleErrors) {
|
||||
const errorMessages = getConsoleMessages().filter(msg => msg.level === 'error');
|
||||
const latestError = errorMessages[errorMessages.length - 1];
|
||||
setConsoleError(new ProjectPreviewConsoleError(
|
||||
`Console error detected: ${latestError.message}`,
|
||||
errorMessages
|
||||
));
|
||||
} else {
|
||||
setConsoleError(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
addConsoleMessageListener(updateState);
|
||||
updateState(); // Initial sync
|
||||
|
||||
return () => removeConsoleMessageListener(updateState);
|
||||
}, [updateState]);
|
||||
|
||||
const clearErrors = useCallback(() => {
|
||||
clearConsoleMessages();
|
||||
}, []);
|
||||
|
||||
const dismissConsoleError = useCallback(() => {
|
||||
setConsoleError(null);
|
||||
}, []);
|
||||
|
||||
const value = {
|
||||
hasErrors,
|
||||
consoleError,
|
||||
clearErrors,
|
||||
dismissConsoleError,
|
||||
};
|
||||
|
||||
return (
|
||||
<ConsoleErrorContext.Provider value={value}>
|
||||
{children}
|
||||
</ConsoleErrorContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { CreditsBadge } from './CreditsBadge';
|
||||
|
||||
// Mock the useAICredits hook
|
||||
vi.mock('@/hooks/useAICredits', () => ({
|
||||
useAICredits: () => ({
|
||||
data: { amount: 10.50 },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock the fetch function
|
||||
global.fetch = vi.fn();
|
||||
|
||||
const mockProvider = {
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
|
||||
describe('CreditsBadge', () => {
|
||||
it('renders the credits amount', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('$10.50')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onOpenDialog when badge is clicked', () => {
|
||||
const mockCallback = vi.fn();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsBadge
|
||||
provider={mockProvider}
|
||||
onOpenDialog={mockCallback}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const badge = screen.getByText('$10.50');
|
||||
fireEvent.click(badge);
|
||||
|
||||
expect(mockCallback).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('has proper styling for clickable badge', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const badge = screen.getByText('$10.50');
|
||||
expect(badge).toHaveClass('cursor-pointer');
|
||||
expect(badge).toHaveClass('hover:bg-secondary/80');
|
||||
});
|
||||
|
||||
it('does not render dialog directly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Dialog should not be rendered by CreditsBadge itself
|
||||
expect(screen.queryByText('Credits - test-provider')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
|
||||
interface CreditsBadgeProps {
|
||||
provider: AIProvider;
|
||||
className?: string;
|
||||
onOpenDialog?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a clickable credits badge showing the remaining credits for an AI provider
|
||||
*/
|
||||
export function CreditsBadge({ provider, className, onOpenDialog }: CreditsBadgeProps) {
|
||||
const { data: credits, isLoading, error } = useAICredits(provider);
|
||||
|
||||
// Don't render anything if there's an error (provider doesn't support credits endpoint)
|
||||
if (error || isLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Don't render if no credits data is available
|
||||
if (!credits) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Format the amount as currency
|
||||
const formattedAmount = new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(credits.amount);
|
||||
|
||||
return (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={`cursor-pointer hover:bg-secondary/80 transition-colors ${className}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onOpenDialog?.();
|
||||
}}
|
||||
>
|
||||
{formattedAmount}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Mock the fetch function
|
||||
global.fetch = vi.fn();
|
||||
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
nostr: false,
|
||||
};
|
||||
|
||||
describe('CreditsDialog', () => {
|
||||
it('renders dialog when open', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Credits')).toBeInTheDocument();
|
||||
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
|
||||
expect(screen.getByText('Recent Transactions')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
open={false}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.queryByText('Credits')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows payment method options', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Payment Method')).toBeInTheDocument();
|
||||
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows preset amount buttons', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('$5')).toBeInTheDocument();
|
||||
expect(screen.getByText('$10')).toBeInTheDocument();
|
||||
expect(screen.getByText('$25')).toBeInTheDocument();
|
||||
expect(screen.getByText('$50')).toBeInTheDocument();
|
||||
expect(screen.getByText('$100')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('calls onDialogStateChange callback when dialog state changes', () => {
|
||||
const mockCallback = vi.fn();
|
||||
const { rerender } = render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
open={false}
|
||||
onOpenChange={mockCallback}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Simulate opening the dialog
|
||||
rerender(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={mockCallback}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Credits')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,529 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { useDeploySettings } from '@/hooks/useDeploySettings';
|
||||
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||
|
||||
/**
|
||||
* Helper function to get provider URL for favicon
|
||||
*/
|
||||
function getProviderUrl(provider: DeployProvider): string | null {
|
||||
switch (provider.type) {
|
||||
case 'shakespeare':
|
||||
if (provider.host) {
|
||||
return `https://${provider.host}`;
|
||||
}
|
||||
return 'https://shakespeare.diy';
|
||||
|
||||
case 'netlify':
|
||||
if (provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://netlify.com';
|
||||
|
||||
case 'vercel':
|
||||
if (provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://vercel.com';
|
||||
|
||||
case 'nsite':
|
||||
return null;
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render provider icon using favicon or fallback
|
||||
*/
|
||||
function renderProviderIcon(provider: DeployProvider, size = 14) {
|
||||
const url = getProviderUrl(provider);
|
||||
|
||||
if (url) {
|
||||
return (
|
||||
<ExternalFavicon
|
||||
url={url}
|
||||
size={size}
|
||||
fallback={<Rocket size={size} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <Rocket size={size} />;
|
||||
}
|
||||
|
||||
interface DeployDialogProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
interface ShakespeareFormData {
|
||||
subdomain: string;
|
||||
}
|
||||
|
||||
interface NsiteFormData {
|
||||
nsec: string;
|
||||
}
|
||||
|
||||
interface NetlifyFormData {
|
||||
siteId: string;
|
||||
siteName: string;
|
||||
}
|
||||
|
||||
interface VercelFormData {
|
||||
projectName: string;
|
||||
teamId: string;
|
||||
}
|
||||
|
||||
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const { settings } = useDeploySettings();
|
||||
const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId);
|
||||
const { user } = useCurrentUser();
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { config } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||
|
||||
// Provider-specific form data
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
subdomain: projectId,
|
||||
});
|
||||
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
|
||||
nsec: '',
|
||||
});
|
||||
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
|
||||
siteId: '',
|
||||
siteName: '',
|
||||
});
|
||||
const [vercelForm, setVercelForm] = useState<VercelFormData>({
|
||||
projectName: projectName || projectId,
|
||||
teamId: '',
|
||||
});
|
||||
|
||||
// Load project settings when dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
// First, try to use the currentProvider from project settings
|
||||
if (projectSettings.currentProvider && settings.providers.some(p => p.id === projectSettings.currentProvider)) {
|
||||
setSelectedProviderId(projectSettings.currentProvider);
|
||||
} else {
|
||||
// Otherwise, find the first configured provider in project settings
|
||||
const providerIds = Object.keys(projectSettings.providers);
|
||||
if (providerIds.length > 0) {
|
||||
setSelectedProviderId(providerIds[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [open, projectSettings, settings.providers]);
|
||||
|
||||
const selectedProvider = settings.providers.find(p => p.id === selectedProviderId);
|
||||
|
||||
const handleDeploy = async () => {
|
||||
if (!selectedProvider) return;
|
||||
|
||||
setIsDeploying(true);
|
||||
setError(null);
|
||||
setDeployResult(null);
|
||||
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
let adapter: DeployAdapter;
|
||||
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
if (!user) {
|
||||
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
|
||||
}
|
||||
|
||||
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
|
||||
adapter = new ShakespeareAdapter({
|
||||
fs,
|
||||
signer: user.signer,
|
||||
host: shakespeareProvider.host,
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
const nsiteProvider = selectedProvider as import('@/contexts/DeploySettingsContext').NsiteProvider;
|
||||
|
||||
if (!nsiteForm.nsec) {
|
||||
throw new Error('Site private key (nsec) is required');
|
||||
}
|
||||
|
||||
adapter = new NsiteAdapter({
|
||||
fs,
|
||||
nostr,
|
||||
nsec: nsiteForm.nsec,
|
||||
gateway: nsiteProvider.gateway,
|
||||
relayUrls: nsiteProvider.relayUrls,
|
||||
blossomServers: nsiteProvider.blossomServers,
|
||||
});
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
const netlifyProvider = selectedProvider as NetlifyProvider;
|
||||
if (!netlifyProvider.apiKey) {
|
||||
throw new Error('Netlify API key is required');
|
||||
}
|
||||
|
||||
// If siteId is empty, we're creating a new site, so only pass siteName
|
||||
// If siteId is set, we're updating an existing site
|
||||
adapter = new NetlifyAdapter({
|
||||
fs,
|
||||
apiKey: netlifyProvider.apiKey,
|
||||
baseURL: netlifyProvider.baseURL,
|
||||
siteName: netlifyForm.siteId ? undefined : (netlifyForm.siteName || undefined),
|
||||
siteId: netlifyForm.siteId || undefined,
|
||||
corsProxy: netlifyProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'vercel') {
|
||||
const vercelProvider = selectedProvider as VercelProvider;
|
||||
if (!vercelProvider.apiKey) {
|
||||
throw new Error('Vercel API key is required');
|
||||
}
|
||||
|
||||
adapter = new VercelAdapter({
|
||||
fs,
|
||||
apiKey: vercelProvider.apiKey,
|
||||
baseURL: vercelProvider.baseURL,
|
||||
teamId: vercelForm.teamId || undefined,
|
||||
projectName: vercelForm.projectName || undefined,
|
||||
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else {
|
||||
throw new Error('Unknown provider type');
|
||||
}
|
||||
|
||||
const result = await adapter.deploy({
|
||||
projectId,
|
||||
projectPath,
|
||||
});
|
||||
|
||||
// Save project-specific settings (updateSettings now automatically sets currentProvider)
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'shakespeare',
|
||||
data: {
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'nsite',
|
||||
data: {
|
||||
nsec: nsiteForm.nsec,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'netlify',
|
||||
data: {
|
||||
siteId: result.metadata?.siteId as string | undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'vercel') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'vercel',
|
||||
data: {
|
||||
teamId: vercelForm.teamId || undefined,
|
||||
projectId: vercelForm.projectName || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
setDeployResult(result);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Deployment failed');
|
||||
} finally {
|
||||
setIsDeploying(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setSelectedProviderId('');
|
||||
setDeployResult(null);
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
setNsiteForm({ nsec: '' });
|
||||
setNetlifyForm({ siteId: '', siteName: '' });
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
|
||||
setShakespeareForm({ subdomain });
|
||||
}, []);
|
||||
|
||||
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
|
||||
setIsShakespeareFormValid(isValid);
|
||||
}, []);
|
||||
|
||||
const handleNsiteNsecChange = useCallback((nsec: string) => {
|
||||
setNsiteForm({ nsec });
|
||||
}, []);
|
||||
|
||||
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
|
||||
setNetlifyForm({ siteId, siteName });
|
||||
}, []);
|
||||
|
||||
const handleVercelConfigChange = useCallback((projectName: string, teamId: string) => {
|
||||
setVercelForm({ projectName, teamId });
|
||||
}, []);
|
||||
|
||||
const renderProviderFields = () => {
|
||||
if (!selectedProvider) return null;
|
||||
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
|
||||
|
||||
return (
|
||||
<ShakespeareDeployForm
|
||||
host={shakespeareProvider.host}
|
||||
projectId={projectId}
|
||||
onSubdomainChange={handleShakespeareSubdomainChange}
|
||||
onValidationChange={handleShakespeareValidationChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'nsite') {
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
|
||||
|
||||
return (
|
||||
<NsiteDeployForm
|
||||
gateway={selectedProvider.gateway}
|
||||
savedNsec={savedNsec}
|
||||
onNsecChange={handleNsiteNsecChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'netlify') {
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedSiteId = savedConfig?.type === 'netlify' ? savedConfig.data.siteId : undefined;
|
||||
|
||||
return (
|
||||
<NetlifyDeployForm
|
||||
apiKey={selectedProvider.apiKey}
|
||||
baseURL={selectedProvider.baseURL}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedSiteId={savedSiteId}
|
||||
onSiteChange={handleNetlifySiteChange}
|
||||
corsProxy={selectedProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'vercel') {
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedTeamId = savedConfig?.type === 'vercel' ? savedConfig.data.teamId : undefined;
|
||||
const savedProjectName = savedConfig?.type === 'vercel' ? savedConfig.data.projectId : undefined;
|
||||
|
||||
return (
|
||||
<VercelDeployForm
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedTeamId={savedTeamId}
|
||||
savedProjectName={savedProjectName}
|
||||
onConfigChange={handleVercelConfigChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Rocket className="h-5 w-5" />
|
||||
Deploy Project
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Deploy your project to a hosting platform
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{deployResult ? (
|
||||
<div className="space-y-4">
|
||||
<Alert>
|
||||
<Rocket className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Your project has been successfully deployed!
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Deployed URL</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={deployResult.url}
|
||||
readOnly
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => window.open(deployResult.url, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={handleClose}>
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{settings.providers.length === 0 ? (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
No deployment providers configured.{' '}
|
||||
<Link
|
||||
to="/settings/deploy"
|
||||
className="underline hover:no-underline"
|
||||
onClick={handleClose}
|
||||
>
|
||||
Configure deployment settings
|
||||
</Link>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="provider">Select Provider</Label>
|
||||
<Select value={selectedProviderId} onValueChange={setSelectedProviderId}>
|
||||
<SelectTrigger id="provider">
|
||||
{selectedProvider ? (
|
||||
<div className="flex items-center gap-2">
|
||||
{renderProviderIcon(selectedProvider, 14)}
|
||||
<span>{selectedProvider.name}</span>
|
||||
</div>
|
||||
) : (
|
||||
<SelectValue placeholder="Choose a deployment provider..." />
|
||||
)}
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{settings.providers.map((provider) => (
|
||||
<SelectItem key={provider.id} value={provider.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
{renderProviderIcon(provider, 14)}
|
||||
<span>{provider.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedProvider && renderProviderFields()}
|
||||
|
||||
{selectedProvider?.type === 'shakespeare' && !user && (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
|
||||
<Link
|
||||
to="/settings/nostr"
|
||||
className="underline hover:no-underline"
|
||||
onClick={handleClose}
|
||||
>
|
||||
Go to Nostr Settings
|
||||
</Link>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleDeploy}
|
||||
disabled={
|
||||
!selectedProvider ||
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
|
||||
}
|
||||
>
|
||||
{isDeploying ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
|
||||
Deploying...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Rocket className="h-4 w-4 mr-2" />
|
||||
Deploy
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { useState, useEffect, useMemo, type ReactNode } from 'react';
|
||||
import { DeploySettingsContext, type DeploySettings, type DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
|
||||
|
||||
const DEFAULT_SETTINGS: DeploySettings = {
|
||||
providers: [],
|
||||
};
|
||||
|
||||
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||
const { fs } = useFS();
|
||||
const { configPath } = useFSPaths();
|
||||
const [settings, setSettings] = useState<DeploySettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// Initialize settings from VFS on mount
|
||||
useEffect(() => {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readDeploySettings(fs, configPath);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize deploy settings:', error);
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
};
|
||||
|
||||
initializeSettings();
|
||||
}, [fs, configPath]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeDeploySettings(fs, settings, configPath);
|
||||
} catch (error) {
|
||||
console.error('Failed to save deploy settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized, configPath]);
|
||||
|
||||
const updateSettings = (updates: Partial<DeploySettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...updates }));
|
||||
};
|
||||
|
||||
const removeProvider = (index: number) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers: prev.providers.filter((_, i) => i !== index),
|
||||
}));
|
||||
};
|
||||
|
||||
const setProviders = (providers: DeployProvider[]) => {
|
||||
setSettings(prev => ({ ...prev, providers }));
|
||||
};
|
||||
|
||||
const isConfigured = useMemo(() => {
|
||||
return settings.providers.length > 0;
|
||||
}, [settings.providers]);
|
||||
|
||||
const value = {
|
||||
settings,
|
||||
updateSettings,
|
||||
removeProvider,
|
||||
setProviders,
|
||||
isConfigured,
|
||||
isInitialized,
|
||||
};
|
||||
|
||||
return (
|
||||
<DeploySettingsContext.Provider value={value}>
|
||||
{children}
|
||||
</DeploySettingsContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy';
|
||||
|
||||
/**
|
||||
* Component that dynamically updates the favicon when any project is busy with AI
|
||||
* Rotates the favicon counter-clockwise when busy
|
||||
*/
|
||||
export function DynamicFavicon() {
|
||||
const isBusy = useAnyProjectBusy();
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
const animationRef = useRef<number | null>(null);
|
||||
const rotationRef = useRef(0);
|
||||
const originalFaviconRef = useRef<string | null>(null);
|
||||
const originalImageRef = useRef<HTMLImageElement | null>(null);
|
||||
|
||||
// Initialize canvas and save original favicon
|
||||
useEffect(() => {
|
||||
// Create canvas element for drawing the favicon
|
||||
if (!canvasRef.current) {
|
||||
canvasRef.current = document.createElement('canvas');
|
||||
canvasRef.current.width = 32;
|
||||
canvasRef.current.height = 32;
|
||||
}
|
||||
|
||||
// Store the original favicon URL
|
||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
||||
if (faviconElement && !originalFaviconRef.current) {
|
||||
originalFaviconRef.current = faviconElement.getAttribute('href');
|
||||
}
|
||||
|
||||
// Preload the favicon image
|
||||
if (!originalImageRef.current) {
|
||||
const img = new Image();
|
||||
img.crossOrigin = 'anonymous';
|
||||
img.src = originalFaviconRef.current || '/shakespeare-192x192.png';
|
||||
img.onload = () => {
|
||||
originalImageRef.current = img;
|
||||
};
|
||||
}
|
||||
|
||||
return () => {
|
||||
// Restore original favicon on unmount
|
||||
if (originalFaviconRef.current) {
|
||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
||||
if (faviconElement) {
|
||||
faviconElement.setAttribute('href', originalFaviconRef.current);
|
||||
}
|
||||
}
|
||||
|
||||
// Cancel any ongoing animation
|
||||
if (animationRef.current !== null) {
|
||||
cancelAnimationFrame(animationRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Handle busy state changes
|
||||
useEffect(() => {
|
||||
if (!canvasRef.current) return;
|
||||
|
||||
// If busy, start rotation animation
|
||||
if (isBusy) {
|
||||
const startRotationAnimation = () => {
|
||||
if (!canvasRef.current || !originalImageRef.current) {
|
||||
// If image isn't loaded yet, try again in a moment
|
||||
setTimeout(startRotationAnimation, 100);
|
||||
return;
|
||||
}
|
||||
|
||||
const canvas = canvasRef.current;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const img = originalImageRef.current;
|
||||
|
||||
const animate = () => {
|
||||
if (!ctx || !canvas) return;
|
||||
|
||||
// Clear canvas
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
// Save context state
|
||||
ctx.save();
|
||||
|
||||
// Translate to center for rotation
|
||||
ctx.translate(canvas.width / 2, canvas.height / 2);
|
||||
|
||||
// Rotate counter-clockwise
|
||||
ctx.rotate(-rotationRef.current);
|
||||
|
||||
// Draw the image centered
|
||||
ctx.drawImage(
|
||||
img,
|
||||
-canvas.width / 2,
|
||||
-canvas.height / 2,
|
||||
canvas.width,
|
||||
canvas.height
|
||||
);
|
||||
|
||||
// Restore context state
|
||||
ctx.restore();
|
||||
|
||||
// Update rotation for next frame (slower rotation)
|
||||
rotationRef.current += 0.05;
|
||||
|
||||
// Update favicon
|
||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
||||
if (faviconElement) {
|
||||
faviconElement.setAttribute('href', canvas.toDataURL('image/png'));
|
||||
}
|
||||
|
||||
// Continue animation
|
||||
animationRef.current = requestAnimationFrame(animate);
|
||||
};
|
||||
|
||||
// Start animation loop
|
||||
animate();
|
||||
};
|
||||
|
||||
startRotationAnimation();
|
||||
} else {
|
||||
// If not busy, restore original favicon and stop animation
|
||||
if (animationRef.current !== null) {
|
||||
cancelAnimationFrame(animationRef.current);
|
||||
animationRef.current = null;
|
||||
}
|
||||
|
||||
// Reset rotation
|
||||
rotationRef.current = 0;
|
||||
|
||||
// Restore original favicon
|
||||
if (originalFaviconRef.current) {
|
||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
||||
if (faviconElement) {
|
||||
faviconElement.setAttribute('href', originalFaviconRef.current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
// Cancel animation on effect cleanup
|
||||
if (animationRef.current !== null) {
|
||||
cancelAnimationFrame(animationRef.current);
|
||||
animationRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [isBusy]);
|
||||
|
||||
// This component doesn't render anything visible
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Mail, CheckCircle } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export function EmailSubscription() {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0');
|
||||
const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`;
|
||||
const tag = '8982396';
|
||||
|
||||
// Check localStorage on component mount
|
||||
useEffect(() => {
|
||||
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
||||
if (hasSubscribed === 'true') {
|
||||
setIsSubmitted(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
toast({
|
||||
title: "Email required",
|
||||
description: "Please enter your email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
toast({
|
||||
title: "Invalid email",
|
||||
description: "Please enter a valid email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Submit to Mailchimp
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = url.href;
|
||||
form.target = '_blank'; // Open in new tab
|
||||
form.style.display = 'none';
|
||||
|
||||
// Add email field
|
||||
const emailInput = document.createElement('input');
|
||||
emailInput.type = 'email';
|
||||
emailInput.name = 'EMAIL';
|
||||
emailInput.value = email.trim();
|
||||
form.appendChild(emailInput);
|
||||
|
||||
// Add tag field with the new Shakespeare tag ID
|
||||
const tagInput = document.createElement('input');
|
||||
tagInput.type = 'hidden';
|
||||
tagInput.name = 'tags';
|
||||
tagInput.value = tag;
|
||||
form.appendChild(tagInput);
|
||||
|
||||
// Add npub if available
|
||||
if (user?.pubkey) {
|
||||
const npubInput = document.createElement('input');
|
||||
npubInput.type = 'text';
|
||||
npubInput.name = 'NPUB';
|
||||
npubInput.value = nip19.npubEncode(user.pubkey);
|
||||
npubInput.style.display = 'none';
|
||||
form.appendChild(npubInput);
|
||||
}
|
||||
|
||||
// Add honeypot field
|
||||
const honeypotInput = document.createElement('input');
|
||||
honeypotInput.type = 'text';
|
||||
honeypotInput.name = honeypot;
|
||||
honeypotInput.tabIndex = -1;
|
||||
honeypotInput.style.position = 'absolute';
|
||||
honeypotInput.style.left = '-5000px';
|
||||
form.appendChild(honeypotInput);
|
||||
|
||||
// Add form to document and submit
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
|
||||
// Clean up after a short delay
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(form);
|
||||
}, 1000);
|
||||
|
||||
// Save subscription status to localStorage
|
||||
localStorage.setItem('shakespeare-email-subscribed', 'true');
|
||||
|
||||
setIsSubmitted(true);
|
||||
toast({
|
||||
title: "Successfully subscribed!",
|
||||
description: "You'll receive Shakespeare updates and resources occasionally.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Email signup error:', error);
|
||||
toast({
|
||||
title: "Subscription failed",
|
||||
description: "There was an error subscribing you to updates. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isSubmitted) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-semibold">
|
||||
Thanks for subscribing!
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => {
|
||||
localStorage.removeItem('shakespeare-email-subscribed');
|
||||
setIsSubmitted(false);
|
||||
setEmail('');
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full text-xs"
|
||||
>
|
||||
Subscribe with different email
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Mail className="h-5 w-5 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t('emailUpdatesDescription')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">
|
||||
Email Address
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { ErrorBoundary } from './ErrorBoundary';
|
||||
|
||||
// Component that throws an error
|
||||
function ThrowError({ shouldThrow }: { shouldThrow: boolean }) {
|
||||
if (shouldThrow) {
|
||||
throw new Error('Test error message');
|
||||
}
|
||||
return <div>No error</div>;
|
||||
}
|
||||
|
||||
describe('ErrorBoundary', () => {
|
||||
// Suppress console.error during tests to avoid noise
|
||||
const originalError = console.error;
|
||||
beforeEach(() => {
|
||||
console.error = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
console.error = originalError;
|
||||
});
|
||||
|
||||
it('renders children when there is no error', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<div>Test content</div>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Test content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders error UI when child component throws', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
|
||||
expect(screen.getByText('Test error message')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders custom fallback when provided as ReactNode', () => {
|
||||
const customFallback = <div>Custom error UI</div>;
|
||||
|
||||
render(
|
||||
<ErrorBoundary fallback={customFallback}>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Custom error UI')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders custom fallback when provided as function', () => {
|
||||
const customFallback = ({ error }: { error: Error }) => (
|
||||
<div>Error: {error.message}</div>
|
||||
);
|
||||
|
||||
render(
|
||||
<ErrorBoundary fallback={customFallback}>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Error: Test error message')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onError callback when error occurs', () => {
|
||||
const onError = vi.fn();
|
||||
|
||||
render(
|
||||
<ErrorBoundary onError={onError}>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(onError).toHaveBeenCalledWith(
|
||||
expect.any(Error),
|
||||
expect.objectContaining({
|
||||
componentStack: expect.any(String),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('shows action buttons in error state', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: /reload page/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /go home/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows stack trace in development mode', () => {
|
||||
const originalEnv = process.env.NODE_ENV;
|
||||
process.env.NODE_ENV = 'development';
|
||||
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ThrowError shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Stack Trace')).toBeInTheDocument();
|
||||
|
||||
process.env.NODE_ENV = originalEnv;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { ErrorBoundary as ReactErrorBoundary, FallbackProps } from 'react-error-boundary';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
||||
import { AlertTriangle, RefreshCw, Home } from 'lucide-react';
|
||||
import { getSentryInstance } from '@/lib/sentry';
|
||||
|
||||
interface ErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode | ((props: FallbackProps) => ReactNode);
|
||||
onError?: (error: Error, info: { componentStack: string | null }) => void;
|
||||
/** Whether to report errors to Sentry (default: true) */
|
||||
reportToSentry?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default error fallback component
|
||||
*/
|
||||
function ErrorFallback({ error }: FallbackProps) {
|
||||
const handleReload = () => {
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
const handleGoHome = () => {
|
||||
window.location.href = '/';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4 bg-background">
|
||||
<Card className="max-w-2xl w-full">
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-destructive/10 rounded-full">
|
||||
<AlertTriangle className="h-6 w-6 text-destructive" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-2xl">Something went wrong</CardTitle>
|
||||
<CardDescription className="mt-1">
|
||||
We encountered an unexpected error. Don't worry, your data is safe.
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4">
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertTitle>Error Details</AlertTitle>
|
||||
<AlertDescription className="mt-2 font-mono text-xs break-all">
|
||||
{error.message}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{process.env.NODE_ENV === 'development' && error.stack && (
|
||||
<details className="mt-4">
|
||||
<summary className="cursor-pointer text-sm font-medium mb-2">
|
||||
Stack Trace
|
||||
</summary>
|
||||
<pre className="text-xs bg-muted p-4 rounded-md overflow-auto max-h-64">
|
||||
{error.stack}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="flex flex-wrap gap-2">
|
||||
<Button onClick={handleReload} variant="outline" className="gap-2">
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Reload Page
|
||||
</Button>
|
||||
<Button onClick={handleGoHome} variant="outline" className="gap-2">
|
||||
<Home className="h-4 w-4" />
|
||||
Go Home
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Error Boundary component that catches React rendering errors and displays a fallback UI.
|
||||
* Prevents the entire app from crashing when a component throws an error.
|
||||
*
|
||||
* Built on top of react-error-boundary for robust error handling.
|
||||
*/
|
||||
export function ErrorBoundary({
|
||||
children,
|
||||
fallback,
|
||||
onError,
|
||||
reportToSentry = true,
|
||||
}: ErrorBoundaryProps) {
|
||||
const handleError = (error: Error, info: { componentStack: string | null }) => {
|
||||
// Log error details for debugging
|
||||
console.error('ErrorBoundary caught an error:', error, info);
|
||||
|
||||
// Report to Sentry if enabled
|
||||
if (reportToSentry) {
|
||||
const Sentry = getSentryInstance();
|
||||
if (Sentry) {
|
||||
Sentry.captureException(error, {
|
||||
contexts: {
|
||||
react: {
|
||||
componentStack: info.componentStack,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Call optional error handler
|
||||
onError?.(error, info);
|
||||
};
|
||||
|
||||
// Determine fallback render
|
||||
const fallbackRender = typeof fallback === 'function'
|
||||
? fallback
|
||||
: fallback
|
||||
? () => fallback
|
||||
: ErrorFallback;
|
||||
|
||||
return (
|
||||
<ReactErrorBoundary
|
||||
fallbackRender={fallbackRender}
|
||||
onError={handleError}
|
||||
>
|
||||
{children}
|
||||
</ReactErrorBoundary>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ReactNode, useMemo } from 'react';
|
||||
|
||||
interface ExternalFaviconProps {
|
||||
/** The URL to fetch the favicon for */
|
||||
url: string;
|
||||
/** Size of the favicon in pixels */
|
||||
size?: number;
|
||||
/** Fallback element to display if favicon fails to load */
|
||||
fallback?: ReactNode;
|
||||
/** Additional CSS classes */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* ExternalFavicon component that fetches and displays a favicon for a given URL
|
||||
* using the configurable favicon service from app settings.
|
||||
*/
|
||||
export function ExternalFavicon({
|
||||
url,
|
||||
size = 16,
|
||||
fallback,
|
||||
className = '',
|
||||
}: ExternalFaviconProps) {
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Generate the favicon URL using the configured template
|
||||
const faviconSrc = useMemo(() => {
|
||||
try {
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
const normalizedUrl = normalizeUrl(url);
|
||||
return faviconUrl(config.faviconUrl, normalizedUrl);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}, [url, config.faviconUrl]);
|
||||
|
||||
// If faviconSrc is not available, render the fallback directly
|
||||
if (!faviconSrc) {
|
||||
return (
|
||||
<span className={cn('inline-flex items-center justify-center', className)}>
|
||||
<span>{fallback}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={cn('inline-flex items-center justify-center', className)}>
|
||||
<img
|
||||
src={faviconSrc}
|
||||
alt=""
|
||||
className="object-contain"
|
||||
style={{ width: size, height: size }}
|
||||
onError={(e) => {
|
||||
// Hide the image and show the fallback on error
|
||||
e.currentTarget.style.display = 'none';
|
||||
const fallbackElement = e.currentTarget.nextElementSibling as HTMLElement;
|
||||
if (fallbackElement) {
|
||||
fallbackElement.style.display = 'inline-block';
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{fallback && (
|
||||
<span style={{ display: 'none' }}>
|
||||
{fallback}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GiftCardRedeemDialog } from './GiftCardRedeemDialog';
|
||||
|
||||
// Mock fetch
|
||||
global.fetch = vi.fn();
|
||||
|
||||
describe('GiftCardRedeemDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders loading state initially', async () => {
|
||||
// Mock the gift card check endpoint
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockImplementation(() =>
|
||||
new Promise(() => {}) // Never resolves to keep it loading
|
||||
);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show loading skeleton
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error for invalid gift card', async () => {
|
||||
// Mock the gift card check endpoint to return an error
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: async () => ({
|
||||
error: {
|
||||
message: 'No giftcard found with code "INVALID-CODE"',
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="INVALID-CODE"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for error message to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Invalid Gift Card')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows already redeemed message for redeemed gift card', async () => {
|
||||
// Mock the gift card check endpoint to return a redeemed gift card
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
object: 'giftcard',
|
||||
id: 'gc_123',
|
||||
code: 'TEST-CODE-1234-5678',
|
||||
amount: 25.0,
|
||||
redeemed: true,
|
||||
created_at: 1640995200,
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for redeemed message to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Already Redeemed')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows gift card amount for valid unredeemed gift card', async () => {
|
||||
// Mock the gift card check endpoint to return a valid gift card
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
object: 'giftcard',
|
||||
id: 'gc_123',
|
||||
code: 'TEST-CODE-1234-5678',
|
||||
amount: 25.0,
|
||||
redeemed: false,
|
||||
created_at: 1640995200,
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for gift card amount to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/You've got \$25\.00!/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows provider name when matching preset is found', async () => {
|
||||
// Mock the gift card check endpoint
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
object: 'giftcard',
|
||||
id: 'gc_123',
|
||||
code: 'TEST-CODE-1234-5678',
|
||||
amount: 10.0,
|
||||
redeemed: false,
|
||||
created_at: 1640995200,
|
||||
}),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GiftCardRedeemDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
baseURL="https://ai.shakespeare.diy/v1"
|
||||
code="TEST-CODE-1234-5678"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Wait for provider name to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Shakespeare AI')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,357 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Gift, Check } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { generateSecretKey, nip19 } from 'nostr-tools';
|
||||
import { Dialog, DialogContent } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
interface GiftCardRedeemDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
baseURL: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
interface Giftcard {
|
||||
object: 'giftcard';
|
||||
id: string;
|
||||
code: string;
|
||||
amount: number;
|
||||
redeemed: boolean;
|
||||
created_at?: number;
|
||||
}
|
||||
|
||||
interface GiftcardRedemption {
|
||||
object: 'giftcard_redemption';
|
||||
amount: number;
|
||||
}
|
||||
|
||||
// No steps needed - everything on one screen!
|
||||
|
||||
/**
|
||||
* Gift Card Redemption Dialog
|
||||
*
|
||||
* This component handles the complete gift card redemption flow, including:
|
||||
* - Fetching gift card details from the provider API
|
||||
* - Multi-step wizard for login and provider setup
|
||||
* - Account switching before redemption
|
||||
* - Automatic provider matching against presets
|
||||
*
|
||||
* Flow:
|
||||
* 1. Check if gift card is valid (unauthenticated API call)
|
||||
* 2. Determine required steps based on user state:
|
||||
* - Not logged in? → Show login step
|
||||
* - Provider not configured? → Show provider setup step
|
||||
* - Ready to redeem? → Show preview with account switcher
|
||||
* 3. Redeem gift card and add credits to user's account
|
||||
* 4. Navigate to AI Settings to show new balance
|
||||
*
|
||||
* @param open - Whether the dialog is open
|
||||
* @param onOpenChange - Callback when dialog open state changes
|
||||
* @param baseURL - Provider base URL (e.g., https://ai.shakespeare.diy/v1)
|
||||
* @param code - Gift card code to redeem (e.g., XXXX-XXXX-XXXX-XXXX)
|
||||
*/
|
||||
export function GiftCardRedeemDialog({ open, onOpenChange, baseURL, code }: GiftCardRedeemDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { settings, setProvider } = useAISettings();
|
||||
const { config } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
const login = useLoginActions();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [generatedNsec, setGeneratedNsec] = useState<string>('');
|
||||
const [agreedToProviderTerms, setAgreedToProviderTerms] = useState(false);
|
||||
const hasInitialized = useRef(false);
|
||||
|
||||
// Find matching provider by baseURL
|
||||
const matchingProvider = settings.providers.find(p => p.baseURL === baseURL);
|
||||
const matchingPreset = AI_PROVIDER_PRESETS.find(p => p.baseURL === baseURL);
|
||||
|
||||
// Query gift card details without authentication
|
||||
const { data: giftcard, isLoading: isLoadingGiftcard, error: giftcardError } = useQuery({
|
||||
queryKey: ['giftcard-check', baseURL, code],
|
||||
queryFn: async (): Promise<Giftcard> => {
|
||||
const response = await fetch(`${baseURL}/credits/giftcards/check/${code}`);
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.error?.message || 'Failed to fetch gift card details');
|
||||
}
|
||||
return response.json();
|
||||
},
|
||||
enabled: open && !!baseURL && !!code,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
// Mutation for redeeming gift card
|
||||
const redeemMutation = useMutation({
|
||||
mutationFn: async (): Promise<GiftcardRedemption> => {
|
||||
if (!matchingProvider) {
|
||||
throw new Error('Provider not configured');
|
||||
}
|
||||
const ai = createAIClient(matchingProvider, user, config.corsProxy);
|
||||
return await ai.post('/credits/giftcards/redeem', {
|
||||
body: { code },
|
||||
}) as GiftcardRedemption;
|
||||
},
|
||||
onSuccess: (redemption) => {
|
||||
toast({
|
||||
title: '🎉 ' + t('giftCardRedeemed'),
|
||||
description: t('creditsAddedToAccount', { amount: formatCurrency(redemption.amount) }),
|
||||
});
|
||||
onOpenChange(false);
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: t('redemptionFailed'),
|
||||
description: error.message || t('failedToRedeemGiftCard'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Reset state and initialize when dialog opens
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
// Clear state when closing
|
||||
setGeneratedNsec('');
|
||||
setAgreedToProviderTerms(false);
|
||||
hasInitialized.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Only initialize once when dialog opens
|
||||
if (!hasInitialized.current) {
|
||||
hasInitialized.current = true;
|
||||
|
||||
// Auto-generate account if needed
|
||||
if (!user && !generatedNsec) {
|
||||
const secretKey = generateSecretKey();
|
||||
const nsec = nip19.nsecEncode(secretKey);
|
||||
setGeneratedNsec(nsec);
|
||||
login.nsec(nsec);
|
||||
}
|
||||
}
|
||||
}, [open, user, generatedNsec, login]);
|
||||
|
||||
const formatCurrency = (amount: number) => {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(amount);
|
||||
};
|
||||
|
||||
const handleRedeem = () => {
|
||||
// Check prerequisites
|
||||
if (!user) return;
|
||||
|
||||
// If provider not configured, add it first
|
||||
if (!matchingProvider && matchingPreset) {
|
||||
if (!agreedToProviderTerms) return;
|
||||
|
||||
const providerConfig = {
|
||||
id: matchingPreset.id,
|
||||
baseURL: matchingPreset.baseURL,
|
||||
nostr: matchingPreset.nostr || undefined,
|
||||
};
|
||||
|
||||
setProvider(providerConfig);
|
||||
}
|
||||
|
||||
// Redeem the gift card
|
||||
redeemMutation.mutate(undefined, {
|
||||
onSuccess() {
|
||||
// Invalidate AI credits query for this provider and user
|
||||
const providerId = matchingProvider?.id || matchingPreset?.id;
|
||||
if (providerId) {
|
||||
queryClient.invalidateQueries({ queryKey: ['ai-credits', user.pubkey, providerId] });
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Error state
|
||||
if (giftcardError) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8">
|
||||
<div className="mb-4">
|
||||
<Gift className="h-16 w-16 mx-auto text-muted-foreground opacity-50" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold mb-2">{t('invalidGiftCard')}</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{giftcardError instanceof Error ? giftcardError.message : t('giftCardNotFound')}
|
||||
</p>
|
||||
<Button onClick={() => onOpenChange(false)} className="mt-6">
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Loading state
|
||||
if (isLoadingGiftcard) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8 space-y-4">
|
||||
<Skeleton className="h-16 w-16 rounded-full mx-auto" />
|
||||
<Skeleton className="h-8 w-48 mx-auto" />
|
||||
<Skeleton className="h-4 w-64 mx-auto" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Already redeemed
|
||||
if (giftcard?.redeemed) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8">
|
||||
<div className="mb-4">
|
||||
<Check className="h-16 w-16 mx-auto text-green-500" />
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold mb-2">{t('alreadyRedeemed')}</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{t('giftCardAlreadyRedeemed')}
|
||||
</p>
|
||||
<Button onClick={() => onOpenChange(false)} className="mt-6">
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<div className="text-center py-8 space-y-6">
|
||||
{/* Animated gift icon */}
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="h-24 w-24 rounded-full bg-primary/10 animate-pulse" />
|
||||
</div>
|
||||
<div className="relative flex items-center justify-center">
|
||||
<Gift className="h-16 w-16 text-primary animate-bounce" style={{ animationDuration: '2s' }} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Title and amount */}
|
||||
<div>
|
||||
<h2 className="text-3xl font-bold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('youveGotCredits', { amount: giftcard && formatCurrency(giftcard.amount) })}
|
||||
</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{t('readyToAddCredits')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Provider info */}
|
||||
{matchingPreset && (
|
||||
<div className="bg-muted/50 rounded-lg p-4 text-sm">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<span className="text-muted-foreground">{t('provider')}:</span>
|
||||
<span className="font-medium">{matchingPreset.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Account selector - always show */}
|
||||
<div className="border rounded-lg p-4">
|
||||
<p className="text-xs text-muted-foreground mb-3 text-left">
|
||||
{t('redeemingToAccount')}
|
||||
</p>
|
||||
<LoginArea className="w-full" />
|
||||
</div>
|
||||
|
||||
{/* Provider ToS - only show if provider not configured */}
|
||||
{!matchingProvider && matchingPreset && (
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Checkbox
|
||||
id="agree-provider-terms"
|
||||
checked={agreedToProviderTerms}
|
||||
onCheckedChange={(checked) => setAgreedToProviderTerms(checked === true)}
|
||||
/>
|
||||
<label
|
||||
htmlFor="agree-provider-terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
{t('agreeToTermsOfService', { providerName: matchingPreset.name })}{' '}
|
||||
{matchingPreset.tosURL ? (
|
||||
<a
|
||||
href={matchingPreset.tosURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary underline hover:no-underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{t('termsOfService')}
|
||||
</a>
|
||||
) : (
|
||||
t('termsOfService')
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
onClick={handleRedeem}
|
||||
disabled={
|
||||
!user ||
|
||||
redeemMutation.isPending ||
|
||||
(!matchingProvider && !agreedToProviderTerms)
|
||||
}
|
||||
size="lg"
|
||||
className="w-full text-lg h-14 font-semibold"
|
||||
>
|
||||
{redeemMutation.isPending ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2" />
|
||||
{t('redeeming')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Gift className="h-5 w-5 mr-2" />
|
||||
{t('redeemNow')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="w-full"
|
||||
>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GitDialog } from './GitDialog';
|
||||
|
||||
// Mock the hooks
|
||||
const mockRefetch = vi.fn();
|
||||
const mockUseGitStatus = vi.fn();
|
||||
|
||||
const baseGitStatus = {
|
||||
isGitRepo: true,
|
||||
currentBranch: 'main',
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
totalCommits: 5,
|
||||
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
|
||||
latestCommit: {
|
||||
oid: 'abc123def456',
|
||||
message: 'Initial commit',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: Date.now() / 1000,
|
||||
},
|
||||
},
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
useGitStatus: () => mockUseGitStatus(),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useFS', () => ({
|
||||
useFS: vi.fn(() => ({
|
||||
fs: {},
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useToast', () => ({
|
||||
useToast: vi.fn(() => ({
|
||||
toast: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockUseGitSettings = vi.fn();
|
||||
|
||||
vi.mock('@/hooks/useGitSettings', () => ({
|
||||
useGitSettings: () => mockUseGitSettings(),
|
||||
}));
|
||||
|
||||
describe('GitDialog', () => {
|
||||
beforeEach(() => {
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: baseGitStatus,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
username: 'git',
|
||||
password: 'github-token',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('renders git dialog without repository information section', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Repository')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Repository Information')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows sync status when branch is published', () => {
|
||||
// Mock git status with published branch
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Sync Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Up to date')).toBeInTheDocument();
|
||||
expect(screen.getByText('Pull')).toBeInTheDocument();
|
||||
expect(screen.getByText('Push')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows clean working directory when no changes', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Working directory is clean')).toBeInTheDocument();
|
||||
expect(screen.getByText('No uncommitted changes')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('enables push button when there are commits ahead', () => {
|
||||
// Mock git status with commits ahead
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 2,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables push button when no commits ahead and branch is published', () => {
|
||||
// Mock git status with published branch and no commits ahead
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables push and disables pull when branch is not published', () => {
|
||||
// Mock git status with unpublished branch (has commits but no remote branch)
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: false,
|
||||
totalCommits: 5,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Sync Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Branch not published')).toBeInTheDocument();
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
|
||||
const pullButton = screen.getByText('Pull');
|
||||
expect(pullButton).toBeInTheDocument();
|
||||
expect(pullButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('does not show credentials warning when credentials are configured', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show warning when credentials are configured
|
||||
expect(screen.queryByText(/No credentials configured/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows credentials warning when no credentials are configured', () => {
|
||||
// Mock git settings with no credentials and mock git status with an https remote
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
},
|
||||
});
|
||||
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show warning when credentials are missing
|
||||
expect(screen.getByText(/You are not logged into github.com/)).toBeInTheDocument();
|
||||
expect(screen.getByText('log in')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { ReactNode } from 'react';
|
||||
import { GitSettingsProvider } from './GitSettingsProvider';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the config utils
|
||||
vi.mock('@/lib/configUtils', () => ({
|
||||
readGitSettings: vi.fn(),
|
||||
writeGitSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
// Test component that uses the hook
|
||||
function TestComponent() {
|
||||
const { settings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
|
||||
|
||||
const handleAdd = () => {
|
||||
const credential: GitCredential = {
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
};
|
||||
addCredential('https://github.com', credential);
|
||||
};
|
||||
|
||||
const handleUpdate = () => {
|
||||
updateCredential('https://github.com', { password: 'updated-token' });
|
||||
};
|
||||
|
||||
const handleRemove = () => {
|
||||
removeCredential('https://github.com');
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div data-testid="configured">{isConfigured ? 'configured' : 'not-configured'}</div>
|
||||
<div data-testid="count">{Object.keys(settings.credentials).length}</div>
|
||||
<button onClick={handleAdd}>Add GitHub</button>
|
||||
<button onClick={handleUpdate}>Update GitHub</button>
|
||||
<button onClick={handleRemove}>Remove GitHub</button>
|
||||
{settings.credentials['https://github.com'] && (
|
||||
<div data-testid="github-creds">
|
||||
{settings.credentials['https://github.com'].username}:
|
||||
{settings.credentials['https://github.com'].password}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TestWrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<TestApp>
|
||||
<GitSettingsProvider>
|
||||
{children}
|
||||
</GitSettingsProvider>
|
||||
</TestApp>
|
||||
);
|
||||
}
|
||||
|
||||
describe('GitSettingsProvider', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
|
||||
// Mock the read function to return default settings
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue({
|
||||
credentials: {},
|
||||
hostTokens: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('provides initial empty state', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('0');
|
||||
});
|
||||
});
|
||||
|
||||
it('can add credentials', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1');
|
||||
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:test-token');
|
||||
});
|
||||
|
||||
it('can update credentials', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
// First add a credential
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:test-token');
|
||||
|
||||
// Then update it
|
||||
fireEvent.click(screen.getByText('Update GitHub'));
|
||||
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:updated-token');
|
||||
});
|
||||
|
||||
it('can remove credentials', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
// First add a credential
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1');
|
||||
|
||||
// Then remove it
|
||||
fireEvent.click(screen.getByText('Remove GitHub'));
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('0');
|
||||
});
|
||||
|
||||
it('persists settings to VFS', async () => {
|
||||
const { writeGitSettings } = await import('@/lib/configUtils');
|
||||
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
|
||||
// Check that settings were saved to VFS
|
||||
await waitFor(() => {
|
||||
expect(writeGitSettings).toHaveBeenCalledWith(
|
||||
expect.anything(), // fs instance
|
||||
expect.objectContaining({
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
}
|
||||
}
|
||||
}),
|
||||
'/config' // configPath
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('loads settings from VFS', async () => {
|
||||
const settings = {
|
||||
credentials: {
|
||||
'https://gitlab.com': {
|
||||
username: 'git',
|
||||
password: 'gitlab-token',
|
||||
},
|
||||
},
|
||||
hostTokens: {},
|
||||
};
|
||||
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue(settings);
|
||||
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
|
||||
|
||||
interface GitSettingsProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: GitSettings = {
|
||||
credentials: {},
|
||||
hostTokens: {},
|
||||
};
|
||||
|
||||
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const { configPath } = useFSPaths();
|
||||
const [settings, setSettings] = useState<GitSettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// Initialize settings from VFS on mount
|
||||
useEffect(() => {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readGitSettings(fs, configPath);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Git settings:', error);
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
};
|
||||
|
||||
initializeSettings();
|
||||
}, [fs, configPath]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeGitSettings(fs, settings, configPath);
|
||||
} catch (error) {
|
||||
console.error('Failed to save Git settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized, configPath]);
|
||||
|
||||
const updateSettings = (newSettings: Partial<GitSettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
};
|
||||
|
||||
const addCredential = (origin: string, credential: GitCredential) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: {
|
||||
...prev.credentials,
|
||||
[origin]: credential,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const removeCredential = (origin: string) => {
|
||||
setSettings(prev => {
|
||||
const { [origin]: removed, ...rest } = prev.credentials;
|
||||
return {
|
||||
...prev,
|
||||
credentials: rest,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const updateCredential = (origin: string, credential: Partial<GitCredential>) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: {
|
||||
...prev.credentials,
|
||||
[origin]: {
|
||||
...prev.credentials[origin],
|
||||
...credential,
|
||||
},
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const addHostToken = (host: string, token: GitHostToken) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
hostTokens: {
|
||||
...prev.hostTokens,
|
||||
[host]: token,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const removeHostToken = (host: string) => {
|
||||
setSettings(prev => {
|
||||
const { [host]: removed, ...rest } = prev.hostTokens;
|
||||
return {
|
||||
...prev,
|
||||
hostTokens: rest,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const updateHostToken = (host: string, token: Partial<GitHostToken>) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
hostTokens: {
|
||||
...prev.hostTokens,
|
||||
[host]: {
|
||||
...prev.hostTokens[host],
|
||||
...token,
|
||||
},
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const isConfigured = Object.entries(settings.credentials).length > 0;
|
||||
|
||||
const contextValue: GitSettingsContextType = {
|
||||
settings,
|
||||
updateSettings,
|
||||
addCredential,
|
||||
removeCredential,
|
||||
updateCredential,
|
||||
addHostToken,
|
||||
removeHostToken,
|
||||
updateHostToken,
|
||||
isConfigured,
|
||||
isInitialized,
|
||||
};
|
||||
|
||||
return (
|
||||
<GitSettingsContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</GitSettingsContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GitStatusIndicator } from './GitStatusIndicator';
|
||||
|
||||
// Mock the useGitStatus hook
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
useGitStatus: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
|
||||
describe('GitStatusIndicator', () => {
|
||||
it('should not render when not in a git repo', () => {
|
||||
vi.mocked(useGitStatus).mockReturnValue({
|
||||
data: {
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
isGitRepo: false,
|
||||
},
|
||||
} as unknown as ReturnType<typeof useGitStatus>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<GitStatusIndicator projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('should not render when no uncommitted changes', () => {
|
||||
vi.mocked(useGitStatus).mockReturnValue({
|
||||
data: {
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
isGitRepo: true,
|
||||
},
|
||||
} as unknown as ReturnType<typeof useGitStatus>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<GitStatusIndicator projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('should render yellow dot when there are uncommitted changes', () => {
|
||||
vi.mocked(useGitStatus).mockReturnValue({
|
||||
data: {
|
||||
hasUncommittedChanges: true,
|
||||
changedFiles: ['file1.txt', 'file2.txt'],
|
||||
isGitRepo: true,
|
||||
},
|
||||
} as unknown as ReturnType<typeof useGitStatus>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<GitStatusIndicator projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const indicator = container.firstChild as HTMLElement;
|
||||
expect(indicator).toBeTruthy();
|
||||
expect(indicator.className).toContain('bg-yellow-500');
|
||||
expect(indicator.className).toContain('rounded-full');
|
||||
expect(indicator.title).toBe('2 uncommitted changes');
|
||||
});
|
||||
|
||||
it('should handle singular file count in tooltip', () => {
|
||||
vi.mocked(useGitStatus).mockReturnValue({
|
||||
data: {
|
||||
hasUncommittedChanges: true,
|
||||
changedFiles: ['file1.txt'],
|
||||
isGitRepo: true,
|
||||
},
|
||||
} as unknown as ReturnType<typeof useGitStatus>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<GitStatusIndicator projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const indicator = container.firstChild as HTMLElement;
|
||||
expect(indicator.title).toBe('1 uncommitted change');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface GitStatusIndicatorProps {
|
||||
projectId: string | null;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function GitStatusIndicator({ projectId, className }: GitStatusIndicatorProps) {
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
|
||||
// Only show the indicator if we're in a git repo and have uncommitted changes
|
||||
if (!gitStatus?.isGitRepo || !gitStatus?.hasUncommittedChanges) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"w-2 h-2 bg-yellow-500 rounded-full animate-pulse",
|
||||
"shadow-sm shadow-yellow-500/50",
|
||||
className
|
||||
)}
|
||||
title={`${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { JSRuntimeContext, type JSRuntimeContextType } from '@/contexts/JSRuntimeContext';
|
||||
import type { JSRuntime } from '@/lib/JSRuntime';
|
||||
|
||||
interface JSRuntimeProviderProps {
|
||||
children: ReactNode;
|
||||
runtime: JSRuntime;
|
||||
}
|
||||
|
||||
export function JSRuntimeProvider({ children, runtime }: JSRuntimeProviderProps) {
|
||||
const contextValue: JSRuntimeContextType = { runtime };
|
||||
|
||||
return (
|
||||
<JSRuntimeContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</JSRuntimeContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { LanguagePicker } from './LanguagePicker';
|
||||
|
||||
describe('LanguagePicker', () => {
|
||||
it('renders language picker with default English selection', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<LanguagePicker />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show the trigger button
|
||||
expect(screen.getByRole('combobox')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows language options when opened', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<LanguagePicker />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Click to open the dropdown
|
||||
const trigger = screen.getByRole('combobox');
|
||||
fireEvent.click(trigger);
|
||||
|
||||
// Should show all language options (using getAllByText since there might be duplicates)
|
||||
expect(screen.getAllByText('System').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('English').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('Portuguese').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('Chinese').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('displays flag emojis for languages', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<LanguagePicker />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Click to open the dropdown
|
||||
const trigger = screen.getByRole('combobox');
|
||||
fireEvent.click(trigger);
|
||||
|
||||
// Should show flag emojis (using getAllByText since there might be duplicates)
|
||||
expect(screen.getAllByText('🇺🇸').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('🇧🇷').length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText('🇨🇳').length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Languages } from 'lucide-react';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
interface LanguagePickerProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function LanguagePicker({ className }: LanguagePickerProps) {
|
||||
const { t } = useTranslation();
|
||||
const { config, updateConfig } = useAppContext();
|
||||
|
||||
const handleLanguageChange = (language: string) => {
|
||||
updateConfig((prev) => ({ ...prev, language: language === 'system' ? undefined : language }));
|
||||
};
|
||||
|
||||
return (
|
||||
<Select value={config.language ?? 'system'} onValueChange={handleLanguageChange}>
|
||||
<SelectTrigger className={className}>
|
||||
<div className="flex items-center gap-2">
|
||||
<SelectValue />
|
||||
</div>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="system">
|
||||
<div className="flex items-center gap-2">
|
||||
<Languages className="h-4 w-4" />
|
||||
{t('systemLanguage')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="en">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">🇺🇸</span>
|
||||
{t('english')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="pt">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">🇧🇷</span>
|
||||
{t('portuguese')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="zh">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">🇨🇳</span>
|
||||
{t('chinese')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="ha">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">🇳🇬</span>
|
||||
{t('hausa')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="yo">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">🇳🇬</span>
|
||||
{t('yoruba')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="ig">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">🇳🇬</span>
|
||||
{t('igbo')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Mock QRCode
|
||||
vi.mock('qrcode', () => ({
|
||||
default: {
|
||||
toDataURL: vi.fn().mockResolvedValue('data:image/png;base64,mock-qr-code'),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock WebLN
|
||||
const mockWebLN = {
|
||||
enable: vi.fn().mockResolvedValue(undefined),
|
||||
sendPayment: vi.fn().mockResolvedValue({ preimage: 'mock-preimage' }),
|
||||
};
|
||||
|
||||
// We need to import the component after mocking
|
||||
const { CreditsDialog } = await import('./CreditsDialog');
|
||||
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
nostr: false,
|
||||
};
|
||||
|
||||
describe('Lightning Payment', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Reset WebLN mock
|
||||
Object.defineProperty(window, 'webln', {
|
||||
value: undefined,
|
||||
writable: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows QR code for Lightning payment', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show the normal form initially
|
||||
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows WebLN button when available', async () => {
|
||||
// Mock WebLN availability
|
||||
Object.defineProperty(window, 'webln', {
|
||||
value: mockWebLN,
|
||||
writable: true,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show the normal form initially
|
||||
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays copy invoice button', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show the normal form initially
|
||||
expect(screen.getByText('Payment Method')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,339 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Server, Trash2, Check, Plus, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useMCPServerStatus } from '@/hooks/useMCPServerStatus';
|
||||
import type { MCPServer } from '@/contexts/AISettingsContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
function MCPConnectionStatus({ server }: { server: MCPServer }) {
|
||||
const status = useMCPServerStatus(server);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 ml-auto mr-2">
|
||||
<div
|
||||
className={cn(
|
||||
'h-2 w-2 rounded-full',
|
||||
status === 'connected' && 'bg-green-500',
|
||||
status === 'offline' && 'bg-red-500',
|
||||
status === 'checking' && 'bg-yellow-500 animate-pulse'
|
||||
)}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground capitalize">
|
||||
{status}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface HeadersEditorProps {
|
||||
headers: Record<string, string> | undefined;
|
||||
onChange: (headers: Record<string, string> | undefined) => void;
|
||||
}
|
||||
|
||||
function HeadersEditor({ headers, onChange }: HeadersEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const [newHeaderName, setNewHeaderName] = useState('');
|
||||
const [newHeaderValue, setNewHeaderValue] = useState('');
|
||||
|
||||
const headerEntries = Object.entries(headers || {});
|
||||
|
||||
const handleAddHeader = () => {
|
||||
if (!newHeaderName.trim() || !newHeaderValue.trim()) return;
|
||||
|
||||
const updatedHeaders = {
|
||||
...(headers || {}),
|
||||
[newHeaderName.trim()]: newHeaderValue.trim(),
|
||||
};
|
||||
|
||||
onChange(updatedHeaders);
|
||||
setNewHeaderName('');
|
||||
setNewHeaderValue('');
|
||||
};
|
||||
|
||||
const handleRemoveHeader = (name: string) => {
|
||||
const updatedHeaders = { ...(headers || {}) };
|
||||
delete updatedHeaders[name];
|
||||
|
||||
// If no headers left, set to undefined
|
||||
onChange(Object.keys(updatedHeaders).length > 0 ? updatedHeaders : undefined);
|
||||
};
|
||||
|
||||
const handleUpdateHeader = (oldName: string, newName: string, newValue: string) => {
|
||||
const updatedHeaders = { ...(headers || {}) };
|
||||
delete updatedHeaders[oldName];
|
||||
updatedHeaders[newName] = newValue;
|
||||
onChange(updatedHeaders);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Label>{t('mcpServerHeaders')}</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('mcpServerHeadersDescription')}
|
||||
</p>
|
||||
|
||||
{/* Existing Headers */}
|
||||
{headerEntries.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{headerEntries.map(([name, value]) => (
|
||||
<div key={name} className="flex gap-2">
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => handleUpdateHeader(name, e.target.value, value)}
|
||||
placeholder="Header name"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => handleUpdateHeader(name, name, e.target.value)}
|
||||
placeholder="Header value"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleRemoveHeader(name)}
|
||||
className="shrink-0"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add New Header */}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={newHeaderName}
|
||||
onChange={(e) => setNewHeaderName(e.target.value)}
|
||||
placeholder="Header name (e.g., Authorization)"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={newHeaderValue}
|
||||
onChange={(e) => setNewHeaderValue(e.target.value)}
|
||||
placeholder="Header value"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleAddHeader}
|
||||
disabled={!newHeaderName.trim() || !newHeaderValue.trim()}
|
||||
className="shrink-0"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MCPServersSection() {
|
||||
const { t } = useTranslation();
|
||||
const { settings, setMCPServer, removeMCPServer } = useAISettings();
|
||||
const { toast } = useToast();
|
||||
const [serverName, setServerName] = useState('');
|
||||
const [serverUrl, setServerUrl] = useState('');
|
||||
const [serverHeaders, setServerHeaders] = useState<Record<string, string> | undefined>(undefined);
|
||||
const [serverType] = useState<'streamable-http'>('streamable-http'); // Only streamable-http is supported
|
||||
|
||||
const mcpServers = settings.mcpServers || {};
|
||||
const serverEntries = Object.entries(mcpServers);
|
||||
|
||||
const handleAddServer = () => {
|
||||
if (!serverName.trim() || !serverUrl.trim()) return;
|
||||
|
||||
if (mcpServers[serverName.trim()]) {
|
||||
toast({
|
||||
title: t('error'),
|
||||
description: t('mcpServerAddFailed'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const newServer: MCPServer = {
|
||||
type: serverType,
|
||||
url: serverUrl.trim(),
|
||||
headers: serverHeaders,
|
||||
};
|
||||
|
||||
setMCPServer(serverName.trim(), newServer);
|
||||
|
||||
toast({
|
||||
title: t('mcpServerAdded'),
|
||||
description: t('mcpServerAddedDescription', { name: serverName.trim() }),
|
||||
});
|
||||
|
||||
setServerName('');
|
||||
setServerUrl('');
|
||||
setServerHeaders(undefined);
|
||||
};
|
||||
|
||||
const handleRemoveServer = (name: string) => {
|
||||
removeMCPServer(name);
|
||||
|
||||
toast({
|
||||
title: t('mcpServerDeleted'),
|
||||
description: t('mcpServerDeletedDescription', { name }),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Divider */}
|
||||
<Separator className="my-6" />
|
||||
|
||||
{/* MCP Servers Header */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Server className="h-5 w-5 text-primary" />
|
||||
<h3 className="text-lg font-semibold">{t('mcpServers')}</h3>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('mcpServersDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Configured MCP Servers List */}
|
||||
{serverEntries.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{serverEntries.map(([name, server]) => (
|
||||
<Accordion key={name} type="single" collapsible className="w-full">
|
||||
<AccordionItem value={name} className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2 w-full mr-3">
|
||||
<Server size={16} className="text-primary" />
|
||||
<span className="font-medium">{name}</span>
|
||||
<MCPConnectionStatus server={server} />
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${name}-type`}>{t('mcpServerType')}</Label>
|
||||
<Select value={server.type} disabled>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${name}-url`}>{t('mcpServerUrl')}</Label>
|
||||
<Input
|
||||
id={`${name}-url`}
|
||||
value={server.url}
|
||||
onChange={(e) => setMCPServer(name, { ...server, url: e.target.value })}
|
||||
placeholder="https://example.com/mcp"
|
||||
/>
|
||||
</div>
|
||||
<HeadersEditor
|
||||
headers={server.headers}
|
||||
onChange={(headers) => setMCPServer(name, { ...server, headers })}
|
||||
/>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveServer(name)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
{t('delete')}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Alert>
|
||||
<AlertDescription className="text-sm">
|
||||
{t('noMcpServersConfigured')}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Add New MCP Server */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="add-server" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
<span className="text-sm font-medium">{t('addMcpServer')}</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('mcpServerDescription')}
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-server-name">{t('mcpServerName')}</Label>
|
||||
<Input
|
||||
id="new-server-name"
|
||||
placeholder="e.g., my-mcp-server"
|
||||
value={serverName}
|
||||
onChange={(e) => setServerName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-server-type">{t('mcpServerType')}</Label>
|
||||
<Select value={serverType} disabled>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Only Streamable HTTP transport is currently supported
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-server-url">{t('mcpServerUrl')}</Label>
|
||||
<Input
|
||||
id="new-server-url"
|
||||
placeholder="https://example.com/mcp"
|
||||
value={serverUrl}
|
||||
onChange={(e) => setServerUrl(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<HeadersEditor
|
||||
headers={serverHeaders}
|
||||
onChange={setServerHeaders}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleAddServer}
|
||||
disabled={!serverName.trim() || !serverUrl.trim() || !!mcpServers[serverName.trim()]}
|
||||
className="gap-2 w-full"
|
||||
>
|
||||
<Check className="h-4 w-4" />
|
||||
{t('add')}
|
||||
</Button>
|
||||
{mcpServers[serverName.trim()] && (
|
||||
<p className="text-sm text-destructive">
|
||||
A server with this name already exists
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
);
|
||||
}
|
||||