Compare commits

...

22 Commits

Author SHA1 Message Date
42cc96a0e3
ref: remove NLP
improve: about page
2025-01-20 04:31:10 +08:00
f7de462a28
fix: unable to properly segment raw TLD data
feat: searchbox's value changes while selecting suggestion
2025-01-20 03:03:28 +08:00
de7c5990bb add: energy score into inferencing 2024-10-13 18:33:49 +08:00
1acb0a7f11 ref: re-enable backend api, remove deprecated code 2024-10-13 18:10:44 +08:00
a15694ada8 fix: import path in start script 2024-10-13 18:01:56 +08:00
43da50f37c ref: project name, start script 2024-10-13 17:53:27 +08:00
bf92c349fc update: from dev branch 2024-10-13 16:23:40 +08:00
5bebd5607a add: LICENSE 2024-10-13 16:23:05 +08:00
a0644eb470
update: faster tokenizer 2024-10-07 02:02:20 +08:00
ea8b503653
ref: format 2024-10-07 01:41:21 +08:00
76c4472de1
update: bytes <-> unicode for qwen tokenizer 2024-10-07 01:41:09 +08:00
81fe88ade7
add: transform func for Unicode/ Bytes in Qwen tokenizer 2024-09-28 23:13:14 +08:00
e8adbab368
fix: lib functions related to URL/links 2024-09-28 22:20:27 +08:00
f7ab85a108
add: basic infra for new NLU system 2024-09-28 21:56:07 +08:00
973b926544
add: embedding 2024-09-22 21:09:19 +08:00
668a88e917
ref: use bun tester 2024-09-22 20:39:49 +08:00
cf6c69e61b
update: tokenizer 2024-09-22 20:39:07 +08:00
5abe7521ba
add: tokenizer and getEmbedding
remove: model
2024-09-22 20:14:09 +08:00
d97e678206
ref: format 2024-09-21 21:31:08 +08:00
35f90b42d9
merge: update from dev 2024-09-21 21:14:33 +08:00
Alikia2x
aa6b06147d merge: branch dev into dev-nlp 2024-06-17 01:28:52 +08:00
Alikia2x
d418b15978 test: text-classification 2024-04-10 15:55:18 +08:00
101 changed files with 7215 additions and 2247 deletions

1
.prettierignore Normal file
View File

@ -0,0 +1 @@
public/*

View File

@ -1,5 +1,5 @@
{
"useTabs": false,
"useTabs": true,
"tabWidth": 4,
"trailingComma": "none",
"singleQuote": false,

661
LICENSE Normal file
View File

@ -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/>.

View File

@ -1,11 +1,11 @@
import { Express } from "express";
import { completeGoogle } from "search-engine-autocomplete";
import { completeGoogle } from "@alikia/search-complete";
export function configureBackendRoutes(app: Express) {
app.get('/api/v1/suggestion', async (req, res) => {
app.get("/api/v1/suggestion", async (req, res) => {
const query = req.query.q as string;
const t = parseInt(req.query.t as string || "0") || null;
let language = req.query.l as string || 'en-US';
const t = parseInt((req.query.t as string) || "0") || null;
let language = (req.query.l as string) || "en-US";
try {
const data = await completeGoogle(query, language);
@ -13,10 +13,10 @@ export function configureBackendRoutes(app: Express) {
res.json({ ...data, time: t });
} catch (error) {
// logger.error({ type: "onesearch_search_autocomplete_error", error: error.message });
res.status(500).json({ error: 'Internal Server Error' });
res.status(500).json({ error: "Internal Server Error" });
}
});
app.get("/api/v1/ping", async (_, res) => {
res.status(200).json({ message: "pong" });
})
});
}

BIN
bun.lockb

Binary file not shown.

View File

@ -11,9 +11,19 @@ export default function Background() {
return (
<div>
{darkMode ? (
<BackgroundContainer src="rgb(23,25,29)" isFocus={isFocus} onClick={() => setFocus(false)} darkMode={darkMode}/>
<BackgroundContainer
src="rgb(23,25,29)"
isFocus={isFocus}
onClick={() => setFocus(false)}
darkMode={darkMode}
/>
) : (
<BackgroundContainer src="white" isFocus={isFocus} onClick={() => setFocus(false)} darkMode={darkMode}/>
<BackgroundContainer
src="white"
isFocus={isFocus}
onClick={() => setFocus(false)}
darkMode={darkMode}
/>
)}
</div>
);

View File

@ -24,7 +24,11 @@ export default function BackgroundContainer(props: {
src={props.src}
className={
"w-full h-full fixed object-cover inset-0 duration-200 z-0 " +
(props.isFocus ? (settings.bgBlur ? "blur-lg scale-110" : "brightness-50 scale-105") : "")
(props.isFocus
? settings.bgBlur
? "blur-lg scale-110"
: "brightness-50 scale-105"
: "")
}
alt="background"
onClick={props.onClick}

View File

@ -0,0 +1,87 @@
import { SuggestionItem } from "global";
import PlainSearch from "./plainSearch";
import LinkSuggestion from "./link";
import PlainText from "./plainText";
export default function SuggestionComponent({
s,
i,
selected,
devMode,
engineName,
t
}: {
s: SuggestionItem;
i: number;
selected: number;
devMode: boolean;
engineName: string;
t: any;
}) {
if (s.suggestion.trim() === "") return null;
if (s.type === "default") {
return (
<PlainSearch key={i} query={s.suggestion} selected={i == selected}>
{s.suggestion}&nbsp;
<span className="text-zinc-700 dark:text-zinc-400 text-sm">
{t("search.search-help-text", { engine: engineName })}
</span>
{devMode && (
<span className="absolute text-zinc-700 dark:text-zinc-400 text-sm leading-10 h-10 right-2">
{s.relevance}
</span>
)}
</PlainSearch>
);
} else if (s.type === "QUERY") {
return (
<PlainSearch key={i} query={s.suggestion} selected={i == selected}>
{s.suggestion}
{devMode && (
<span className="absolute text-zinc-700 dark:text-zinc-400 text-sm leading-10 h-10 right-2">
{s.relevance}
</span>
)}
</PlainSearch>
);
} else if (s.type === "NAVIGATION" || s.type === "default-link" || s.type === "link") {
return (
<LinkSuggestion key={i} query={s.suggestion} selected={i == selected}>
{s.prompt && <span className="text-zinc-700 dark:text-zinc-400">{s.prompt}</span>}
{s.suggestion}
{devMode && (
<span className="absolute text-zinc-700 dark:text-zinc-400 text-sm leading-10 h-10 right-2">
{s.relevance}
</span>
)}
</LinkSuggestion>
);
} else if (s.type === "text") {
return (
<PlainText key={i} selected={i == selected}>
{s.prompt && <span className="text-zinc-700 dark:text-zinc-400">{s.prompt}</span>}
<p>{s.suggestion}</p>
{devMode && (
<span className="bottom-0 absolute text-zinc-700 dark:text-zinc-400 text-sm leading-10 h-10 right-2">
{s.relevance}
</span>
)}
</PlainText>
);
} else if (s.type === "inpage-link") {
return (
<LinkSuggestion key={i} query={s.suggestion} selected={i == selected} inPage={true}>
{s.prompt && <span className="text-zinc-700 dark:text-zinc-400">{s.prompt}</span>}
{s.suggestion}
{devMode && (
<span className="absolute text-zinc-700 dark:text-zinc-400 text-sm leading-10 h-10 right-2">
{s.relevance}
</span>
)}
</LinkSuggestion>
);
}
return null;
}

View File

@ -1,11 +1,11 @@
import { settingsType, suggestionItem } from "global";
import { settingsType, SuggestionItem } from "global";
import copyToClipboard from "lib/copy";
import { normalizeURL } from "lib/normalizeURL";
import search from "lib/search";
export default function (
index: number,
suggestion: suggestionItem[],
suggestion: SuggestionItem[],
_query: string,
settings: settingsType,
searchBoxRef: React.RefObject<HTMLInputElement>

View File

@ -1,10 +1,10 @@
import { suggestionItem } from "global";
import { SuggestionItem } from "global";
import { findClosestDateIndex } from "lib/weather/getCurrentWeather";
import { getLocationNative } from "lib/weather/getLocation";
import { getWeather } from "lib/weather/getWeather";
import { WMOCodeTable } from "lib/weather/wmocode";
type UpdateSuggestionFunction = (data: suggestionItem[]) => void;
type UpdateSuggestionFunction = (data: SuggestionItem[]) => void;
export function handleNLUResult(result: any, updateSuggestion: UpdateSuggestionFunction) {
if (result.intent == "weather.summary") {
@ -13,9 +13,7 @@ export function handleNLUResult(result: any, updateSuggestion: UpdateSuggestionF
if (data instanceof GeolocationCoordinates) {
getWeather(data.latitude, data.longitude).then((weather) => {
console.log(weather["hourly"]);
let hourIndex = findClosestDateIndex(
weather["hourly"]["time"]
);
let hourIndex = findClosestDateIndex(weather["hourly"]["time"]);
let temp = weather["hourly"]["apparent_temperature"][hourIndex];
let weatherCode = weather["hourly"]["weather_code"][hourIndex];
console.log(temp, weatherCode, hourIndex);

View File

@ -1,28 +1,23 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef } from "react";
import SuggestionBox from "./suggestionBox";
import { queryAtom } from "lib/state/query";
import { suggestionItem, suggestionsResponse } from "global";
import { SuggestionItem, SuggestionsResponse } from "global";
import getSearchEngineName from "lib/onesearch/getSearchEngineName";
import PlainSearch from "./plainSearch";
import { suggestionAtom } from "lib/state/suggestion";
import validLink from "lib/url/validLink";
import LinkSuggestion from "./link";
import { selectedSuggestionAtom } from "lib/state/suggestionSelection";
import { settingsAtom } from "lib/state/settings";
import PlainText from "./plainText";
import { sendError } from "lib/telemetering/sendError";
import { handleNLUResult } from "./handleNLUResult";
import { sendError } from "lib/feedback/sendError";
import { useAtom, useAtomValue } from "jotai";
import i18next from "i18next";
import { useTranslation } from "react-i18next";
import { keywordSuggestion } from "lib/onesearch/keywordSuggestion";
import { NLUType } from "lib/nlp/load";
import { searchboxLastInputAtom } from "lib/state/searchboxLastInput"
import SuggestionComponent from "./SuggestionItem.tsx";
export default function OneSearch() {
const [suggestion, setFinalSuggetsion] = useAtom(suggestionAtom);
const [manager, setManager] = useState(null);
const [NLUModel, setNLUModel] = useState<NLUType>();
const [NLUModelLoaded, setNLUModelLoaded] = useState(false);
const [suggestion, setFinalSuggestion] = useAtom(suggestionAtom);
const lastInput = useAtomValue(searchboxLastInputAtom);
const lastRequestTimeRef = useRef(0);
const selected = useAtomValue(selectedSuggestionAtom);
const settings = useAtomValue(settingsAtom);
@ -41,9 +36,9 @@ export default function OneSearch() {
}
fetch(`/api/v1/suggestion?q=${query}&l=${lang}&t=${time}&engine=${engine}`)
.then((res) => res.json())
.then((data: suggestionsResponse) => {
.then((data: SuggestionsResponse) => {
try {
const suggestionToUpdate: suggestionItem[] = data.suggestions;
const suggestionToUpdate: SuggestionItem[] = data.suggestions;
if (data.time > lastRequestTimeRef.current) {
cleanSuggestion("NAVIGATION", "QUERY");
lastRequestTimeRef.current = data.time;
@ -59,10 +54,10 @@ export default function OneSearch() {
// Handle fetch error
sendError(error);
});
}, [query]);
}, [lastInput]);
function updateSuggestion(data: suggestionItem[]) {
setFinalSuggetsion((cur: suggestionItem[]) => {
function updateSuggestion(data: SuggestionItem[]) {
setFinalSuggestion((cur: SuggestionItem[]) => {
const types: string[] = [];
for (const sug of data) {
if (!types.includes(sug.type)) types.push(sug.type);
@ -79,7 +74,7 @@ export default function OneSearch() {
}
function cleanSuggestion(...types: string[]) {
setFinalSuggetsion((suggestion: suggestionItem[]) => {
setFinalSuggestion((suggestion: SuggestionItem[]) => {
return suggestion.filter((item) => {
return !types.includes(item.type);
});
@ -87,25 +82,7 @@ export default function OneSearch() {
}
useEffect(() => {
(async function () {
const NLU = await import("lib/nlp/load");
const mainNLUModel = new NLU.NLU();
setNLUModel(mainNLUModel);
setNLUModelLoaded(true);
})();
}, []);
useEffect(() => {
if (NLUModel === null || NLUModel === undefined) {
return;
}
NLUModel.init().then((nlu: typeof NLUModel) => {
setManager(nlu.manager);
});
}, [NLUModelLoaded]);
useEffect(() => {
cleanSuggestion("default-link", "default", "text", "link");
cleanSuggestion("default-link", "default", "text", "link", "inpage-link");
if (validLink(query)) {
updateSuggestion([
{
@ -125,102 +102,24 @@ export default function OneSearch() {
}
]);
}
if (keywordSuggestion(query) !== null) {
updateSuggestion([keywordSuggestion(query)!]);
}
if (manager != null) {
// @ts-ignore
manager.process(query).then((result) => {
console.log(result);
handleNLUResult(result, updateSuggestion);
});
}
}, [query, engineName]);
}, [lastInput, engineName]);
return (
<SuggestionBox>
{suggestion.map((s, i) => {
if (s.suggestion.trim() === "") return;
if (s.type === "default") {
return (
<PlainSearch key={i} query={s.suggestion} selected={i == selected}>
{s.suggestion}&nbsp;
<span className="text-zinc-700 dark:text-zinc-400 text-sm">
{t("search.search-help-text", { engine: engineName })}
</span>
{devMode && (
<span className="absolute text-zinc-700 dark:text-zinc-400 text-sm leading-10 h-10 right-2">
{s.relevance}
</span>
)}
</PlainSearch>
);
} else if (s.type === "QUERY") {
return (
<PlainSearch key={i} query={s.suggestion} selected={i == selected}>
{s.suggestion}
{devMode && (
<span className="absolute text-zinc-700 dark:text-zinc-400 text-sm leading-10 h-10 right-2">
{s.relevance}
</span>
)}
</PlainSearch>
);
} else if (
s.type === "NAVIGATION" ||
s.type === "default-link" ||
s.type === "link"
) {
return (
<LinkSuggestion key={i} query={s.suggestion} selected={i == selected}>
{s.prompt && (
<span className="text-zinc-700 dark:text-zinc-400">{s.prompt}</span>
)}
{s.suggestion}
{devMode && (
<span className="absolute text-zinc-700 dark:text-zinc-400 text-sm leading-10 h-10 right-2">
{s.relevance}
</span>
)}
</LinkSuggestion>
);
} else if (s.type === "text") {
return (
<PlainText key={i} selected={i == selected}>
{s.prompt && (
<span className="text-zinc-700 dark:text-zinc-400">{s.prompt}</span>
)}
<p>{s.suggestion}</p>
{devMode && (
<span className="bottom-0 absolute text-zinc-700 dark:text-zinc-400 text-sm leading-10 h-10 right-2">
{s.relevance}
</span>
)}
</PlainText>
);
} else if (s.type === "inpage-link") {
return (
<LinkSuggestion
{suggestion.map((s, i) => (
<SuggestionComponent
key={i}
query={s.suggestion}
selected={i == selected}
inPage={true}
>
{s.prompt && (
<span className="text-zinc-700 dark:text-zinc-400">{s.prompt}</span>
)}
{s.suggestion}
{devMode && (
<span className="absolute text-zinc-700 dark:text-zinc-400 text-sm leading-10 h-10 right-2">
{s.relevance}
</span>
)}
</LinkSuggestion>
);
}
})}
s={s}
i={i}
selected={selected}
devMode={devMode}
engineName={engineName}
t={t}
/>
))}
</SuggestionBox>
);
}

View File

@ -2,7 +2,11 @@ import { useAtomValue } from "jotai";
import search from "lib/search";
import { settingsAtom } from "lib/state/settings";
export default function PlainSearch(props: { children: React.ReactNode; query: string; selected: boolean }) {
export default function PlainSearch(props: {
children: React.ReactNode;
query: string;
selected: boolean;
}) {
const settings = useAtomValue(settingsAtom);
const engine = settings.searchEngines[settings.currentSearchEngine];
const newTab = settings.searchInNewTab;
@ -18,8 +22,7 @@ export default function PlainSearch(props: { children: React.ReactNode; query: s
{props.children}
</div>
);
}
else {
} else {
return (
<div
className={`relative w-full h-10 leading-10 bg-zinc-100 hover:bg-zinc-300

View File

@ -1,6 +1,8 @@
export default function Suggestion(props: { children: React.ReactNode }) {
return (
<div dangerouslySetInnerHTML={{ __html: `<p>${props.children}</p>` as string }} className={`relative w-full h-10 leading-10 bg-zinc-100 hover:bg-zinc-300 dark:bg-zinc-800 hover:dark:bg-zinc-700 px-5 z-10 cursor-pointer duration-100`}>
</div>
<div
dangerouslySetInnerHTML={{ __html: `<p>${props.children}</p>` as string }}
className={`relative w-full h-10 leading-10 bg-zinc-100 hover:bg-zinc-300 dark:bg-zinc-800 hover:dark:bg-zinc-700 px-5 z-10 cursor-pointer duration-100`}
></div>
);
}

View File

@ -142,7 +142,12 @@ const PickerList = React.forwardRef<HTMLDivElement, PickerListProps>((props, ref
const { selected, selectionOnChange, selectionItems, toggleDisplay } = props;
return createPortal(
<div className="absolute w-screen h-screen" onClick={()=>{toggleDisplay(false)}}>
<div
className="absolute w-screen h-screen"
onClick={() => {
toggleDisplay(false);
}}
>
<div
ref={ref}
className="overflow-y-auto fixed w-fit text-black dark:text-white opacity-0 duration-200

View File

@ -6,12 +6,14 @@ import { selectedSuggestionAtom } from "lib/state/suggestionSelection";
import handleEnter from "lib/onesearch/handleEnter";
import { suggestionAtom } from "lib/state/suggestion";
import { useTranslation } from "react-i18next";
import { searchboxLastInputAtom } from "lib/state/searchboxLastInput";
export default function Search(props: { onFocus: () => void }) {
const { t } = useTranslation();
const settings = useAtomValue(settingsAtom);
const [query, setQuery] = useAtom(queryAtom);
const [selectedSuggestion, setSelected] = useAtom(selectedSuggestionAtom);
const [_, setLastInput] = useAtom(searchboxLastInputAtom)
const suggestions = useAtomValue(suggestionAtom);
const searchBoxRef = useRef<HTMLInputElement>(null);
@ -25,11 +27,21 @@ export default function Search(props: { onFocus: () => void }) {
} else if (e.key == "ArrowUp") {
e.preventDefault();
const len = suggestions.length;
setSelected((selectedSuggestion - 1 + len) % len);
const lastSelectedIndex = (selectedSuggestion - 1 + len) % len;
const lastSuggeston = suggestions[lastSelectedIndex];
setSelected(lastSelectedIndex);
if (["QUERY", "NAVIGATION", "default"].includes(lastSuggeston.type)) {
setQuery(lastSuggeston.suggestion);
}
} else if (e.key == "ArrowDown") {
e.preventDefault();
const len = suggestions.length;
setSelected((selectedSuggestion + 1) % len);
const nextSelectedIndex = (selectedSuggestion + 1 + len) % len;
const nextSuggeston = suggestions[nextSelectedIndex];
setSelected(nextSelectedIndex);
if (["QUERY", "NAVIGATION", "default"].includes(nextSuggeston.type)) {
setQuery(nextSuggeston.suggestion);
}
}
}
@ -48,11 +60,10 @@ export default function Search(props: { onFocus: () => void }) {
placeholder={t("search.placeholder")}
onFocus={props.onFocus}
onKeyDown={handleKeydown}
onChange={(e) =>
setQuery(() => {
return e.target.value;
})
}
onChange={(e) => {
setLastInput(new Date().getTime());
setQuery(() => e.target.value);
}}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"

View File

@ -3,10 +3,10 @@ import { selectionType } from "./picker";
export type selectedOnChange = (target: selectionType) => void;
export default function SelectionItem(props: {key: selectionType, children: ReactNode, onChange: selectedOnChange}){
return (
<div onClick={() => props.onChange(props.key)}>
{props.children}
</div>
)
export default function SelectionItem(props: {
key: selectionType;
children: ReactNode;
onChange: selectedOnChange;
}) {
return <div onClick={() => props.onChange(props.key)}>{props.children}</div>;
}

View File

@ -2,9 +2,7 @@
import { useState, useEffect } from "react";
export default function Time(props: {
showSecond: boolean
}) {
export default function Time(props: { showSecond: boolean }) {
const [currentTime, setCurrentTime] = useState(new Date());
useEffect(() => {

50
global.d.ts vendored
View File

@ -1,31 +1,31 @@
import { Suggestion } from "search-engine-autocomplete";
import React from "react";
interface settingsType extends object {
"version": number,
"elementBackdrop": boolean,
"bgBlur": boolean,
"timeShowSecond": boolean,
"currentSearchEngine": string,
"searchInNewTab": boolean,
"searchEngines": {
[key: string]: string
},
version: number;
elementBackdrop: boolean;
bgBlur: boolean;
timeShowSecond: boolean;
currentSearchEngine: string;
searchInNewTab: boolean;
searchEngines: {
[key: string]: string;
};
}
interface suggestionsResponse extends object{
suggestions: Suggestion[],
query: string,
verbatimRelevance: number,
time: number
interface SuggestionsResponse extends object {
suggestions: Suggestion[];
query: string;
verbatimRelevance: number;
time: number;
}
type suggestionItem = {
suggestion: string,
type: string,
relativeRelevance?: number,
relevance: number,
prompt?: string | React.ReactElement,
intention?: string | null,
probability?: number,
confidence?: number,
}
interface SuggestionItem {
suggestion: string;
type: string;
relativeRelevance?: number;
relevance: number;
prompt?: string | React.ReactElement;
intention?: string | null;
probability?: number;
confidence?: number;
};

View File

@ -1,5 +1,10 @@
{
"search": {
"placeholder": "ابحث أو اكتب عنوان URL"
},
"about": {
"license": {
"view": "← عرض"
}
}
}

View File

@ -1,4 +1,7 @@
{
"404": {
"title": "Page not found"
},
"search": {
"placeholder": "Search or type a URL",
"engine-aria": "Switch search engine",
@ -17,9 +20,6 @@
"title": "page not found",
"desc": "Please check if there is a typo in the URL. <br/>If SparkHome brought you to this page,<br/> please <a style=\"text-decoration:underline;\" href=\"mailto:contact@alikia2x.com\">contact us.</a>"
},
"about": {
"title": "SparkHome"
},
"tools": {
"base64": {
"title": "Base64 tools - LuminaraUtils",
@ -29,5 +29,30 @@
"copy": "Copy",
"copied": "Copied"
}
},
"about": {
"title": "About sparkast",
"license": {
"title": "License",
"view": "→ view",
"text": "GPL 3.0"
},
"presented-by": "Presented By",
"backend-api-version": "Backend API Version",
"client-version": "Client API Version",
"oss": {
"title": "OSS Statement",
"view": "→ View"
}
},
"license": {
"title": "License - sparkast",
"desc": "sparkast is open source software. It is licensed under the GPL 3.0 license. You can view the full license text below.",
"page-title": "License"
},
"oss_license": {
"title": "OSS Licenses - sparkast",
"desc": "This birth of this project would not have been possible without the following open source software. This page shows the licenses of the open source software used in sparkast.",
"page-title": "OSS Licenses"
}
}

View File

@ -1,12 +1,14 @@
{
"search": {
"placeholder": "検索またはURLを入力"
},
"Search": {
"engine-aria": "検索エンジンを切り替える",
"engine": {
"google": "Google"
},
"placeholder": "検索またはURLを入力"
},
"about": {
"license": {
"view": "→ 見る"
}
}
}

View File

@ -1,4 +1,7 @@
{
"404": {
"title": "页面未找到"
},
"search": {
"placeholder": "搜索或输入网址",
"engine-aria": "切换搜索引擎",
@ -13,26 +16,6 @@
},
"search-help-text": "用 {engine} 搜索"
},
"Search": {
"placeholder": "搜索或输入网址",
"engine-aria": "切换搜索引擎",
"engine": {
"google": "谷歌",
"baidu": "百度",
"bing": "必应",
"duckduckgo": "DuckDuckGo",
"yandex": "Yandex",
"yahoo": "雅虎",
"ecosia": "Ecosia"
},
"search-help-text": "用 {engine} 搜索"
},
"404": {
"title": "页面未找到"
},
"About": {
"title": "星火主页"
},
"tools": {
"base64": {
"title": "Base64 工具",
@ -48,6 +31,28 @@
"title": "网页不存在"
},
"about": {
"title": "星火主页"
"title": "关于 sparkast",
"oss": {
"title": "开源软件声明",
"view": "→ 查看"
},
"license": {
"title": "许可证",
"text": "GPL 3.0",
"view": "→ 查看"
},
"presented-by": "出品",
"backend-api-version": "后端 API 版本",
"client-version": "客户端 API 版本"
},
"license": {
"title": "开源许可证 - sparkast",
"page-title": "开源许可证",
"desc": "sparkast 是开源软件。它根据 GPL 3.0 许可证获得许可。您可以在下面查看完整的许可文本。"
},
"oss_license": {
"title": "开源软件声明 - sparkast",
"page-title": "开源软件声明",
"desc": "本项目的诞生离不开开源软件。此页面显示 sparkast 中使用的开源软件的许可证。"
}
}

View File

@ -1,10 +1,12 @@
<!DOCTYPE html>
<html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SparkHome</title>
<meta property="og:title" content="sparkast">
<meta property="og:description" content="Your ultimate productivity tool that gives you the answer to all within a single search box.">
<title>sparkast</title>
</head>
<body>
<div id="root"></div>

21
lib/feedback/sendError.ts Normal file
View File

@ -0,0 +1,21 @@
import pjson from "package.json";
const CLIENT_VERSION = pjson.version;
export function sendError(error: Error) {
fetch("/api/v1/error", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
message: error.message,
name: error.name,
time: new Date().getTime() / 1000,
version: CLIENT_VERSION,
ua: navigator.userAgent,
cause: error.cause,
stack: error.stack
})
});
}

View File

@ -1,147 +0,0 @@
{
"weather.summary": [
"how's the weather",
"What's going on with the weather?",
"Can you give me an update on the weather?",
"How's the forecast looking today?",
"Give me a summary of the current weather.",
"Can you tell me the current weather?",
"What is the weather situation at the moment?",
"Could you provide a quick weather update?",
"Is it raining or sunny outside?",
"What's the weather like right now?",
"Tell me the current weather conditions.",
"How about the weather today?",
"Is it a good day to be outside?",
"What should I expect in terms of weather today?",
"Is there any severe weather to be aware of?",
"Can you summarize today's weather forecast?",
"What's the weather looking like for the next few hours?",
"Is it going to stay this way all day?",
"Could you give me a brief overview of the weather?",
"What's the general weather situation in our area?",
"Is it cloudy or clear outside?",
"Any weather alerts I should know about?",
"How's the weather looking for outdoor activities?",
"What's the forecast saying for today's weather?",
"Is it going to be a warm day?",
"Are we expecting any storms today?",
"What's the weather condition outside my window?",
"Is it a typical day for this season in terms of weather?",
"how's the weather now?"
],
"weather.temp": [
"What's the temperature like right now?",
"Can you tell me the current temperature?",
"How hot is it outside?",
"What's the temperature supposed to be today?",
"What is the current temp outside?",
"Could you tell me the outdoor temperature?",
"Is it cold or warm outside?",
"What's the high temperature for today?",
"What's the low temperature expected tonight?",
"How does the temperature feel outside?",
"Is it going to get warmer or cooler today?",
"What's the temperature in the shade?",
"Can you provide the current temp in Celsius?",
"What's the temperature in Fahrenheit right now?",
"Is it too hot to be outside?",
"What's the temperature like in the morning?",
"How about the temperature in the evening?",
"Is it warm enough to go swimming?",
"What's the temperature in the city center?",
"Can you tell me the temp in the nearby area?",
"Is it below freezing outside?",
"What's the average temperature for today?",
"Is the temperature dropping or rising?",
"What should I wear considering the temperature?"
],
"base64.encode": [
"Please encode this data with base64: %s",
"I need to encode the following data in base64: %s",
"Could you encode this string using base64? %s",
"Convert this data to b64 encoding: %s",
"I want to encode this information with base64: %s",
"Help me encode this in base64: %s",
"Can you encode this data to base64 format? %s",
"b64 encode",
"base64 encode",
"encode base64 %s"
],
"base64.decode": [
"Please decode this base64 data: %s",
"I have a base64 encoded string that needs decoding: %s",
"Could you decode this base64 string for me? %s",
"Convert this base64 encoded data back to its original form: %s",
"I need to decode this base64 information: %s",
"Help me decode this base64 data: %s",
"Can you translate this base64 back to normal text? %s",
"b64 decode",
"base64 decode",
"decode base64 %s"
],
"url.encode": [
"Please encode this URL: %s",
"I need to encode this URL component: %s",
"Could you encode this part of the URL? %s",
"Convert this URL to its encoded form: %s",
"I want to encode this URL for safe transmission: %s",
"Help me encode this URL segment: %s",
"Can you encode this URL data? %s"
],
"url.decode": [
"Please decode this URL: %s",
"I have an encoded URL that needs decoding: %s",
"Could you decode this URL for me? %s",
"Convert this encoded URL back to its original form: %s",
"I need to decode this URL component: %s",
"Help me decode this URL segment: %s",
"Can you translate this encoded URL back to normal? %s"
],
"html.encode": [
"Please encode this HTML entity: %s",
"I need to encode this text to HTML entity: %s",
"Could you encode this as an HTML entity? %s",
"Convert this text to HTML entity encoding: %s",
"I want to encode this to prevent HTML interpretation: %s",
"Help me encode this into HTML entity: %s",
"Can you encode this for HTML usage? %s"
],
"html.decode": [
"Please decode this HTML entity: %s",
"I have an HTML entity that needs decoding: %s",
"Could you decode this HTML entity for me? %s",
"Convert this HTML entity back to its original text: %s",
"I need to decode this HTML entity to plain text: %s",
"Help me decode this HTML entity: %s",
"Can you translate this HTML entity back to normal text? %s"
],
"ai.command": [
"write a typescript helloworld code",
"Check the following content for grammar and clarity",
"Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option.",
"Improve this markdown content in asepcts like grammar and expression, for a GitHub repo README.",
"can u think of a short name of my package",
"simplify this code"
],
"ai.answer": [
"Which framework do you think is the most suitable for performance sensitive projects?"
],
"None": [
"free weather api",
"js get timezone",
"how",
"how's",
"how's the"
]
}

View File

@ -1,127 +0,0 @@
{
"weather.summary": [
"天气如何",
"现在的天气",
"今天的天气预报",
"现在的天气状况",
"今天天气怎么样",
"目前是什么天气",
"今天的天气概述",
"当前天气状况如何",
"今天会下雨吗",
"今天会下雪吗",
"今天晴天吗",
"今天的天气状况如何",
"现在外面是什么天气",
"今天天气好么",
"今天适合外出吗",
"今天的天气适宜做什么",
"今天有没有雾霾",
"今天的空气质量如何",
"今天的紫外线指数是多少",
"今天有没有大风",
"今天会不会很冷",
"今天的天气会变化吗",
"今天晚上的天气如何",
"今天夜里会下雨吗",
"今天的天气对出行有影响吗",
"今天的天气对运动有影响吗",
"今天的天气对工作有影响吗",
"今天的天气对旅游有影响吗",
"今天的天气对健康有影响吗"
],
"weather.temp": [
"现在的温度",
"现在多少度",
"外面有多热",
"明天热不热?",
"现在的气温是多少",
"今天最高温度是多少",
"今天最低温度是多少",
"现在外面感觉冷吗",
"现在需要穿外套吗",
"现在适合穿短袖吗",
"现在的温度适合外出吗",
"现在的温度适合运动吗",
"现在的温度适合睡觉吗",
"明天会比今天热吗",
"明天会比今天冷吗",
"今天的温度变化大吗",
"现在的温度适合开空调吗",
"现在的温度适合开暖气吗",
"室外的温度是多少",
"室内的温度是多少",
"现在的温度适合种植吗",
"现在的温度适合养宠物吗",
"现在的温度对健康有影响吗",
"现在的温度是否舒适",
"现在的温度是否适合工作"
],
"base64.encode": [
"请将数据使用base64编码%s",
"需要将以下数据base64编码%s",
"请将此字符串转为base64%s",
"将数据转为base64编码%s",
"信息base64编码%s",
"请帮忙编码base64%s",
"将数据编码为base64%s"
],
"base64.decode": [
"请解码这个base64数据%s",
"有base64编码字符串需要解码%s",
"帮忙解码base64%s",
"将base64编码转回原数据%s",
"解码base64信息%s",
"解码这个base64%s",
"将base64转文本%s"
],
"url.encode": [
"请编码这个URL%s",
"URL部分需要编码%s",
"请将URL部分编码%s",
"URL编码转换%s",
"安全传输需编码URL%s",
"编码URL段%s",
"URL数据编码%s"
],
"url.decode": [
"请解码这个URL%s",
"有URL编码需要解码%s",
"解码这个URL%s",
"URL编码转回原URL%s",
"解码URL部分%s",
"解码URL段%s",
"URL编码转文本%s"
],
"html.encode": [
"请编码HTML实体%s",
"文本转为HTML实体%s",
"编码为HTML实体%s",
"文本HTML实体编码%s",
"预防HTML解析编码%s",
"HTML实体编码%s",
"文本HTML使用编码%s"
],
"html.decode": [
"请解码HTML实体%s",
"HTML实体需要解码%s",
"解码HTML实体%s",
"HTML实体转回文本%s",
"HTML实体解码%s",
"解码HTML实体%s",
"HTML实体转文本%s"
],
"None": [
"你好",
"为什么计算机使用二进制",
"什么是",
"热",
"怎么"
]
}

13
lib/nlp/energyScore.ts Normal file
View File

@ -0,0 +1,13 @@
function logsumexp(arr: number[]): number {
const maxVal = Math.max(...arr);
const sumExp = arr.reduce((sum, val) => sum + Math.exp(val - maxVal), 0);
return Math.log(sumExp) + maxVal;
}
function minusEnergyScore(logits: number[]): number {
return logsumexp(logits);
}
const energyScore = minusEnergyScore;
export default energyScore;

72
lib/nlp/getEmbedding.ts Normal file
View File

@ -0,0 +1,72 @@
function getEmbeddingLayer(buffer: ArrayBuffer): { [key: number]: Float32Array } {
const dict: { [key: number]: Float32Array } = {};
const entrySize = 192;
const numEntries = buffer.byteLength / entrySize;
const dataView = new DataView(buffer);
for (let i = 0; i < numEntries; i++) {
const offset = i * entrySize;
const key = i;
const floatArray = new Float32Array(96);
for (let j = 0; j < 96; j++) {
const halfFloat = dataView.getUint16(offset + j * 2, true);
floatArray[j] = halfFloatToFloat32(halfFloat);
}
dict[key] = floatArray;
}
return dict;
}
function halfFloatToFloat32(halfFloat: number): number {
const sign = (halfFloat & 0x8000) >> 15;
const exponent = (halfFloat & 0x7c00) >> 10;
const fraction = halfFloat & 0x03ff;
if (exponent === 0) {
if (fraction === 0) {
// 零或负零
return sign ? -0.0 : 0.0;
} else {
// 非规格化的数
const f = fraction / 1024.0;
const value = f * Math.pow(2, -14);
return sign ? -value : value;
}
} else if (exponent === 0x1f) {
if (fraction === 0) {
// 无穷大或负无穷大
return sign ? -Infinity : Infinity;
} else {
// NaN
return NaN;
}
} else {
// 规格化的数
const f = fraction / 1024.0 + 1.0;
const value = f * Math.pow(2, exponent - 15);
return sign ? -value : value;
}
}
function getEmbedding(
tokenIds: number[],
embeddingDict: { [key: number]: Float32Array },
contextSize: number
): Float32Array {
let result: number[] = [];
for (let i = 0; i < contextSize; i++) {
if (i < tokenIds.length) {
const tokenId = tokenIds[i];
result = result.concat(Array.from(embeddingDict[tokenId]));
} else {
result = result.concat(new Array(96).fill(0));
}
}
return new Float32Array(result);
}
export { getEmbeddingLayer, getEmbedding };

View File

@ -1,56 +0,0 @@
// @ts-ignore
import { containerBootstrap } from "@nlpjs/core";
// @ts-ignore
import { Nlp } from "@nlpjs/nlp";
// @ts-ignore
import { NluManager, NluNeural } from "@nlpjs/nlu";
// @ts-ignore
import { LangEn } from "@nlpjs/lang-en-min";
// @ts-ignore
import { LangZh } from "@nlpjs/lang-zh";
import * as fflate from 'fflate';
export interface NLUType {
manager: any;
inited: boolean;
loadIntentionModel(): Promise<void>;
init(): Promise<this>;
process(lang: string, text: string): Promise<any>;
}
export class NLU {
manager: any;
inited: boolean = false;
async loadIntentionModel() {
const container = await containerBootstrap();
container.use(Nlp);
container.use(LangEn);
container.use(LangZh);
container.use(NluNeural);
const manager = new NluManager({
container,
locales: ["en", "zh"],
nlu: {
useNoneFeature: true
}
});
const response = await fetch("/model");
const responseBuf = await response.arrayBuffer();
const compressed = new Uint8Array(responseBuf);
const decompressed = fflate.decompressSync(compressed);
const modelText = fflate.strFromU8(decompressed);
manager.fromJSON(JSON.parse(modelText));
this.manager = manager;
}
async init() {
await this.loadIntentionModel();
this.inited = true;
return this;
}
async process(lang: string, text: string): Promise<any> {
const actual = await this.manager.process(lang, text);
return actual;
}
}

View File

@ -0,0 +1,94 @@
class TrieNode {
children: Map<string, TrieNode>;
tokenId: number | null;
constructor() {
this.children = new Map();
this.tokenId = null;
}
}
class Trie {
root: TrieNode;
constructor() {
this.root = new TrieNode();
}
insert(token: string, tokenId: number) {
let node = this.root;
for (const char of token) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char)!;
}
node.tokenId = tokenId;
}
searchLongestToken(text: string): [number | null, number] {
let node = this.root;
let longestTokenId: number | null = null;
let currentTokenLength = 0;
for (const char of text) {
if (!node.children.has(char)) {
break;
}
node = node.children.get(char)!;
currentTokenLength += 1;
if (node.tokenId !== null) {
longestTokenId = node.tokenId;
}
}
return [longestTokenId, currentTokenLength];
}
}
export default class BPETokenizer {
private trie: Trie;
constructor(vocabulary: { [key: string]: number }) {
this.trie = new Trie();
for (const token in vocabulary) {
if (vocabulary.hasOwnProperty(token)) {
this.trie.insert(token, vocabulary[token]);
}
}
}
tokenize(text: string): number[] {
const tokenIds: number[] = [];
let i = 0;
while (i < text.length) {
const [longestTokenId, length] = this.trie.searchLongestToken(text.slice(i));
if (longestTokenId !== null) {
tokenIds.push(longestTokenId);
i += length;
} else {
// If no token is found, treat the character as a single token
tokenIds.push(text.charCodeAt(i));
i += 1;
}
}
return tokenIds;
}
}
// Example usage:
// const vocabulary = {
// 'aa': 1,
// 'bb': 2,
// 'ab': 3,
// 'ba': 4,
// 'a': 5,
// 'b': 6
// };
// const tokenizer = new BPETokenizer(vocabulary);
// const text = 'ababbaa';
// const tokenIds = tokenizer.tokenize(text);
// console.log(tokenIds); // Output: [ 3, 3, 6, 1 ]

View File

@ -0,0 +1,37 @@
function byteToUnicode(): { [key: number]: string } {
const bs: number[] = [
...Array.from({ length: 126 - 33 + 1 }, (_, i) => 33 + i), // range(ord("!"), ord("~") + 1)
...Array.from({ length: 172 - 161 + 1 }, (_, i) => 161 + i), // range(ord("¡"), ord("¬") + 1)
...Array.from({ length: 255 - 174 + 1 }, (_, i) => 174 + i) // range(ord("®"), ord("ÿ") + 1)
];
const cs: number[] = [...bs];
let n = 0;
for (let b = 0; b < 256; b++) {
if (!bs.includes(b)) {
bs.push(b);
cs.push(256 + n);
n++;
}
}
const csChars: string[] = cs.map((n) => String.fromCharCode(n));
return Object.fromEntries(bs.map((b, i) => [b, csChars[i]]));
}
export default function bytesToUnicode(str: string): string {
const byteToUnicodeMap = byteToUnicode();
const encoder = new TextEncoder();
// Convert the input string to an array of bytes (numbers)
const byteArray = Array.from(encoder.encode(str));
// Map each byte to its corresponding Unicode character
const unicodeArray = byteArray.map((byte) => {
return byteToUnicodeMap[byte];
});
// Join the array of Unicode characters into a single string
return unicodeArray.join("");
}

View File

@ -0,0 +1,21 @@
export async function loadVocab(): Promise<any> {
try {
// Fetch the vocab.json file
const response = await fetch("/model/vocab.json");
// Check if the request was successful
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Parse the JSON from the response
const data = await response.json();
// Return the parsed JSON
return data;
} catch (error) {
// Handle any errors that occurred during the fetch or parsing process
console.error("Error loading vocab.json:", error);
throw error;
}
}

View File

@ -0,0 +1,7 @@
import BPETokenizer from "./BPEtokenizer";
async function tokenize(text: string, tokenizer: BPETokenizer) {
return tokenizer.tokenize(text);
}
export default tokenize;

View File

@ -0,0 +1,46 @@
function unicodeToByte(): { [key: string]: number } {
const bs: number[] = [
...Array.from({ length: 126 - 33 + 1 }, (_, i) => 33 + i), // range(ord("!"), ord("~") + 1)
...Array.from({ length: 172 - 161 + 1 }, (_, i) => 161 + i), // range(ord("¡"), ord("¬") + 1)
...Array.from({ length: 255 - 174 + 1 }, (_, i) => 174 + i) // range(ord("®"), ord("ÿ") + 1)
];
const cs: number[] = [...bs];
let n = 0;
for (let b = 0; b < 256; b++) {
if (!bs.includes(b)) {
bs.push(b);
cs.push(256 + n);
n++;
}
}
const csChars: string[] = cs.map((n) => String.fromCharCode(n));
const originalMapping = Object.fromEntries(bs.map((b, i) => [b, csChars[i]]));
const reversedMapping: { [key: string]: number } = {};
for (const [key, value] of Object.entries(originalMapping)) {
reversedMapping[value] = Number(key);
}
return reversedMapping;
}
export default function unicodeToBytes(str: string): string {
const unicodeToByteMap = unicodeToByte();
const unicodeArray = str.split("");
const byteNumberArray = unicodeArray.map((char) => {
return unicodeToByteMap[char];
});
const byteArray = Uint8Array.from(byteNumberArray);
const decoder = new TextDecoder();
const decodedString = decoder.decode(byteArray);
return decodedString;
}

View File

@ -1,71 +0,0 @@
// @ts-ignore
import { containerBootstrap } from "@nlpjs/core";
// @ts-ignore
import { Nlp } from "@nlpjs/nlp";
// @ts-ignore
import { NluManager, NluNeural } from "@nlpjs/nlu";
// @ts-ignore
import { LangEn } from "@nlpjs/lang-en-min";
// @ts-ignore
import { LangZh } from "@nlpjs/lang-zh";
import fs from "node:fs";
import * as fflate from 'fflate';
let zh: TrainData = {};
let en: TrainData = {};
type TrainData = {
[key: string]: string[];
};
export async function trainIntentionModel() {
try {
const dataZH = fs.readFileSync("./lib/nlp/data/zh.json", "utf8");
const dataEN = fs.readFileSync("./lib/nlp/data/en.json", "utf8");
zh = JSON.parse(dataZH);
en = JSON.parse(dataEN);
} catch (err) {
console.error(err);
}
const container = await containerBootstrap();
container.use(Nlp);
container.use(LangEn);
container.use(LangZh);
container.use(NluNeural);
const manager = new NluManager({
container,
locales: ["en", "zh"],
nlu: {
useNoneFeature: true
}
});
// Adds the utterances and intents for the NLP
for (const key in zh) {
for (const value of zh[key]) {
manager.add("zh", value, key);
}
}
for (const key in en) {
for (const value of en[key]) {
manager.add("en", value, key);
}
}
await manager.train();
const resultModel = manager.toJSON();
const buf = fflate.strToU8(JSON.stringify(resultModel));
const gzipped = fflate.gzipSync(buf, {
filename: 'model.json',
mtime: new Date().getTime()
});
fs.writeFileSync("./public/model", Buffer.from(gzipped));
}
trainIntentionModel();

View File

@ -1,7 +1,7 @@
export function normalizeURL(input: string): string {
export function normalizeURL(input: string, absolute: boolean = true): string {
try {
// try to create a URL object
const url = new URL(input, window.location.href);
const url = absolute ? new URL(input) : new URL(input, window.location.href);
// if the URL is valid, return it
return url.href;
} catch (error) {

View File

@ -1,11 +1,11 @@
import { settingsType, suggestionItem } from "global";
import { settingsType, SuggestionItem } from "global";
import copyToClipboard from "lib/copy";
import { normalizeURL } from "lib/normalizeURL";
import search from "lib/search";
export default function (
index: number,
suggestion: suggestionItem[],
suggestion: SuggestionItem[],
_query: string,
settings: settingsType,
searchBoxRef: React.RefObject<HTMLInputElement>
@ -23,6 +23,6 @@ export default function (
} else if (selected.type === "link") {
window.open(normalizeURL(selected.suggestion));
} else if (selected.type === "inpage-link") {
location.href = normalizeURL(selected.suggestion);
location.href = normalizeURL(selected.suggestion, false);
}
}

View File

@ -1,4 +1,4 @@
import { suggestionItem } from "global";
import { SuggestionItem } from "global";
interface keywordLinkDict {
[key: string]: string;
@ -15,24 +15,24 @@ const dict_cn: keywordLinkDict = {
export function keywordSuggestion(query: string) {
for (const keyword in dict_cn) {
if (query.includes(keyword)) {
const result: suggestionItem = {
const result: SuggestionItem = {
type: "inpage-link",
suggestion: dict_cn[keyword],
prompt: keyword,
relevance: 3000
};
return result
return result;
}
}
for (const keyword in dict_en) {
if (query.includes(keyword)) {
const result: suggestionItem = {
const result: SuggestionItem = {
type: "inpage-link",
suggestion: dict_en[keyword],
prompt: keyword,
relevance: 3000
};
return result
return result;
}
}
return null;

View File

@ -1 +1,9 @@
export const engineTranslation = ["google", "bing", "baidu", "duckduckgo", "yandex", "ecosia", "yahoo"];
export const engineTranslation = [
"google",
"bing",
"baidu",
"duckduckgo",
"yandex",
"ecosia",
"yahoo"
];

22
lib/server/startScript.ts Normal file
View File

@ -0,0 +1,22 @@
import { promises as dns } from "node:dns";
// Copied from vite/src/node/utils.ts
/**
* Returns resolved localhost address when `dns.lookup` result differs from DNS
*
* `dns.lookup` result is same when defaultResultOrder is `verbatim`.
* Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
* For example, when IPv6 is not supported on that machine/network.
*/
export async function getLocalhostAddressIfDiffersFromDNS(): Promise<string | undefined> {
const [nodeResult, dnsResult] = await Promise.all([
dns.lookup("localhost"),
dns.lookup("localhost", { verbatim: true })
]);
const isSame =
nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address;
return isSame ? undefined : nodeResult.address;
}
export const wildcardHosts = new Set(["0.0.0.0", "::", "0000:0000:0000:0000:0000:0000:0000:0000"]);

View File

@ -0,0 +1,5 @@
import { atom } from "jotai";
const searchboxLastInputAtom = atom(0);
export { searchboxLastInputAtom };

View File

@ -1,24 +1,24 @@
import { settingsType } from "global";
import { atomWithStorage } from 'jotai/utils'
import { atomWithStorage } from "jotai/utils";
const defaultSettings: settingsType = {
"version": 2,
"elementBackdrop": true,
"bgBlur": true,
"timeShowSecond": false,
"currentSearchEngine": "google",
"searchInNewTab": true,
"searchEngines": {
"google": "https://www.google.com/search?q=%s",
"bing": "https://www.bing.com/search?q=%s",
"baidu": "https://www.baidu.com/s?wd=%s",
"duckduckgo": "https://duckduckgo.com/?q=%s",
"yandex": "https://yandex.com/search/?text=%s",
"yahoo": "https://search.yahoo.com/search?p=%s",
"ecosia": "https://www.ecosia.org/search?q=%s"
version: 2,
elementBackdrop: true,
bgBlur: true,
timeShowSecond: false,
currentSearchEngine: "google",
searchInNewTab: true,
searchEngines: {
google: "https://www.google.com/search?q=%s",
bing: "https://www.bing.com/search?q=%s",
baidu: "https://www.baidu.com/s?wd=%s",
duckduckgo: "https://duckduckgo.com/?q=%s",
yandex: "https://yandex.com/search/?text=%s",
yahoo: "https://search.yahoo.com/search?p=%s",
ecosia: "https://www.ecosia.org/search?q=%s"
}
};
const settingsAtom = atomWithStorage('settings', defaultSettings);
const settingsAtom = atomWithStorage("settings", defaultSettings);
export { settingsAtom };

View File

@ -1,6 +1,6 @@
import { suggestionItem } from "global";
import { SuggestionItem } from "global";
import { atom } from "jotai";
const suggestionAtom = atom([] as suggestionItem[]);
const suggestionAtom = atom([] as SuggestionItem[]);
export { suggestionAtom };

View File

@ -1,21 +0,0 @@
import pjson from "package.json"
const CLIENT_VERSION = pjson.version;
export function sendError(error: Error) {
fetch("/api/v1/error", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
message: error.message,
name: error.name,
time: new Date().getTime()/1000,
version: CLIENT_VERSION,
ua: navigator.userAgent,
cause: error.cause,
stack: error.stack
})
})
}

View File

@ -1,5 +1,5 @@
import TLDtxt from "./tlds.txt?raw"
import TLDtxt from "./tlds.txt";
export function getTLD() {
return TLDtxt.split("\n").filter((line) => line[0] !== "#")
return TLDtxt.split("\r\n").filter((line) => line[0] !== "#");
}

View File

@ -1,4 +1,4 @@
# Version 2024071300, Last Updated Sat Jul 13 07:07:01 2024 UTC
# Version 2025011900, Last Updated Sun Jan 19 07:07:01 2025 UTC
AAA
AARP
ABB
@ -297,7 +297,6 @@ CY
CYMRU
CYOU
CZ
DABUR
DAD
DANCE
DATA

View File

@ -1,41 +1,33 @@
import { toASCII } from "tr46";
import { getTLD } from "./tldList";
console.log(getTLD());
export default function validLink(link: string) {
let finalURL;
try {
const url = new URL(link);
finalURL = url;
new URL(link);
return true;
} catch (error) {
// if the URL is invalid, try to add the protocol
try {
const urlWithHTTP = new URL("http://" + link);
finalURL = urlWithHTTP;
finalURL = new URL("http://" + link);
} catch (error) {
return false;
}
}
if (
validTLD(finalURL.host) ||
isValidIPv6(finalURL.host.slice(1, finalURL.host.length - 1)) ||
isValidIPv4(finalURL.host)
) {
return true;
} else {
return false;
}
if (finalURL.host.endsWith(".")) return false;
return validTLD(finalURL.host) ||
isValidIPv6(link.slice(1, finalURL.host.length - 1)) ||
isValidIPv4(link);
}
export function validTLD(domain: string): boolean {
if (!domain.includes(".")) return false;
const tld = toASCII(domain.split(".").reverse()[0]);
const tldList = getTLD();
if (tldList.includes(tld.toUpperCase())) {
return true;
} else {
return false;
}
return !!tldList.includes(tld.toUpperCase());
}
export function isValidIPv6(ip: string): boolean {
@ -69,10 +61,8 @@ export function isValidIPv6(ip: string): boolean {
return false;
}
}
if (doubleColonCount === 0 && groups !== 8) {
return false;
}
return true;
return !(doubleColonCount === 0 && groups !== 8);
}
export function isValidIPv4(ip: string): boolean {

View File

@ -1,8 +1,5 @@
import * as pjson from "package.json";
export default function getVersion(){
return pjson.version;
}
export const clientVersion = pjson.version;
export const clientNLUVersion = 2;
export const apiVersion = 1;

View File

@ -4,9 +4,9 @@ export function getClosestHourTimestamp(): string {
// 获取本地时间的年份、月份、日期、小时
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始
const day = String(now.getDate()).padStart(2, '0');
const hour = String(now.getHours()).padStart(2, '0');
const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始
const day = String(now.getDate()).padStart(2, "0");
const hour = String(now.getHours()).padStart(2, "0");
// 拼接成所需的格式
const localHourTimestamp = `${year}-${month}-${day}T${hour}:00`;

View File

@ -3,15 +3,16 @@ export async function getWeather(lat: number, lon: number) {
const cacheKey = `weather-cache-${lat.toFixed(2)}-${lon.toFixed(2)}-${timezone}`;
const localData = localStorage.getItem(cacheKey);
if (localData != null) {
console.log('Using cache');
console.log("Using cache");
const parsedLocalData = JSON.parse(localData);
if (parsedLocalData["hourly"]["time"][0] != undefined &&
new Date().getTime() - new Date(parsedLocalData["hourly"]["time"][0]).getTime() < 86400 * 1000
if (
parsedLocalData["hourly"]["time"][0] != undefined &&
new Date().getTime() - new Date(parsedLocalData["hourly"]["time"][0]).getTime() <
86400 * 1000
) {
return parsedLocalData;
}
else {
console.log('Cache expired');
} else {
console.log("Cache expired");
localStorage.removeItem(cacheKey);
}
}

View File

@ -1,21 +1,24 @@
{
"name": "sparkhome",
"name": "sparkast",
"private": false,
"version": "5.8.0",
"version": "5.8.1",
"type": "module",
"scripts": {
"dev": "bun server.ts",
"build": "bun license-gen && tsc -b && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "NODE_ENV=production bun server.ts",
"license-gen": "bunx generate-license-file --input package.json --output lib/license.txt --overwrite"
"license-gen": "bunx generate-license-file --input package.json --output lib/license.txt --overwrite",
"format": "prettier --write ."
},
"dependencies": {
"@alikia/search-complete": "^0.4.4",
"@iconify/react": "^5.0.1",
"@nextui-org/react": "^2.4.2",
"@types/bun": "^1.1.6",
"@types/express": "^4.17.21",
"@types/tr46": "^5.0.0",
"@xenova/transformers": "^2.17.2",
"cac": "^6.7.14",
"chalk": "^5.3.0",
"express": "^4.19.2",
@ -28,12 +31,13 @@
"jest": "^29.7.0",
"jotai": "^2.8.3",
"node-nlp": "^4.27.0",
"onnxruntime-web": "^1.20.0-dev.20240925-a47254eaef",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-helmet": "^6.1.0",
"react-i18next": "^14.1.2",
"react-router": "^6.23.1",
"react-router-dom": "^6.23.1",
"search-engine-autocomplete": "^0.4.3",
"tr46": "^5.0.0",
"valid-url": "^1.0.9",
"validate-color": "^2.2.4",
@ -42,6 +46,7 @@
"devDependencies": {
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@types/react-helmet": "^6.1.11",
"@types/valid-url": "^1.0.7",
"@typescript-eslint/eslint-plugin": "^7.13.1",
"@typescript-eslint/parser": "^7.13.1",
@ -51,6 +56,7 @@
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.7",
"postcss": "^8.4.38",
"prettier": "^3.3.3",
"tailwindcss": "^3.4.4",
"typescript": "^5.2.2",
"vite": "^5.3.1",

View File

@ -9,7 +9,10 @@ export default function NotFound() {
<div className="relative h-20 mx-4 w-[0.15rem] bg-black dark:bg-white"></div>
<div className="flex flex-col">
<div className="uppercase text-3xl font-light">{t("notfound.title")}</div>
<div className="text-sm" dangerouslySetInnerHTML={{__html:t("notfound.desc")}}></div>
<div
className="text-sm"
dangerouslySetInnerHTML={{ __html: t("notfound.desc") }}
></div>
</div>
</div>
</div>

View File

@ -1,20 +1,54 @@
import useDarkMode from "lib/darkModeHook";
import getVersion, { apiVersion, clientNLUVersion } from "lib/version";
import { apiVersion, clientVersion } from "lib/version";
import AboutLayout from "./layout";
import { useTranslation } from "react-i18next";
function License() {
const { t } = useTranslation();
return (
<>
<p className="flex items-center my-4">
<span className="font-medium text-2xl md:text-2xl mr-4 w-[36rem]">
{t("about.oss.title")}
</span>
<span
className="relative font-bold px-2 py-1 rounded-md text-nowrap underline
bg-green-600 text-white"
>
<a href="/about/oss-licenses">{t("about.oss.view")}</a>
</span>
</p>
<p className="flex items-center my-4">
<span className="font-medium text-2xl md:text-2xl mr-4 w-[36rem]">
{t("about.license.title")}
</span>
<span
className="relative font-bold px-2 py-1 rounded-md text-nowrap underline
bg-red-500 text-white"
>
<a href="/about/license">{t("about.license.text")}</a>
</span>
</p>
</>
);
}
export default function AboutPage() {
const darkMode = useDarkMode();
const { t } = useTranslation();
return (
<AboutLayout>
<h1 className="text-4xl font-bold mb-6">About SparkHome</h1>
<h1 className="text-4xl font-bold mb-6">{t("about.title")}</h1>
<div className="flex mb-8">
<img src="/favicon.ico" className="relative w-20 h-20" />
<div className="flex flex-col ml-4">
<span className="leading-7 md:leading-9 text-3xl font-bold">SparkHome</span>
<span className="leading-7 md:leading-9 text-3xl font-bold">sparkast</span>
<p className="mt-2 leading-5 text-base md:text-xl">
Made with <span className="text-red-500"></span> by
<a className="underline text-red-500 mx-1" href="https://alikia2x.com">
<a
className="underline decoration-dotted text-red-500 mx-1"
href="https://alikia2x.com"
>
alikia2x
</a>
from Luminara Studio
@ -22,42 +56,41 @@ export default function AboutPage() {
</div>
</div>
<Version title="Overall Version" version={getVersion()} versionClass="bg-red-500" />
<Version
title="Browser NLU Model Version"
version={"Build " + clientNLUVersion}
title={t("about.backend-api-version")}
version={"/api/v" + apiVersion}
versionClass="bg-purple-500"
/>
<Version
title="Backend API Version"
version={"/api/v" + apiVersion}
title={t("about.client-version")}
version={clientVersion}
versionClass="bg-orange-500"
/>
<p className="flex items-center my-3">
<span className="font-bold text-xl md:text-2xl mr-4 w-[36rem]">License</span>
<span
className="relative px-2 py-1 text-sm font-bold rounded-md text-nowrap underline
bg-green-600 text-white"
>
<a href="/about/license"> view</a>
</span>
</p>
<p className="relative font-bold text-2xl mt-12">Presented By</p>
{!darkMode && <img src="/LuminaraStudio.png" className="relative md:h-64 mt-6" />}
{darkMode && <img src="/LuminaraStudioDark.png" className="relative md:h-56 mt-6" />}
<License />
<p className="relative font-bold text-2xl mt-12">{t("about.presented-by")}</p>
{!darkMode && (
<img src="/assets/img/LuminaraStudio.png" className="relative md:h-64 mt-6" />
)}
{darkMode && (
<img src="/assets/img/LuminaraStudioDark.png" className="relative md:h-64 mt-6" />
)}
</AboutLayout>
);
}
function Version(props: { title: string; version: string; versionClass?: string }) {
document.title = "About SparkHome";
const { t } = useTranslation();
return (
<p className="flex items-center my-3">
<span className="font-bold text-xl md:text-2xl mr-4 w-[36rem]">{props.title}</span>
<p className="flex items-center my-4">
<span className="font-medium text-2xl md:text-2xl mr-4 w-[36rem]">
{t(props.title)}
</span>
<span
className={
"relative px-2 py-1 text-sm font-bold rounded-md text-nowrap text-white " +
"relative px-2 py-1 font-bold rounded-md text-nowrap text-white " +
props.versionClass || ""
}
>

View File

@ -1,8 +1,18 @@
import React from "react";
import { useTranslation } from "react-i18next";
import { Helmet } from "react-helmet";
export default function AboutLayout({ children }: { children: React.ReactNode }) {
const { t } = useTranslation();
return (
<div className="h-screen w-screen overflow-x-hidden bg-white dark:bg-[rgb(23,25,29)]">
<main className="relative h-full w-full md:w-3/4 lg:w-1/2 left-0 md:left-[12.5%] lg:left-1/4
pt-12 px-3 md:px-0">
<Helmet>
<title>{t('about.title')}</title>
</Helmet>
<main
className="relative h-full w-full md:w-3/4 lg:w-1/2 left-0 md:left-[12.5%] lg:left-1/4
pt-12 px-3 md:px-0"
>
{children}
</main>
</div>

View File

@ -0,0 +1,22 @@
import LICENSE from "lib/license.txt?raw";
import { Helmet } from "react-helmet";
import { useTranslation } from "react-i18next";
export default function OSSLicensesPage() {
const { t } = useTranslation();
return (
<div className="dark:bg-[rgb(23,25,29)] dark:text-white min-h-screen w-screen overflow-x-hidden">
<Helmet>
<title>{t("oss_license.title")}</title>
</Helmet>
<main
className="relative h-full w-full md:w-3/4 lg:w-1/2 left-0 md:left-[12.5%] lg:left-1/4
pt-12"
>
<h1 className="text-4xl font-bold mb-6">{t('oss_license.page-title')}</h1>
<p className="text-lg mb-8">{t('oss_license.desc')}</p>
<div className="font-mono text-justify whitespace-break-spaces">{LICENSE}</div>
</main>
</div>
);
}

View File

@ -0,0 +1,22 @@
import LICENSE from "LICENSE?raw";
import { useTranslation } from "react-i18next";
import { Helmet } from "react-helmet";
export default function ThisProjectLicensePage() {
const { t } = useTranslation();
return (
<div className="dark:bg-[rgb(23,25,29)] dark:text-white min-h-screen w-screen overflow-x-hidden">
<Helmet>
<title>{t("license.title")}</title>
</Helmet>
<main
className="relative h-full w-full md:w-3/4 lg:w-1/2 left-0 md:left-[12.5%] lg:left-1/4
pt-12"
>
<h1 className="text-4xl font-bold mb-6">{t('license.page-title')}</h1>
<p className="text-lg mb-8">{t('license.desc')}</p>
<div className="font-mono text-justify whitespace-break-spaces">{LICENSE}</div>
</main>
</div>
);
}

View File

@ -1,17 +0,0 @@
import LICENSE from "lib/license.txt?raw";
export default function LicensePage() {
return (
<div className="dark:bg-[rgb(23,25,29)] dark:text-white min-h-screen w-screen overflow-x-hidden">
<main
className="relative h-full w-full md:w-3/4 lg:w-1/2 left-0 md:left-[12.5%] lg:left-1/4
pt-12"
>
<h1 className="text-4xl font-bold mb-6">LICENSE</h1>
<div className="font-mono text-justify whitespace-break-spaces">
{LICENSE}
</div>
</main>
</div>
);
}

View File

@ -13,6 +13,7 @@ export default function Homepage() {
return (
<div className="h-screen w-screen overflow-x-hidden bg-white dark:bg-[rgb(23,25,29)]">
<title>sparkast</title>
<Background />
<EngineSelector

View File

Before

Width:  |  Height:  |  Size: 84 KiB

After

Width:  |  Height:  |  Size: 84 KiB

View File

Before

Width:  |  Height:  |  Size: 81 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

BIN
public/model/NLU.onnx Normal file

Binary file not shown.

View File

@ -0,0 +1,13 @@
{
"idx_to_class": {
"0": "weather",
"1": "base64",
"2": "url-encode",
"3": "html-encode",
"4": "ai.command",
"5": "knowledge",
"6": "ai.question",
"7": "datetime"
},
"threshold": 1.7
}

Binary file not shown.

1
public/model/vocab.json Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -5,36 +5,33 @@ import pjson from "./package.json";
import { networkInterfaces } from "os";
import cac from "cac";
import { configureBackendRoutes } from "./backend/route";
import { Server, IncomingMessage, ServerResponse } from "http";
import { getLocalhostAddressIfDiffersFromDNS, wildcardHosts } from "./lib/server/startScript";
async function helloMessage() {
const { base } = await ViteExpress.getViteConfig();
const timeCost = new Date().getTime() - start.getTime();
console.log("");
const timeCost = Date.now() - start.getTime();
console.log(
" ",
chalk.redBright("SparkHome"),
chalk.redBright("v" + pjson.version),
chalk.whiteBright(" ready in"),
`${Math.round(timeCost)} ms`
`\n ${chalk.redBright("sparkast v" + pjson.version)} ${chalk.whiteBright("ready in")} ${Math.round(timeCost)} ms\n`
);
console.log(` ${chalk.redBright("➜ Local:")} ${chalk.cyan(`http://${name}:${port}${base}`)}`);
if (host === undefined) {
ips.forEach((ip) =>
console.log(
` ${chalk.redBright("➜ Network:")} ${chalk.cyan(`http://${ip}:${port}${base}`)}`
)
);
console.log("");
console.log(" ", chalk.redBright("➜ "), "Local:\t", chalk.cyan(`http://${host}:${port}${base}`));
if (host !== "localhost") {
for (const ip of ips) {
console.log(" ", chalk.redBright("➜ "), "Network:\t", chalk.cyan(`http://${ip}:${port}${base}`));
}
}
console.log(" ", chalk.red("➜ "), chalk.whiteBright("press"), "h + enter", chalk.whiteBright("to show help"))
console.log(` ${chalk.red("➜ ")}${chalk.whiteBright("press h + enter to show help")}`);
}
async function handleInput() {
async function handleInput(server: Server<typeof IncomingMessage, typeof ServerResponse>) {
for await (const line of console) {
switch (line) {
switch (line.trim()) {
case "h":
console.log(" Shortcuts");
console.log(" ", chalk.whiteBright("press"), "c + enter ", chalk.whiteBright("to clear console"));
console.log(" ", chalk.whiteBright("press"), "q + enter ", chalk.whiteBright("to quit"));
console.log(
` Shortcuts\n ${chalk.whiteBright("press c + enter to clear console")}\n ${chalk.whiteBright("press q + enter to quit")}`
);
break;
case "c":
console.clear();
@ -43,8 +40,6 @@ async function handleInput() {
server.on("vite:close", () => {});
server.close();
return;
default:
break;
}
}
}
@ -52,37 +47,48 @@ async function handleInput() {
const start = new Date();
const cli = cac();
const nets = networkInterfaces();
const ips: string[] = [];
for (const name of Object.keys(nets)) {
if (nets[name] === undefined) {
continue;
}
for (const net of nets[name]) {
// Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
// 'IPv4' is in Node <= 17, from 18 it's a number 4 or 6
const familyV4Value = typeof net.family === "string" ? "IPv4" : 4;
if (net.family === familyV4Value && !net.internal) {
ips.push(net.address);
}
}
}
const ips: string[] = Object.values(nets)
.flat()
.filter(
(net) =>
!!net && net.family === (typeof net.family === "string" ? "IPv4" : 4) && !net.internal
)
.map((net) => (!!net ? net.address : undefined))
.filter((v) => v !== undefined);
const app = express();
const port = 3000;
let host = "localhost";
cli.option("--host [host]", "Sepcify host name")
cli.help()
cli.version(pjson.version);
let host: string | undefined = "localhost";
cli.option("--host [host]", "Specify host name").help().version(pjson.version);
const parsed = cli.parse();
if (parsed.options.host!==undefined && typeof parsed.options.host == "boolean" && parsed.options.host) {
host = "0.0.0.0";
const optionsHost: string | boolean | undefined = parsed.options.host;
if (optionsHost === undefined || optionsHost === false) {
// Use a secure default
host = "localhost";
} else if (optionsHost === true) {
// If passed --host in the CLI without arguments
host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
} else {
host = optionsHost;
}
// Set host name to localhost when possible
let name = host === undefined || wildcardHosts.has(host) ? "localhost" : host;
if (host === "localhost") {
const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
if (localhostAddr) {
name = localhostAddr;
}
}
configureBackendRoutes(app);
const server = app.listen(port, host);
// if the var `host` is undefined, then just not pass it.
const server = host ? app.listen(port, host) : app.listen(port);
ViteExpress.bind(app, server, helloMessage);
handleInput();
handleInput(server);

View File

@ -3,7 +3,8 @@ import { createBrowserRouter, RouterProvider } from "react-router-dom";
import "./i18n";
import Homepage from "pages";
import AboutPage from "pages/about";
import LicensePage from "pages/about/license";
import OSSLicensesPage from "pages/about/license/OSS";
import ThisProjectLicensePage from "../pages/about/license/ThisProject.tsx";
const router = createBrowserRouter([
{
@ -11,14 +12,16 @@ const router = createBrowserRouter([
element: <Homepage />
},
{
path: "about",
path: "/about",
element: <AboutPage />,
children: [
},
{
path: "license",
element: <LicensePage />
}
]
path: "/about/oss-licenses",
element: <OSSLicensesPage />
},
{
path: "/about/license",
element: <ThisProjectLicensePage />
}
]);

View File

@ -1,18 +1,18 @@
import * as en from "i18n/en.json"
import * as zh from "i18n/zh.json"
import * as ja from "i18n/ja.json"
import * as ar from "i18n/ar.json"
import * as de from "i18n/de.json"
import * as es from "i18n/es.json"
import * as fr from "i18n/fr.json"
import * as it from "i18n/it.json"
import * as ko from "i18n/ko.json"
import * as pt from "i18n/pt.json"
import * as ru from "i18n/ru.json"
import * as en from "i18n/en.json";
import * as zh from "i18n/zh.json";
import * as ja from "i18n/ja.json";
import * as ar from "i18n/ar.json";
import * as de from "i18n/de.json";
import * as es from "i18n/es.json";
import * as fr from "i18n/fr.json";
import * as it from "i18n/it.json";
import * as ko from "i18n/ko.json";
import * as pt from "i18n/pt.json";
import * as ru from "i18n/ru.json";
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from 'i18next-browser-languagedetector';
import ICU from 'i18next-icu';
import LanguageDetector from "i18next-browser-languagedetector";
import ICU from "i18next-icu";
i18n.use(initReactI18next) // passes i18n down to react-i18next
.use(LanguageDetector)
.use(ICU)
@ -59,7 +59,7 @@ i18n.use(initReactI18next) // passes i18n down to react-i18next
},
detection: {
order: ['navigator'],
order: ["navigator"],
caches: []
}
});

View File

@ -2,14 +2,11 @@ import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./app";
import "./index.css";
import { NextUIProvider } from "@nextui-org/react";
const app = createRoot(document.getElementById("root")!);
app.render(
<StrictMode>
<NextUIProvider>
<App />
</NextUIProvider>
</StrictMode>
);

80
test/validIP.test.ts Normal file
View File

@ -0,0 +1,80 @@
import { describe, expect, test } from "bun:test";
import { isValidIPv4 } from "../lib/url/validLink";
describe("Check if a string is a valid IPv4", () => {
test("Invalid IPv4 addresses - Missing part", () => {
expect(isValidIPv4("192.168.1")).toBe(false);
expect(isValidIPv4("1")).toBe(false);
});
test("Invalid IPv4 addresses - Contains non-digit characters", () => {
expect(isValidIPv4("192.168.1.a")).toBe(false);
expect(isValidIPv4("192.168.1.1a")).toBe(false);
expect(isValidIPv4("192.168.1.1.1")).toBe(false);
});
test("Invalid IPv4 addresses - Contains empty parts", () => {
expect(isValidIPv4("192.168.1.")).toBe(false);
expect(isValidIPv4("192..168.1")).toBe(false);
});
test("Invalid IPv4 addresses - Contains negative numbers", () => {
expect(isValidIPv4("192.168.-1.1")).toBe(false);
});
test("Invalid IPv4 addresses - Contains out-of-range numbers", () => {
expect(isValidIPv4("192.168.256.1")).toBe(false);
expect(isValidIPv4("192.168.1.256")).toBe(false);
});
test("Invalid IPv4 addresses - Contains multiple dots", () => {
expect(isValidIPv4("192.168..1.1")).toBe(false);
expect(isValidIPv4("192.168.1..1")).toBe(false);
});
test("Invalid IPv4 addresses - Empty string", () => {
expect(isValidIPv4("")).toBe(false);
});
test("Invalid IPv4 addresses - Contains special characters", () => {
expect(isValidIPv4("192.168.1.1!")).toBe(false);
expect(isValidIPv4("192.168.1.1 ")).toBe(false);
expect(isValidIPv4("192.168.1.1\t")).toBe(false);
});
test("Invalid IPv4 addresses - Contains non-ASCII characters", () => {
expect(isValidIPv4("192.168.1.1©")).toBe(false);
});
test("Invalid IPv4 addresses - Contains newline character", () => {
expect(isValidIPv4("192.168.1.1\n")).toBe(false);
});
test("Invalid IPv4 addresses - Contains multiple IP addresses", () => {
expect(isValidIPv4("192.168.1.1 192.168.1.2")).toBe(false);
});
test("Invalid IPv4 addresses - Contains IPv6 address", () => {
expect(isValidIPv4("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe(false);
});
test("Valid IPv4 addresses - Standard IP", () => {
expect(isValidIPv4("192.168.1.1")).toBe(true);
});
test("Valid IPv4 addresses - All zeros", () => {
expect(isValidIPv4("0.0.0.0")).toBe(true);
});
test("Valid IPv4 addresses - Maximum value", () => {
expect(isValidIPv4("255.255.255.255")).toBe(true);
});
test("Valid IPv4 addresses - Leading zero but valid", () => {
expect(isValidIPv4("192.000.001.001")).toBe(true);
});
test("Valid IPv4 addresses - Single digit parts", () => {
expect(isValidIPv4("1.2.3.4")).toBe(true);
});
});

View File

@ -1,4 +1,4 @@
import { describe, expect, test } from "@jest/globals";
import { describe, expect, test } from "bun:test";
import validLink, { validTLD } from "../lib/url/validLink";
describe("Check if a string is an accessible domain/URL/IP", () => {
@ -8,9 +8,13 @@ describe("Check if a string is an accessible domain/URL/IP", () => {
// With https and path
expect(validLink("https://jestjs.io/docs/getting-started/")).toBe(true);
// With anchor
expect(validLink("https://difftastic.wilfred.me.uk/zh-CN/git.html#git-difftool")).toBe(true);
expect(validLink("https://difftastic.wilfred.me.uk/zh-CN/git.html#git-difftool")).toBe(
true
);
// With params
expect(validLink("https://www.bilibili.com/list/ml2252204359?oid=990610203&bvid=BV1sx4y1g7Hh")).toBe(true);
expect(
validLink("https://www.bilibili.com/list/ml2252204359?oid=990610203&bvid=BV1sx4y1g7Hh")
).toBe(true);
});
test("Punycode URL", () => {
expect(validLink("https://原神大学.com/")).toBe(true);
@ -22,6 +26,10 @@ describe("Check if a string is an accessible domain/URL/IP", () => {
test("Invalid TLD with no protocol", () => {
expect(validLink("www.example.notexist")).toBe(false);
});
test("Dot suffix", () => {
expect(validLink(".")).toBe(false);
expect(validLink("anything.")).toBe(false);
});
test("IPv4 without protocol", () => {
expect(validLink("127.0.0.1")).toBe(true);
});
@ -34,6 +42,9 @@ describe("Check if a string is an accessible domain/URL/IP", () => {
test("Not a valid host/URL.", () => {
expect(validLink("weather")).toBe(false);
});
test("Not a valid IP", () => {
expect(validLink("1")).toBe(false);
});
});
// Reference: https://www.iana.org/domains/root/db
@ -48,7 +59,8 @@ describe("Check if the given TLD exist and assigned.", () => {
// they really exist!
expect(validTLD("example.foo")).toBe(true);
expect(validTLD("example.bar")).toBe(true);
expect(validTLD('example.zip')).toBe(true);
expect(validTLD("example.zip")).toBe(true);
expect(validTLD("xn--s8w913fdga.chn.moe")).toBe(true);
});
test("Exist but not assigned TLD", () => {
expect(validTLD("example.active")).toBe(false);

View File

@ -1,13 +1,9 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import tsconfigPaths from 'vite-tsconfig-paths';
import { chunkSplitPlugin } from 'vite-plugin-chunk-split';
import tsconfigPaths from "vite-tsconfig-paths";
import { chunkSplitPlugin } from "vite-plugin-chunk-split";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
tsconfigPaths(),
chunkSplitPlugin()
]
plugins: [react(), tsconfigPaths(), chunkSplitPlugin()]
});