diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..b55b157b --- /dev/null +++ b/.env.example @@ -0,0 +1,3 @@ +# Ready for docker-compose +REDIS_URL="redis://127.0.0.1:6379" +DATABASE_URL="postgres://username:password@127.0.0.1:5435/postgres?sslmode=disable" \ No newline at end of file diff --git a/.gitignore b/.gitignore index 8303cd42..a70ee3fd 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,9 @@ packages/sdk/profileId.txt packages/sdk/test.ts dump.sql +dump-* +.sql +clickhouse # Logs diff --git a/.vscode/settings.json b/.vscode/settings.json index cc89dd2d..1e76b8a0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -15,5 +15,8 @@ "typescript.preferences.autoImportFileExcludePatterns": [ "next/router.d.ts", "next/dist/client/router.d.ts" - ] + ], + "[sql]": { + "editor.defaultFormatter": "adpyke.vscode-sql-formatter" + } } diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..0ad25db4 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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 +. diff --git a/README.md b/README.md index 0ccdf389..d32ca5ad 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,6 @@ -

- -

+# openpanel -# mixan - -Mixan is a simple analytics tool for logging events on web and react-native. My goal is to make a minimal mixpanel copy with the most basic features (for now). +Openpanel is a simple analytics tool for logging events on web and react-native. My goal is to make a minimal mixpanel copy with the most basic features (for now). - Easy to use - Fully responsive UI @@ -17,10 +13,23 @@ Mixan is a simple analytics tool for logging events on web and react-native. My ### Speed/Benchmark -As of today (2023-12-12) I have more then 1.2 million events in PSQL and performance is smooth as butter 🧈. Only thing that is slow (2s response time) is to get all unique events. Solved now with cache but can probably make better with `indexes` and avoid using `distinct`. +As of today (~~2023-12-12~~ 2024-01-16) I have more then ~~1.2~~ 2.8 million events and 20 thousand profiles in postgres and performance is smooth as butter\* 🧈. Only thing that is slow (2s response time) is to get all unique events. Solved now with cache but can probably make better with `indexes` and avoid using `distinct`. + +\* Smooth as butter is somewhat exaggerated but I would say it still fast! It takes 1.4 sec to search through all events (3 million) with advanced where clause. I think this performance is absolutly good enough. ### GUI +- [x] Fix design for report editor +- [x] Fix profiles + - [x] Pagination + - [x] Filter by event name +- [x] Fix [profileId] + - [x] Add events + - [x] Improve design for properties and linked profiles +- [x] New design for events +- [ ] Map events to convertions +- [ ] Map ids +- [x] Fix menu links when projectId is undefined - [x] Fix tables on settings - [x] Rename event label - [ ] Common web dashboard @@ -36,14 +45,16 @@ As of today (2023-12-12) I have more then 1.2 million events in PSQL and perform - [x] View events in a list - [x] Simple filters - [x] View profiles in a list -- [ ] Invite users +- [x] Invite users - [ ] Drag n Drop reports on dashboard - [x] Manage dashboards -- [ ] Support more chart types +- [x] Support more chart types - [x] Bar - [x] Histogram - - [ ] Pie - - [ ] Area + - [x] Pie + - [x] Area + - [x] Metric + - [x] Line - [ ] Support funnels - [ ] Support multiple breakdowns - [x] Aggregations (sum, average...) @@ -56,53 +67,49 @@ As of today (2023-12-12) I have more then 1.2 million events in PSQL and perform - [x] Create web sdk - [x] Screen view function should take in title, path and parse query string (especially utm tags) -## @mixan/sdk +## @openpanel/sdk For pushing events ### Install -- npm: `npm install @mixan/sdk` -- pnpm: `pnpm add @mixan/sdk` -- yarn: `yarn add @mixan/sdk` +- npm: `npm install @openpanel/sdk` +- pnpm: `pnpm add @openpanel/sdk` +- yarn: `yarn add @openpanel/sdk` ### Usage ```ts -import { Mixan } from '@mixan/sdk'; +import { OpenpanelWeb } from '@openpanel/web'; -const mixan = new Mixan({ +// import { OpenpanelNative } from '@openpanel/sdk-native'; + +const openpanel = new OpenpanelWeb({ clientId: 'uuid', - clientSecret: 'uuid', url: 'http://localhost:8080/api/sdk', batchInterval: 10000, verbose: false, - saveProfileId(id) { - // Web - localStorage.setItem('@profileId', id); - // // react-native-mmkv - // mmkv.setItem('@profileId', id) - }, - removeProfileId() { - // Web - localStorage.removeItem('@profileId'); - // // react-native-mmkv - // mmkv.delete('@profileId') - }, - getProfileId() { - // Web - return localStorage.getItem('@profileId'); - // // react-native-mmkv - // return mmkv.getString('@profileId') - }, + trackIp: true, }); +// const openpanel = new OpenpanelNative({ +// clientId: 'uuid', +// clientSecret: 'uuid', +// url: 'http://localhost:8080/api/sdk', +// batchInterval: 10000, +// verbose: false, +// trackIp: true, +// }); + // Call this before you send any events // It will create a anonymous profile // This profile will be merged if you call `setUser` in a later stage -mixan.init(); +openpanel.init(); -mixan.setUser({ +// tracks all outgoing links as a `link_out` event +openpanel.trackOutgoingLinks(); + +openpanel.setUser({ id: 'id', first_name: 'John', last_name: 'Doe', @@ -111,33 +118,36 @@ mixan.setUser({ }); // will upsert 'app_open' on user property and increment it -mixan.increment('app_open'); +openpanel.increment('app_open'); // will upsert 'app_open' on user property and increment it by 10 -mixan.increment('app_open', 10); +openpanel.increment('app_open', 10); // will upsert 'app_open' on user property and decrement it by 2 -mixan.decrement('app_open', 2); +openpanel.decrement('app_open', 2); // send a sign_in event -mixan.event('sign_in'); +openpanel.event('sign_in'); // send a sign_in event with properties -mixan.event('sign_in', { +openpanel.event('sign_in', { provider: 'gmail', }); -// short hand for 'screen_view', can also take any properties -mixan.screenView('Profile', { - id: '123', - // any other properties, url, public +// Screen view for web +openpanel.screenView(); + +// Screen view for native +openpanel.screenView('Article', { + id: '3', + title: 'Nice article here', }); // Call this when a user is logged out. // This will just make sure you do not send // the associated profile id for the next events -mixan.clear(); +openpanel.clear(); ``` -## @mixan/web +## @openpanel/dashboard A nextjs web app. Collects all events and your gui to analyze your data. @@ -150,6 +160,11 @@ We use https://cron-job.org (free) to handle our cronjobs, you can use any provi - **https://domain.com/api/cron/cache/update** Will update the memory cache - **https://domain.com/api/cron/events/enrich** Enrich events (adds duration etc) +## Development + +1. Run `docker-compose up -d` to get redis and postgres running +2. Then `pnpm dev` to boot the web and worker (queue) + ## Screenshots ![Line chart](images/line.png) diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 00000000..4eb2bc6d --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,15 @@ +# Roadmap + +## Simple todos + +- [ ] add session_id on events table, link this id on create +- [ ] add overview page containing + - [x] User histogram (last 30 minutes) + - [ ] Bounce rate + - [ ] Session duration + - [ ] Views per session + - [ ] Unique users + - [ ] Total users + - [ ] Total pageviews + - [ ] Total events +- [ ] diff --git a/TRADEMARK.md b/TRADEMARK.md new file mode 100644 index 00000000..7f0d1fb8 --- /dev/null +++ b/TRADEMARK.md @@ -0,0 +1,64 @@ +# Openpanel Trademark Guidelines + +## Overview + +Welcome to Openpanel's Trademark Guidelines. These guidelines are designed to help you understand how to use and refer to the Openpanel brand and trademarks properly. By following these guidelines, you contribute to maintaining the integrity of the Openpanel brand. + +## Trademark Usage + +### Openpanel Logo + +The Openpanel logo is a key element of our brand identity. To ensure consistency and visibility, please adhere to the following guidelines: + +- **Do not modify or alter the Openpanel logo.** +- **Maintain proper spacing around the logo to ensure clarity and legibility.** +- **Use the official Openpanel logo assets provided on our official website.** + +### Openpanel Name + +When referring to Openpanel in text, please follow these guidelines: + +- **Use the full, unaltered "Openpanel" name when mentioning our product.** +- **Capitalize the "O" in Openpanel.** +- **Avoid using Openpanel in a way that could be misleading or imply endorsement.** + +## Domain Names + +To avoid confusion and maintain the clarity of the Openpanel brand, please refrain from using domain names that may be misleading or suggest an official affiliation with Openpanel. + +## Open Source Projects + +If you are developing an open-source project related to Openpanel, feel free to use and reference our trademarks as long as it is clear that your project is not officially endorsed or affiliated with Openpanel. + +## Contact Us + +If you have any questions or need further clarification on the use of Openpanel trademarks, please contact us at [hey@openpanel.dev]. + +--- + +## Acceptable Uses + +You are permitted to use the Openpanel name in the following situations, provided it is done truthfully and accurately: + +- To refer to Openpanel and its products and services in news articles and other content without alteration. +- To discuss Openpanel and its products in a fair and honest manner that does not imply sponsorship, endorsement, or affiliation with Openpanel. +- To refer to and/or link to the products and services hosted on Openpanel’s servers and website. +- To indicate if your product, service, or solution integrates, is interoperable, or compatible with Openpanel, as long as it does not create confusion about the origin of your offering. +- You may use our word marks as part of a public subdomain solely for serving as the URL for your self-managed Openpanel instance (e.g., openpanel.companyname.com). + +## Prohibited Uses + +Unless you have explicit written permission from Openpanel or your use falls under the acceptable uses mentioned above, the use of Openpanel trademarks is strictly prohibited. Here are examples of prohibited uses that may be considered for permission upon request: + +- Use of Openpanel trademarks in connection with a public website offering Openpanel software for installation and use on a server (instead of directing users to the official Openpanel site). +- Use of Openpanel trademarks in connection with versions of Openpanel products made publicly available or offered in the cloud by a managed service provider, resale, or other commercial basis. +- Use of Openpanel trademarks in connection with bundling Openpanel products with other software. + +In these cases: + +- Adherence to the terms of the open-source license for Openpanel software products and code is mandatory. +- Removal of all Openpanel logos is required, with the adoption of your own branding to clearly signify no affiliation with or endorsement by Openpanel. +- Avoidance of using any Openpanel trademark in connection with the user-facing name, branding, or marketing materials of your project. +- Usage of word marks, but not logos, in truthful statements describing the relationship between your software and Openpanel is allowed. For instance, "this software is derived from the source code of the Openpanel software," along with a disclaimer that your project is not officially associated with Openpanel or its products. + +Openpanel reserves the right, at its sole discretion, to (i) terminate, revoke, modify, or change permission to use the trademarks at any time and; (ii) object to any use or misuse of the trademarks globally. Any changes to these guidelines are effective immediately upon posting, and your continued use of the trademarks following revised guidelines signifies your acceptance of such revisions. diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile new file mode 100644 index 00000000..d600a717 --- /dev/null +++ b/apps/api/Dockerfile @@ -0,0 +1,104 @@ +# Dockerfile that builds the web app only + +FROM --platform=linux/amd64 node:20-slim AS base + +ARG DATABASE_URL +ENV DATABASE_URL=$DATABASE_URL + +ARG CLICKHOUSE_DB +ENV CLICKHOUSE_DB=$CLICKHOUSE_DB + +ARG CLICKHOUSE_PASSWORD +ENV CLICKHOUSE_PASSWORD=$CLICKHOUSE_PASSWORD + +ARG CLICKHOUSE_URL +ENV CLICKHOUSE_URL=$CLICKHOUSE_URL + +ARG CLICKHOUSE_USER +ENV CLICKHOUSE_USER=$CLICKHOUSE_USER + +ARG REDIS_URL +ENV REDIS_URL=$REDIS_URL + +ENV PNPM_HOME="/pnpm" + +ENV PATH="$PNPM_HOME:$PATH" + +RUN corepack enable + +ARG NODE_VERSION=20 + +RUN apt update \ + && apt install -y curl python3 make g++ \ + && curl -L https://raw.githubusercontent.com/tj/n/master/bin/n -o n \ + && bash n $NODE_VERSION \ + && rm n \ + && npm install -g n \ + && rm -rf /var/cache/apk/* + +WORKDIR /app + +COPY package.json package.json +COPY pnpm-lock.yaml pnpm-lock.yaml +COPY pnpm-workspace.yaml pnpm-workspace.yaml +COPY apps/api/package.json apps/api/package.json +COPY packages/db/package.json packages/db/package.json +COPY packages/redis/package.json packages/redis/package.json +COPY packages/queue/package.json packages/queue/package.json +COPY packages/common/package.json packages/common/package.json +COPY packages/constants/package.json packages/constants/package.json +COPY packages/validation/package.json packages/validation/package.json +COPY packages/sdk/package.json packages/sdk/package.json + +# BUILD +FROM base AS build + +WORKDIR /app/apps/api +RUN pnpm install --frozen-lockfile + +WORKDIR /app +COPY apps apps +COPY packages packages +COPY tooling tooling +RUN pnpm db:codegen + +WORKDIR /app/apps/api +RUN pnpm run build + +# PROD +FROM base AS prod + +WORKDIR /app/apps/api +RUN pnpm install --frozen-lockfile --prod + +# FINAL +FROM base AS runner + +COPY --from=build /app/package.json /app/package.json +COPY --from=prod /app/node_modules /app/node_modules + +# Apps +COPY --from=build /app/apps/api /app/apps/api + +# Apps node_modules +COPY --from=prod /app/apps/api/node_modules /app/apps/api/node_modules + +# Packages +COPY --from=build /app/packages/db /app/packages/db +COPY --from=build /app/packages/redis /app/packages/redis +COPY --from=build /app/packages/queue /app/packages/queue +COPY --from=build /app/packages/common /app/packages/common + +# Packages node_modules +COPY --from=prod /app/packages/db/node_modules /app/packages/db/node_modules +COPY --from=prod /app/packages/redis/node_modules /app/packages/redis/node_modules +COPY --from=prod /app/packages/queue/node_modules /app/packages/queue/node_modules +COPY --from=prod /app/packages/common/node_modules /app/packages/common/node_modules + +RUN pnpm db:codegen + +WORKDIR /app/apps/api + +EXPOSE 3000 + +CMD ["pnpm", "start"] \ No newline at end of file diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 00000000..348016a3 --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1,51 @@ +{ + "name": "@openpanel/api", + "version": "0.0.1", + "scripts": { + "dev": "dotenv -e ../../.env -c -v WATCH=1 tsup", + "testing": "API_PORT=3333 pnpm dev", + "start": "node dist/index.js", + "build": "rm -rf dist && tsup", + "lint": "eslint .", + "format": "prettier --check \"**/*.{mjs,ts,md,json}\"", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@fastify/cors": "^9.0.0", + "@fastify/websocket": "^8.3.1", + "@logtail/pino": "^0.4.19", + "@openpanel/common": "workspace:*", + "@openpanel/db": "workspace:*", + "@openpanel/queue": "workspace:*", + "@openpanel/redis": "workspace:*", + "fastify": "^4.25.2", + "ico-to-png": "^0.2.1", + "pino": "^8.17.2", + "pino-pretty": "^10.3.1", + "ramda": "^0.29.1", + "sharp": "^0.33.2", + "ua-parser-js": "^1.0.37", + "uuid": "^9.0.1" + }, + "devDependencies": { + "@openpanel/eslint-config": "workspace:*", + "@openpanel/prettier-config": "workspace:*", + "@openpanel/sdk": "workspace:*", + "@openpanel/tsconfig": "workspace:*", + "@types/ramda": "^0.29.6", + "@types/ua-parser-js": "^0.7.39", + "@types/uuid": "^9.0.8", + "@types/ws": "^8.5.10", + "eslint": "^8.48.0", + "prettier": "^3.0.3", + "tsup": "^7.2.0", + "typescript": "^5.2.2" + }, + "eslintConfig": { + "root": true, + "extends": [ + "@openpanel/eslint-config/base" + ] + }, + "prettier": "@openpanel/prettier-config" +} diff --git a/apps/api/scripts/get-referrers.ts b/apps/api/scripts/get-referrers.ts new file mode 100644 index 00000000..e0934a00 --- /dev/null +++ b/apps/api/scripts/get-referrers.ts @@ -0,0 +1,48 @@ +import fs from 'fs'; +import path from 'path'; + +function transform(data: any) { + const obj: Record = {}; + for (const type in data) { + for (const name in data[type]) { + const domains = data[type][name].domains ?? []; + for (const domain of domains) { + obj[domain] = { + type, + name, + }; + } + } + } + + return obj; +} + +async function main() { + // Get document, or throw exception on error + try { + const data = await fetch( + 'https://s3-eu-west-1.amazonaws.com/snowplow-hosted-assets/third-party/referer-parser/referers-latest.json' + ).then((res) => res.json()); + + fs.writeFileSync( + path.resolve(__dirname, '../src/referrers/index.ts'), + [ + '// This file is generated by the script get-referrers.ts', + '', + '// The data is fetch from snowplow-referer-parser https://github.com/snowplow-referer-parser/referer-parser', + `// The orginal referers.yml is based on Piwik's SearchEngines.php and Socials.php, copyright 2012 Matthieu Aubry and available under the GNU General Public License v3.`, + '', + `const referrers: Record = ${JSON.stringify( + transform(data) + )} as const;`, + 'export default referrers;', + ].join('\n'), + 'utf-8' + ); + } catch (e) { + console.log(e); + } +} + +main(); diff --git a/apps/api/scripts/test-events.ts b/apps/api/scripts/test-events.ts new file mode 100644 index 00000000..06f12faf --- /dev/null +++ b/apps/api/scripts/test-events.ts @@ -0,0 +1,224 @@ +import { omit, prop, uniqBy } from "ramda"; + +import { generateProfileId, getTime, toISOString } from "@openpanel/common"; +import type { Event, IServiceCreateEventPayload } from "@openpanel/db"; +import { + createEvent as createClickhouseEvent, + db, + formatClickhouseDate, + getSalts, +} from "@openpanel/db"; + +import { parseIp } from "../src/utils/parseIp"; +import { parseUserAgent } from "../src/utils/parseUserAgent"; + +const clean = omit([ + "ip", + "os", + "ua", + "url", + "hash", + "host", + "path", + "device", + "screen", + "hostname", + "language", + "referrer", + "timezone", +]); +async function main() { + const events = await db.event.findMany({ + where: { + project_id: "4e2798cb-e255-4e9d-960d-c9ad095aabd7", + name: "screen_view", + createdAt: { + gte: new Date("2024-01-01"), + lt: new Date("2024-02-04"), + }, + }, + orderBy: { + createdAt: "asc", + }, + }); + + const grouped: Record = {}; + let index = 0; + for (const event of events.slice()) { + // console.log(index, event.name, event.createdAt.toISOString()); + index++; + + const properties = event.properties as Record; + + if (properties.ua?.includes("bot")) { + // console.log('IGNORE', event.id); + continue; + } + + if (!event.profile_id) { + // console.log('IGNORE', event.id); + continue; + } + const hej = grouped[event.profile_id]; + if (hej) { + hej.push(event); + } else { + grouped[event.profile_id] = [event]; + } + } + + console.log("Total users", Object.keys(grouped).length); + + let uidx = -1; + for (const profile_id of Object.keys(grouped)) { + uidx++; + console.log(`User index ${uidx}`); + + const events = uniqBy(prop("createdAt"), grouped[profile_id] || []); + + if (events) { + let lastSessionStart = null; + let screenViews = 0; + let totalDuration = 0; + console.log("new user..."); + let eidx = -1; + for (const event of events) { + eidx++; + const prevEvent = events[eidx - 1]; + const prevEventAt = prevEvent?.createdAt; + + const nextEvent = events[eidx + 1]; + + const properties = event.properties as Record; + const projectId = event.project_id; + const path = properties.path!; + const ip = properties.ip!; + const origin = "https://openpanel.kiddo.se"; + const ua = properties.ua!; + const uaInfo = parseUserAgent(ua); + const salts = await getSalts(); + const profileId = generateProfileId({ + salt: salts.current, + origin, + ip, + ua, + }); + + const geo = parseIp(ip); + + const isNextEventNewSession = + nextEvent && + nextEvent.createdAt.getTime() - event.createdAt.getTime() > + 1000 * 60 * 30; + + const payload: IServiceCreateEventPayload = { + name: event.name, + profileId, + projectId, + properties: clean(properties), + createdAt: event.createdAt.toISOString(), + country: geo.country, + city: geo.city, + region: geo.region, + continent: geo.continent, + os: uaInfo.os, + osVersion: uaInfo.osVersion, + browser: uaInfo.browser, + browserVersion: uaInfo.browserVersion, + device: uaInfo.device, + brand: uaInfo.brand, + model: uaInfo.model, + duration: + nextEvent && !isNextEventNewSession + ? nextEvent.createdAt.getTime() - event.createdAt.getTime() + : 0, + path, + referrer: properties?.referrer?.host ?? "", // TODO + referrerName: properties?.referrer?.host ?? "", // TODO + }; + + if (!prevEventAt) { + lastSessionStart = await createSessionStart(payload); + } else if ( + event.createdAt.getTime() - prevEventAt.getTime() > + 1000 * 60 * 30 + ) { + if (eidx > 0 && prevEventAt && lastSessionStart) { + await createSessionEnd(prevEventAt, lastSessionStart, { + screenViews, + totalDuration, + }); + totalDuration = 0; + screenViews = 0; + lastSessionStart = await createSessionStart(payload); + } + } + + screenViews++; + totalDuration += payload.duration; + await createEvent(payload); + } // for each user event + + const prevEventAt = events[events.length - 1]?.createdAt; + if (prevEventAt && lastSessionStart) { + await createSessionEnd(prevEventAt, lastSessionStart, { + screenViews, + totalDuration, + }); + } + } + } +} + +async function createEvent(event: IServiceCreateEventPayload) { + console.log( + `Create ${event.name} - ${event.path} - ${formatClickhouseDate( + event.createdAt, + )} - ${event.duration / 1000} sec`, + ); + await createClickhouseEvent(event); +} + +async function createSessionStart(event: IServiceCreateEventPayload) { + const session: IServiceCreateEventPayload = { + ...event, + duration: 0, + name: "session_start", + createdAt: toISOString(getTime(event.createdAt) - 100), + }; + + await createEvent(session); + return session; +} + +async function createSessionEnd( + prevEventAt: Date, + sessionStart: IServiceCreateEventPayload, + options: { + screenViews: number; + totalDuration: number; + }, +) { + const properties: Record = {}; + if (options.screenViews === 1) { + properties.__bounce = true; + } else { + properties.__bounce = false; + } + + const session: IServiceCreateEventPayload = { + ...sessionStart, + properties: { + ...properties, + ...sessionStart.properties, + }, + duration: options.totalDuration, + name: "session_end", + createdAt: toISOString(prevEventAt.getTime() + 10), + }; + + await createEvent(session); + return session; +} + +main(); diff --git a/apps/api/scripts/test-ua.ts b/apps/api/scripts/test-ua.ts new file mode 100644 index 00000000..00547799 --- /dev/null +++ b/apps/api/scripts/test-ua.ts @@ -0,0 +1,18 @@ +//@ts-nocheck + +async function main() { + const crypto = require('crypto'); + + function createHash(data, len) { + return crypto + .createHash('shake256', { outputLength: len }) + .update(data) + .digest('hex'); + } + + console.log(createHash('foo', 2)); + // 1af9 + console.log(createHash('foo', 32)); + // 1af97f7818a28edf} +} +main(); diff --git a/apps/api/src/bots/bots.readme.md b/apps/api/src/bots/bots.readme.md new file mode 100644 index 00000000..2f504974 --- /dev/null +++ b/apps/api/src/bots/bots.readme.md @@ -0,0 +1,6 @@ +# Device Detector - The Universal Device Detection library for parsing User Agents + +> @link https://matomo.org +> @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or lat + +[bots.ts](./bots.ts) is based on matomo bots.yml file. You can see the original version here [here](https://raw.githubusercontent.com/matomo-org/device-detector/master/regexes/bots.yml). diff --git a/apps/api/src/bots/bots.ts b/apps/api/src/bots/bots.ts new file mode 100644 index 00000000..421891fa --- /dev/null +++ b/apps/api/src/bots/bots.ts @@ -0,0 +1,4901 @@ +export default [ + { + regex: 'monitoring360bot', + name: '360 Monitoring', + category: 'Site Monitor', + url: 'https://www.360monitoring.io', + producer: { + name: 'Plesk International GmbH', + url: 'https://www.plesk.com', + }, + }, + { + regex: 'Cloudflare-Healthchecks', + name: 'Cloudflare Health Checks', + category: 'Service Agent', + url: 'https://developers.cloudflare.com/health-checks/', + producer: { + name: 'CloudFlare', + url: 'https://www.cloudflare.com/', + }, + }, + { + regex: '360Spider', + name: '360Spider', + category: 'Search bot', + url: 'https://www.so.com/help/help_3_2.html', + producer: { + name: 'Online Media Group, Inc.', + url: '', + }, + }, + { + regex: 'Aboundex', + name: 'Aboundexbot', + category: 'Search bot', + url: 'http://www.aboundex.com/crawler/', + producer: { + name: 'Aboundex.com', + url: 'http://www.aboundex.com', + }, + }, + { + regex: 'AcoonBot', + name: 'Acoon', + category: 'Search bot', + url: 'http://www.acoon.de/robot.asp', + producer: { + name: 'Acoon GmbH', + url: 'http://www.acoon.de', + }, + }, + { + regex: 'AddThis\\.com', + name: 'AddThis.com', + category: 'Social Media Agent', + url: '', + producer: { + name: 'Clearspring Technologies, Inc.', + url: 'http://www.clearspring.com', + }, + }, + { + regex: 'AhrefsBot', + name: 'aHrefs Bot', + category: 'Crawler', + url: 'https://ahrefs.com/robot', + producer: { + name: 'Ahrefs Pte Ltd', + url: 'https://ahrefs.com/robot', + }, + }, + { + regex: 'AhrefsSiteAudit/[\\d.]+', + name: 'AhrefsSiteAudit', + category: 'Site Monitor', + url: 'https://ahrefs.com/robot/site-audit', + producer: { + name: 'Ahrefs Pte Ltd', + url: 'https://ahrefs.com/', + }, + }, + { + regex: 'ia_archiver|alexabot|verifybot', + name: 'Alexa Crawler', + category: 'Search bot', + url: 'https://support.alexa.com/hc/en-us/sections/200100794-Crawlers', + producer: { + name: 'Alexa Internet', + url: 'https://www.alexa.com', + }, + }, + { + regex: 'alexa site audit', + name: 'Alexa Site Audit', + category: 'Site Monitor', + url: 'https://support.alexa.com/hc/en-us/articles/200450194', + producer: { + name: 'Alexa Internet', + url: 'https://www.alexa.com', + }, + }, + { + regex: 'Amazonbot', + name: 'Amazon Bot', + category: 'Crawler', + url: 'https://developer.amazon.com/support/amazonbot', + producer: { + name: 'Amazon.com, Inc.', + url: 'https://www.amazon.com/', + }, + }, + { + regex: 'Amazon[ -]Route ?53[ -]Health[ -]Check[ -]Service', + name: 'Amazon Route53 Health Check', + category: 'Service Agent', + producer: { + name: 'Amazon Web Services', + url: 'https://aws.amazon.com/', + }, + }, + { + regex: 'AmorankSpider', + name: 'Amorank Spider', + category: 'Crawler', + url: 'http://amorank.com/webcrawler.html', + producer: { + name: 'Amorank', + url: 'http://www.amorank.com', + }, + }, + { + regex: 'ApacheBench', + name: 'ApacheBench', + category: 'Benchmark', + url: 'https://httpd.apache.org/docs/2.4/programs/ab.html', + producer: { + name: 'The Apache Software Foundation', + url: 'https://www.apache.org/foundation/', + }, + }, + { + regex: 'Applebot', + name: 'Applebot', + category: 'Crawler', + url: 'https://support.apple.com/en-us/HT204683', + producer: { + name: 'Apple Inc', + url: 'https://www.apple.com', + }, + }, + { + regex: 'AppSignalBot', + name: 'AppSignalBot', + category: 'Site Monitor', + url: 'https://docs.appsignal.com/uptime-monitoring/', + producer: { + name: 'AppSignal', + url: 'https://appsignal.com/', + }, + }, + { + regex: 'Arachni', + name: 'Arachni', + category: 'Security Checker', + url: 'https://www.arachni-scanner.com/', + producer: { + name: 'Sarosys LLC', + url: 'https://www.sarosys.com/', + }, + }, + { + regex: 'AspiegelBot', + name: 'AspiegelBot', + category: 'Crawler', + url: 'https://aspiegel.com/', + producer: { + name: 'Huawei', + url: 'https://www.huawei.com/', + }, + }, + { + regex: 'Castro 2, Episode Duration Lookup', + name: 'Castro 2', + category: 'Service Agent', + url: 'http://supertop.co/castro/', + producer: { + name: 'Supertop', + url: 'http://supertop.co', + }, + }, + { + regex: 'Curious George', + name: 'Analytics SEO Crawler', + category: 'Crawler', + url: 'http://www.analyticsseo.com/crawler', + producer: { + name: 'Analytics SEO', + url: 'http://www.analyticsseo.com', + }, + }, + { + regex: 'archive\\.org_bot|special_archiver', + name: 'archive.org bot', + category: 'Crawler', + url: 'https://archive.org/details/archive.org_bot', + producer: { + name: 'The Internet Archive', + url: 'https://archive.org', + }, + }, + { + regex: 'Ask Jeeves/Teoma', + name: 'Ask Jeeves', + category: 'Search bot', + url: '', + producer: { + name: 'Ask Jeeves Inc.', + url: 'http://www.ask.com', + }, + }, + { + regex: 'Backlink-Check\\.de', + name: 'Backlink-Check.de', + category: 'Crawler', + url: 'http://www.backlink-check.de/bot.html', + producer: { + name: 'Mediagreen Medienservice', + url: 'http://www.backlink-check.de', + }, + }, + { + regex: 'BacklinkCrawler', + name: 'BacklinkCrawler', + category: 'Crawler', + url: 'http://www.backlinktest.com/crawler.html', + producer: { + name: '2.0Promotion GbR', + url: 'http://www.backlinktest.com', + }, + }, + { + regex: 'Baidu.*spider|baidu Transcoder', + name: 'Baidu Spider', + category: 'Search bot', + url: 'http://www.baidu.com/search/spider.htm', + producer: { + name: 'Baidu', + url: 'http://www.baidu.com', + }, + }, + { + regex: 'BazQux', + name: 'BazQux Reader', + url: 'https://bazqux.com/fetcher', + category: 'Feed Fetcher', + producer: { + name: '', + url: '', + }, + }, + { + regex: 'Better Uptime Bot', + name: 'Better Uptime Bot', + category: 'Site Monitor', + url: 'https://betteruptime.com/faq', + producer: { + name: 'Better Uptime', + url: 'https://betteruptime.com/', + }, + }, + { + regex: + 'MSNBot|msrbot|bingbot|bingadsbot|BingPreview|msnbot-(UDiscovery|NewsBlogs)|adidxbot', + name: 'BingBot', + category: 'Search bot', + url: 'http://search.msn.com/msnbot.htmn', + producer: { + name: 'Microsoft Corporation', + url: 'http://www.microsoft.com', + }, + }, + { + regex: 'Blekkobot', + name: 'Blekkobot', + category: 'Search bot', + url: 'http://blekko.com/about/blekkobot', + producer: { + name: 'Blekko', + url: 'http://blekko.com', + }, + }, + { + regex: 'BLEXBot', + name: 'BLEXBot Crawler', + category: 'Crawler', + url: 'http://webmeup-crawler.com', + producer: { + name: 'WebMeUp', + url: 'http://webmeup.com', + }, + }, + { + regex: 'Bloglovin', + name: 'Bloglovin', + url: 'http://www.bloglovin.com', + category: 'Feed Fetcher', + producer: { + name: '', + url: '', + }, + }, + { + regex: 'Blogtrottr', + name: 'Blogtrottr', + url: '', + category: 'Feed Fetcher', + producer: { + name: 'Blogtrottr Ltd', + url: 'https://blogtrottr.com/', + }, + }, + { + regex: 'BoardReader Blog Indexer', + name: 'BoardReader Blog Indexer', + category: 'Crawler', + producer: { + name: 'BoardReader', + url: 'https://boardreader.com/', + }, + }, + { + regex: 'BountiiBot', + name: 'Bountii Bot', + category: 'Search bot', + url: 'http://bountii.com/contact.php', + producer: { + name: 'Bountii Inc.', + url: 'http://bountii.com', + }, + }, + { + regex: 'Browsershots', + name: 'Browsershots', + category: 'Service Agent', + url: 'http://browsershots.org/faq', + producer: { + name: 'Browsershots.org', + url: 'http://browsershots.org', + }, + }, + { + regex: 'BUbiNG', + name: 'BUbiNG', + category: 'Crawler', + url: 'http://law.di.unimi.it/BUbiNG.html', + producer: { + name: 'The Laboratory for Web Algorithmics (LAW)', + url: 'http://law.di.unimi.it/software.php#buging', + }, + }, + { + regex: '(? { + if (new RegExp(bot.regex).test(ua)) { + return true; + } + return false; + }); + + if (!res) { + return null; + } + + return { + name: res.name, + type: res.category || 'Unknown', + }; +} diff --git a/apps/api/src/controllers/event.controller.ts b/apps/api/src/controllers/event.controller.ts new file mode 100644 index 00000000..3b49567f --- /dev/null +++ b/apps/api/src/controllers/event.controller.ts @@ -0,0 +1,325 @@ +import { logger, logInfo, noop } from "@/utils/logger"; +import { getClientIp, parseIp } from "@/utils/parseIp"; +import { getReferrerWithQuery, parseReferrer } from "@/utils/parseReferrer"; +import { isUserAgentSet, parseUserAgent } from "@/utils/parseUserAgent"; +import { isSameDomain, parsePath } from "@/utils/url"; +import type { FastifyReply, FastifyRequest } from "fastify"; +import { omit } from "ramda"; +import { v4 as uuid } from "uuid"; + +import { generateDeviceId, getTime, toISOString } from "@openpanel/common"; +import type { IServiceCreateEventPayload } from "@openpanel/db"; +import { createEvent, getEvents, getSalts } from "@openpanel/db"; +import type { JobsOptions } from "@openpanel/queue"; +import { eventsQueue } from "@openpanel/queue"; +import { findJobByPrefix } from "@openpanel/queue/src/utils"; +import type { PostEventPayload } from "@openpanel/sdk"; + +const SESSION_TIMEOUT = 1000 * 60 * 30; +const SESSION_END_TIMEOUT = SESSION_TIMEOUT + 1000; + +async function withTiming(name: string, promise: T) { + try { + const start = Date.now(); + const res = await promise; + const end = Date.now(); + if (end - start > 1000) { + logInfo(`${name} took too long: ${end - start}ms`); + } + return res; + } catch (error) { + logger.error(error, `Failed to execute ${name}`); + throw error; + } +} + +function createContextLogger(request: FastifyRequest) { + const _log = request.log.child({ + requestId: request.id, + requestUrl: request.url, + headers: request.headers, + projectId: request.projectId, + }); + let obj: Record = {}; + return { + add: (key: string, value: unknown) => (obj[key] = value), + addObject: (key: string, value: Record) => { + obj = { ...obj, ...value }; + }, + send: (message: string, value: Record) => + _log.info({ ...obj, ...value }, message), + }; +} + +export async function postEvent( + request: FastifyRequest<{ + Body: PostEventPayload; + }>, + reply: FastifyReply, +) { + const contextLogger = createContextLogger(request); + let deviceId: string | null = null; + const { projectId, body } = request; + const properties = body.properties ?? {}; + const getProperty = (name: string): string | undefined => { + // replace thing is just for older sdks when we didn't have `__` + // remove when kiddokitchen app (24.09.02) is not used anymore + return ( + ((properties[name] || properties[name.replace("__", "")]) as + | string + | null + | undefined) ?? undefined + ); + }; + const profileId = body.profileId ?? ""; + const createdAt = new Date(body.timestamp); + const url = getProperty("__path"); + const { path, hash, query } = parsePath(url); + const referrer = isSameDomain(getProperty("__referrer"), url) + ? null + : parseReferrer(getProperty("__referrer")); + const utmReferrer = getReferrerWithQuery(query); + const ip = getClientIp(request)!; + const origin = request.headers.origin!; + const ua = request.headers["user-agent"]!; + const uaInfo = parseUserAgent(ua); + const salts = await getSalts(); + const currentDeviceId = generateDeviceId({ + salt: salts.current, + origin, + ip, + ua, + }); + const previousDeviceId = generateDeviceId({ + salt: salts.previous, + origin, + ip, + ua, + }); + + const isServerEvent = !ip && !origin && !isUserAgentSet(ua); + + if (isServerEvent) { + const [event] = await withTiming( + "Get last event (server-event)", + getEvents( + `SELECT * FROM events WHERE name = 'screen_view' AND profile_id = '${profileId}' AND project_id = '${projectId}' ORDER BY created_at DESC LIMIT 1`, + ), + ); + + eventsQueue.add("event", { + type: "createEvent", + payload: { + name: body.name, + deviceId: event?.deviceId || "", + sessionId: event?.sessionId || "", + profileId, + projectId, + properties: Object.assign( + {}, + omit(["__path", "__referrer"], properties), + { + hash, + query, + }, + ), + createdAt, + country: event?.country ?? "", + city: event?.city ?? "", + region: event?.region ?? "", + continent: event?.continent ?? "", + os: event?.os ?? "", + osVersion: event?.osVersion ?? "", + browser: event?.browser ?? "", + browserVersion: event?.browserVersion ?? "", + device: event?.device ?? "", + brand: event?.brand ?? "", + model: event?.model ?? "", + duration: 0, + path: event?.path ?? "", + referrer: event?.referrer ?? "", + referrerName: event?.referrerName ?? "", + referrerType: event?.referrerType ?? "", + profile: undefined, + meta: undefined, + }, + }); + return reply.status(200).send(""); + } + + const [geo, sessionEndJobCurrentDeviceId, sessionEndJobPreviousDeviceId] = + await withTiming( + "Get geo and jobs from queue", + Promise.all([ + parseIp(ip), + findJobByPrefix( + eventsQueue, + `sessionEnd:${projectId}:${currentDeviceId}:`, + ), + findJobByPrefix( + eventsQueue, + `sessionEnd:${projectId}:${previousDeviceId}:`, + ), + ]), + ); + + const createSessionStart = + !sessionEndJobCurrentDeviceId && !sessionEndJobPreviousDeviceId; + + if (sessionEndJobCurrentDeviceId && !sessionEndJobPreviousDeviceId) { + deviceId = currentDeviceId; + const diff = Date.now() - sessionEndJobCurrentDeviceId.timestamp; + sessionEndJobCurrentDeviceId.changeDelay(diff + SESSION_END_TIMEOUT); + } else if (!sessionEndJobCurrentDeviceId && sessionEndJobPreviousDeviceId) { + deviceId = previousDeviceId; + const diff = Date.now() - sessionEndJobPreviousDeviceId.timestamp; + sessionEndJobPreviousDeviceId.changeDelay(diff + SESSION_END_TIMEOUT); + } else { + deviceId = currentDeviceId; + // Queue session end + eventsQueue.add( + "event", + { + type: "createSessionEnd", + payload: { + deviceId, + }, + }, + { + delay: SESSION_END_TIMEOUT, + jobId: `sessionEnd:${projectId}:${deviceId}:${Date.now()}`, + }, + ); + } + + const [[sessionStartEvent], prevEventJob] = await withTiming( + "Get session start event", + Promise.all([ + getEvents( + `SELECT * FROM events WHERE name = 'session_start' AND device_id = '${deviceId}' AND project_id = '${projectId}' ORDER BY created_at DESC LIMIT 1`, + ), + findJobByPrefix(eventsQueue, `event:${projectId}:${deviceId}:`), + ]), + ); + + const payload: Omit = { + name: body.name, + deviceId, + profileId, + projectId, + sessionId: createSessionStart ? uuid() : sessionStartEvent?.sessionId ?? "", + properties: Object.assign({}, omit(["__path", "__referrer"], properties), { + hash, + query, + }), + createdAt, + country: geo.country, + city: geo.city, + region: geo.region, + continent: geo.continent, + os: uaInfo.os, + osVersion: uaInfo.osVersion, + browser: uaInfo.browser, + browserVersion: uaInfo.browserVersion, + device: uaInfo.device, + brand: uaInfo.brand, + model: uaInfo.model, + duration: 0, + path: path, + referrer: referrer?.url, + referrerName: referrer?.name ?? utmReferrer?.name ?? "", + referrerType: referrer?.type ?? utmReferrer?.type ?? "", + profile: undefined, + meta: undefined, + }; + + const isDelayed = prevEventJob ? await prevEventJob?.isDelayed() : false; + + if (isDelayed && prevEventJob && prevEventJob.data.type === "createEvent") { + const prevEvent = prevEventJob.data.payload; + const duration = getTime(payload.createdAt) - getTime(prevEvent.createdAt); + contextLogger.add("prevEvent", prevEvent); + + // Set path from prev screen_view event if current event is not a screen_view + if (payload.name != "screen_view") { + payload.path = prevEvent.path; + } + + if (payload.name === "screen_view") { + if (duration < 0) { + contextLogger.send("duration is wrong", { + payload, + duration, + }); + } else { + // Skip update duration if it's wrong + // Seems like request is not in right order + await withTiming( + "Update previous job with duration", + prevEventJob.updateData({ + type: "createEvent", + payload: { + ...prevEvent, + duration, + }, + }), + ); + } + + await withTiming("Promote previous job", prevEventJob.promote()); + } + } else if (payload.name !== "screen_view") { + contextLogger.send("no previous job", { + prevEventJob, + payload, + }); + } + + if (createSessionStart) { + // We do not need to queue session_start + await withTiming( + "Create session start event", + createEvent({ + ...payload, + name: "session_start", + // @ts-expect-error + createdAt: toISOString(getTime(payload.createdAt) - 100), + }), + ); + } + + const options: JobsOptions = {}; + if (payload.name === "screen_view") { + options.delay = SESSION_TIMEOUT; + options.jobId = `event:${projectId}:${deviceId}:${Date.now()}`; + } + + contextLogger.send("event is queued", { + ip, + origin, + ua, + uaInfo, + referrer, + profileId, + projectId, + deviceId, + geo, + sessionStartEvent, + path, + payload, + }); + + // Queue current event + eventsQueue + .add( + "event", + { + type: "createEvent", + payload, + }, + options, + ) + .catch(noop("Failed to queue event")); + + reply.status(202).send(deviceId); +} diff --git a/apps/api/src/controllers/live.controller.ts b/apps/api/src/controllers/live.controller.ts new file mode 100644 index 00000000..08db054e --- /dev/null +++ b/apps/api/src/controllers/live.controller.ts @@ -0,0 +1,109 @@ +import type { FastifyReply, FastifyRequest } from "fastify"; +import type * as WebSocket from "ws"; + +import { getSafeJson } from "@openpanel/common"; +import type { IServiceCreateEventPayload } from "@openpanel/db"; +import { getEvents, getLiveVisitors } from "@openpanel/db"; +import { redis, redisPub, redisSub } from "@openpanel/redis"; + +export function getLiveEventInfo(key: string) { + return key.split(":").slice(2) as [string, string]; +} + +export async function test( + req: FastifyRequest<{ + Params: { + projectId: string; + }; + }>, + reply: FastifyReply, +) { + const [event] = await getEvents( + `SELECT * FROM events WHERE project_id = '${req.params.projectId}' AND name = 'screen_view' LIMIT 1`, + ); + if (!event) { + return reply.status(404).send("No event found"); + } + redisPub.publish("event", JSON.stringify(event)); + redis.set( + `live:event:${event.projectId}:${Math.random() * 1000}`, + "", + "EX", + 10, + ); + reply.status(202).send(event); +} + +export function wsVisitors( + connection: { + socket: WebSocket; + }, + req: FastifyRequest<{ + Params: { + projectId: string; + }; + }>, +) { + const { params } = req; + + redisSub.subscribe("event"); + redisSub.psubscribe("__key*:expired"); + + const message = (channel: string, message: string) => { + if (channel === "event") { + const event = getSafeJson(message); + if (event?.projectId === params.projectId) { + getLiveVisitors(params.projectId).then((count) => { + connection.socket.send(String(count)); + }); + } + } + }; + const pmessage = (pattern: string, channel: string, message: string) => { + const [projectId] = getLiveEventInfo(message); + if (projectId && projectId === params.projectId) { + getLiveVisitors(params.projectId).then((count) => { + connection.socket.send(String(count)); + }); + } + }; + + redisSub.on("message", message); + redisSub.on("pmessage", pmessage); + + connection.socket.on("close", () => { + redisSub.unsubscribe("event"); + redisSub.punsubscribe("__key*:expired"); + redisSub.off("message", message); + redisSub.off("pmessage", pmessage); + }); +} + +export function wsEvents( + connection: { + socket: WebSocket; + }, + req: FastifyRequest<{ + Params: { + projectId: string; + }; + }>, +) { + const { params } = req; + + redisSub.subscribe("event"); + + const message = (channel: string, message: string) => { + const event = getSafeJson(message); + if (event?.projectId === params.projectId) { + connection.socket.send(JSON.stringify(event)); + } + }; + + redisSub.on("message", message); + + connection.socket.on("close", () => { + redisSub.unsubscribe("event"); + redisSub.off("message", message); + }); +} diff --git a/apps/api/src/controllers/misc.controller.ts b/apps/api/src/controllers/misc.controller.ts new file mode 100644 index 00000000..daa3ee7b --- /dev/null +++ b/apps/api/src/controllers/misc.controller.ts @@ -0,0 +1,127 @@ +import type { FastifyReply, FastifyRequest } from "fastify"; +import icoToPng from "ico-to-png"; +import sharp from "sharp"; + +import { createHash } from "@openpanel/common"; +import { redis } from "@openpanel/redis"; + +interface GetFaviconParams { + url: string; +} + +async function getImageBuffer(url: string) { + try { + const res = await fetch(url); + const contentType = res.headers.get("content-type"); + + if (!contentType?.includes("image")) { + return null; + } + + if (!res.ok) { + return null; + } + + if (contentType === "image/x-icon" || url.endsWith(".ico")) { + const arrayBuffer = await res.arrayBuffer(); + const buffer = Buffer.from(arrayBuffer); + return await icoToPng(buffer, 30); + } + + return await sharp(await res.arrayBuffer()) + .resize(30, 30, { + fit: "cover", + }) + .png() + .toBuffer(); + } catch (e) { + console.log("Failed to get image from url", url); + console.log(e); + } +} + +const imageExtensions = ["svg", "png", "jpg", "jpeg", "gif", "webp", "ico"]; + +export async function getFavicon( + request: FastifyRequest<{ + Querystring: GetFaviconParams; + }>, + reply: FastifyReply, +) { + function sendBuffer(buffer: Buffer, cacheKey?: string) { + if (cacheKey) { + redis.set(`favicon:${cacheKey}`, buffer.toString("base64")); + } + reply.type("image/png"); + console.log("buffer", buffer.byteLength); + + return reply.send(buffer); + } + + if (!request.query.url) { + return reply.status(404).send("Not found"); + } + + const url = decodeURIComponent(request.query.url); + + // DIRECT IMAGE + if (imageExtensions.find((ext) => url.endsWith(ext))) { + const cacheKey = createHash(url, 32); + const cache = await redis.get(`favicon:${cacheKey}`); + if (cache) { + return sendBuffer(Buffer.from(cache, "base64")); + } + const buffer = await getImageBuffer(url); + if (buffer && buffer.byteLength > 0) { + return sendBuffer(buffer, cacheKey); + } + } + + const { hostname, origin } = new URL(url); + const cache = await redis.get(`favicon:${hostname}`); + if (cache) { + return sendBuffer(Buffer.from(cache, "base64")); + } + + // TRY FAVICON.ICO + const buffer = await getImageBuffer(`${origin}/favicon.ico`); + if (buffer && buffer.byteLength > 0) { + return sendBuffer(buffer, hostname); + } + + // PARSE HTML + const res = await fetch(url).then((res) => res.text()); + + function findFavicon(res: string) { + const match = res.match( + /(\|\)/, + ); + if (!match) { + return null; + } + + return match[0].match(/href="(.+?)"/)?.[1] ?? null; + } + + const favicon = findFavicon(res); + if (favicon) { + const buffer = await getImageBuffer(favicon); + + if (buffer && buffer.byteLength > 0) { + return sendBuffer(buffer, hostname); + } + } + + return reply.status(404).send("Not found"); +} + +export async function clearFavicons( + request: FastifyRequest, + reply: FastifyReply, +) { + const keys = await redis.keys("favicon:*"); + for (const key of keys) { + await redis.del(key); + } + return reply.status(404).send("OK"); +} diff --git a/apps/api/src/controllers/profile.controller.ts b/apps/api/src/controllers/profile.controller.ts new file mode 100644 index 00000000..14befafb --- /dev/null +++ b/apps/api/src/controllers/profile.controller.ts @@ -0,0 +1,113 @@ +import { getClientIp, parseIp } from "@/utils/parseIp"; +import { isUserAgentSet, parseUserAgent } from "@/utils/parseUserAgent"; +import type { FastifyReply, FastifyRequest } from "fastify"; +import { assocPath, pathOr } from "ramda"; + +import { getProfileById, upsertProfile } from "@openpanel/db"; +import type { + IncrementProfilePayload, + UpdateProfilePayload, +} from "@openpanel/sdk"; + +export async function updateProfile( + request: FastifyRequest<{ + Body: UpdateProfilePayload; + }>, + reply: FastifyReply, +) { + const { profileId, properties, ...rest } = request.body; + const projectId = request.projectId; + const ip = getClientIp(request)!; + const ua = request.headers["user-agent"]!; + const uaInfo = parseUserAgent(ua); + const geo = await parseIp(ip); + + await upsertProfile({ + id: profileId, + projectId, + properties: { + ...(properties ?? {}), + ...(ip ? geo : {}), + ...(isUserAgentSet(ua) ? uaInfo : {}), + }, + ...rest, + }); + + reply.status(202).send(profileId); +} + +export async function incrementProfileProperty( + request: FastifyRequest<{ + Body: IncrementProfilePayload; + }>, + reply: FastifyReply, +) { + const { profileId, property, value } = request.body; + const projectId = request.projectId; + + const profile = await getProfileById(profileId); + if (!profile) { + return reply.status(404).send("Not found"); + } + + const parsed = parseInt( + pathOr("0", property.split("."), profile.properties), + 10, + ); + + if (isNaN(parsed)) { + return reply.status(400).send("Not number"); + } + + profile.properties = assocPath( + property.split("."), + parsed + value, + profile.properties, + ); + + await upsertProfile({ + id: profile.id, + projectId, + properties: profile.properties, + }); + + reply.status(202).send(profile.id); +} + +export async function decrementProfileProperty( + request: FastifyRequest<{ + Body: IncrementProfilePayload; + }>, + reply: FastifyReply, +) { + const { profileId, property, value } = request.body; + const projectId = request.projectId; + + const profile = await getProfileById(profileId); + if (!profile) { + return reply.status(404).send("Not found"); + } + + const parsed = parseInt( + pathOr("0", property.split("."), profile.properties), + 10, + ); + + if (isNaN(parsed)) { + return reply.status(400).send("Not number"); + } + + profile.properties = assocPath( + property.split("."), + parsed - value, + profile.properties, + ); + + await upsertProfile({ + id: profile.id, + projectId, + properties: profile.properties, + }); + + reply.status(202).send(profile.id); +} diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts new file mode 100644 index 00000000..3b53201b --- /dev/null +++ b/apps/api/src/index.ts @@ -0,0 +1,73 @@ +import cors from "@fastify/cors"; +import Fastify from "fastify"; + +import { redisPub } from "@openpanel/redis"; + +import eventRouter from "./routes/event.router"; +import liveRouter from "./routes/live.router"; +import miscRouter from "./routes/misc.router"; +import profileRouter from "./routes/profile.router"; +import { logger, logInfo } from "./utils/logger"; + +declare module "fastify" { + interface FastifyRequest { + projectId: string; + } +} + +const port = parseInt(process.env.API_PORT || "3000", 10); + +const startServer = async () => { + logInfo("Starting server"); + try { + const fastify = Fastify({ + logger: logger, + }); + + fastify.register(cors, { + origin: "*", + }); + + fastify.decorateRequest("projectId", ""); + fastify.register(eventRouter, { prefix: "/event" }); + fastify.register(profileRouter, { prefix: "/profile" }); + fastify.register(liveRouter, { prefix: "/live" }); + fastify.register(miscRouter, { prefix: "/misc" }); + fastify.setErrorHandler((error, request, reply) => { + fastify.log.error(error); + }); + fastify.get("/", (request, reply) => { + reply.send({ name: "openpanel sdk api" }); + }); + // fastify.get('/health-check', async (request, reply) => { + // try { + // await utils.healthCheck() + // reply.status(200).send() + // } catch (e) { + // reply.status(500).send() + // } + // }) + if (process.env.NODE_ENV === "production") { + for (const signal of ["SIGINT", "SIGTERM"]) { + process.on(signal, (err) => { + logger.fatal(err, `uncaught exception detected ${signal}`); + fastify.close().then((err) => { + process.exit(err ? 1 : 0); + }); + }); + } + } + + await fastify.listen({ + host: process.env.NODE_ENV === "production" ? "0.0.0.0" : "localhost", + port, + }); + + // Notify when keys expires + redisPub.config("SET", "notify-keyspace-events", "Ex"); + } catch (e) { + console.error(e); + } +}; + +startServer(); diff --git a/apps/api/src/referrers/index.ts b/apps/api/src/referrers/index.ts new file mode 100644 index 00000000..3bcba5ee --- /dev/null +++ b/apps/api/src/referrers/index.ts @@ -0,0 +1,2684 @@ +// This file is generated by the script get-referrers.ts + +// The data is fetch from snowplow-referer-parser https://github.com/snowplow-referer-parser/referer-parser +// The orginal referers.yml is based on Piwik's SearchEngines.php and Socials.php, copyright 2012 Matthieu Aubry and available under the GNU General Public License v3. + +const referrers: Record = { + 'support.google.com': { type: 'unknown', name: 'Google' }, + 'developers.google.com': { type: 'unknown', name: 'Google' }, + 'maps.google.com': { type: 'unknown', name: 'Google' }, + 'accounts.google.com': { type: 'unknown', name: 'Google' }, + 'drive.google.com': { type: 'unknown', name: 'Google' }, + 'sites.google.com': { type: 'unknown', name: 'Google' }, + 'groups.google.com': { type: 'unknown', name: 'Google' }, + 'groups.google.co.uk': { type: 'unknown', name: 'Google' }, + 'maps.yandex.ru': { type: 'unknown', name: 'Yandex Maps' }, + 'maps.yandex.ua': { type: 'unknown', name: 'Yandex Maps' }, + 'maps.yandex.com': { type: 'unknown', name: 'Yandex Maps' }, + 'maps.yandex.by': { type: 'unknown', name: 'Yandex Maps' }, + 'n.maps.yandex.ru': { type: 'unknown', name: 'Yandex Maps' }, + 'finance.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'news.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'eurosport.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'sports.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'astrology.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'travel.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'answers.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'screen.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'weather.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'messenger.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'games.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'shopping.yahoo.net': { type: 'unknown', name: 'Yahoo!' }, + 'movies.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'cars.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'lifestyle.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'omg.yahoo.com': { type: 'unknown', name: 'Yahoo!' }, + 'match.yahoo.net': { type: 'unknown', name: 'Yahoo!' }, + 'www.talktalk.co.uk': { type: 'search', name: 'TalkTalk' }, + '1.cz': { type: 'search', name: '1.cz' }, + 'search.softonic.com': { type: 'search', name: 'Softonic' }, + 'gais.cs.ccu.edu.tw': { type: 'search', name: 'GAIS' }, + 'search.freecause.com': { type: 'search', name: 'Freecause' }, + 'so.360.cn': { type: 'search', name: '360.cn' }, + 'www.so.com': { type: 'search', name: '360.cn' }, + 'rpmfind.net': { type: 'search', name: 'RPMFind' }, + 'fr2.rpmfind.net': { type: 'search', name: 'RPMFind' }, + 'serach.comcast.net': { type: 'search', name: 'Comcast' }, + 'search.ke.voila.fr': { type: 'search', name: 'Voila' }, + 'www.lemoteur.fr': { type: 'search', name: 'Voila' }, + 'search.nifty.com': { type: 'search', name: 'Nifty' }, + 'searchatlas.centrum.cz': { type: 'search', name: 'Atlas' }, + '2gis.ru': { type: 'search', name: '2gis' }, + 'www.2gis.ru': { type: 'search', name: '2gis' }, + 'link.2gis.ru': { type: 'search', name: '2gis' }, + 'www.link.2gis.ru': { type: 'search', name: '2gis' }, + 'lo.st': { type: 'search', name: 'Lo.st' }, + 'www1.dastelefonbuch.de': { type: 'search', name: 'DasTelefonbuch' }, + 'www.fireball.de': { type: 'search', name: 'Fireball' }, + 'search.1und1.de': { type: 'search', name: '1und1' }, + 'ricerca.virgilio.it': { type: 'search', name: 'Virgilio' }, + 'ricercaimmagini.virgilio.it': { type: 'search', name: 'Virgilio' }, + 'ricercavideo.virgilio.it': { type: 'search', name: 'Virgilio' }, + 'ricercanews.virgilio.it': { type: 'search', name: 'Virgilio' }, + 'mobile.virgilio.it': { type: 'search', name: 'Virgilio' }, + 'search.media.telstra.com.au': { type: 'search', name: 'Telstra' }, + 'www.web.nl': { type: 'search', name: 'Web.nl' }, + 'www.plazoo.com': { type: 'search', name: 'Plazoo' }, + 'www.goyellow.de': { type: 'search', name: 'Goyellow.de' }, + 'search.aol.com': { type: 'search', name: 'AOL' }, + 'search.aol.it': { type: 'search', name: 'AOL' }, + 'aolsearch.aol.com': { type: 'search', name: 'AOL' }, + 'aolsearch.com': { type: 'search', name: 'AOL' }, + 'www.aolrecherche.aol.fr': { type: 'search', name: 'AOL' }, + 'www.aolrecherches.aol.fr': { type: 'search', name: 'AOL' }, + 'www.aolimages.aol.fr': { type: 'search', name: 'AOL' }, + 'aim.search.aol.com': { type: 'search', name: 'AOL' }, + 'www.recherche.aol.fr': { type: 'search', name: 'AOL' }, + 'recherche.aol.fr': { type: 'search', name: 'AOL' }, + 'find.web.aol.com': { type: 'search', name: 'AOL' }, + 'recherche.aol.ca': { type: 'search', name: 'AOL' }, + 'aolsearch.aol.co.uk': { type: 'search', name: 'AOL' }, + 'search.aol.co.uk': { type: 'search', name: 'AOL' }, + 'aolrecherche.aol.fr': { type: 'search', name: 'AOL' }, + 'sucheaol.aol.de': { type: 'search', name: 'AOL' }, + 'suche.aol.de': { type: 'search', name: 'AOL' }, + 'suche.aolsvc.de': { type: 'search', name: 'AOL' }, + 'aolbusqueda.aol.com.mx': { type: 'search', name: 'AOL' }, + 'alicesuche.aol.de': { type: 'search', name: 'AOL' }, + 'alicesuchet.aol.de': { type: 'search', name: 'AOL' }, + 'suchet2.aol.de': { type: 'search', name: 'AOL' }, + 'search.hp.my.aol.com.au': { type: 'search', name: 'AOL' }, + 'search.hp.my.aol.de': { type: 'search', name: 'AOL' }, + 'search.hp.my.aol.it': { type: 'search', name: 'AOL' }, + 'search-intl.netscape.com': { type: 'search', name: 'AOL' }, + 'www.acoon.de': { type: 'search', name: 'Acoon' }, + 'search.free.fr': { type: 'search', name: 'Free' }, + 'search1-2.free.fr': { type: 'search', name: 'Free' }, + 'search1-1.free.fr': { type: 'search', name: 'Free' }, + 'apollo.lv/portal/search/': { type: 'search', name: 'Apollo Latvia' }, + 'www.highbeam.com': { type: 'search', name: 'HighBeam' }, + 'start.iplay.com': { type: 'search', name: 'I-play' }, + 'friendfeed.com': { type: 'search', name: 'FriendFeed' }, + 'www.yasni.de': { type: 'search', name: 'Yasni' }, + 'www.yasni.com': { type: 'search', name: 'Yasni' }, + 'www.yasni.co.uk': { type: 'search', name: 'Yasni' }, + 'www.yasni.ch': { type: 'search', name: 'Yasni' }, + 'www.yasni.at': { type: 'search', name: 'Yasni' }, + 'www.gigablast.com': { type: 'search', name: 'Gigablast' }, + 'dir.gigablast.com': { type: 'search', name: 'Gigablast' }, + 'www.arcor.de': { type: 'search', name: 'Arcor' }, + 'arama.com': { type: 'search', name: 'arama' }, + 'www.fixsuche.de': { type: 'search', name: 'Fixsuche' }, + 'apontador.com.br': { type: 'search', name: 'Apontador' }, + 'www.apontador.com.br': { type: 'search', name: 'Apontador' }, + 'www.search.com': { type: 'search', name: 'Search.com' }, + 'www.monstercrawler.com': { type: 'search', name: 'Monstercrawler' }, + 'google.ac/imgres': { type: 'search', name: 'Google Images' }, + 'google.ad/imgres': { type: 'search', name: 'Google Images' }, + 'google.ae/imgres': { type: 'search', name: 'Google Images' }, + 'google.am/imgres': { type: 'search', name: 'Google Images' }, + 'google.as/imgres': { type: 'search', name: 'Google Images' }, + 'google.at/imgres': { type: 'search', name: 'Google Images' }, + 'google.az/imgres': { type: 'search', name: 'Google Images' }, + 'google.ba/imgres': { type: 'search', name: 'Google Images' }, + 'google.be/imgres': { type: 'search', name: 'Google Images' }, + 'google.bf/imgres': { type: 'search', name: 'Google Images' }, + 'google.bg/imgres': { type: 'search', name: 'Google Images' }, + 'google.bi/imgres': { type: 'search', name: 'Google Images' }, + 'google.bj/imgres': { type: 'search', name: 'Google Images' }, + 'google.bs/imgres': { type: 'search', name: 'Google Images' }, + 'google.by/imgres': { type: 'search', name: 'Google Images' }, + 'google.ca/imgres': { type: 'search', name: 'Google Images' }, + 'google.cat/imgres': { type: 'search', name: 'Google Images' }, + 'google.cc/imgres': { type: 'search', name: 'Google Images' }, + 'google.cd/imgres': { type: 'search', name: 'Google Images' }, + 'google.cf/imgres': { type: 'search', name: 'Google Images' }, + 'google.cg/imgres': { type: 'search', name: 'Google Images' }, + 'google.ch/imgres': { type: 'search', name: 'Google Images' }, + 'google.ci/imgres': { type: 'search', name: 'Google Images' }, + 'google.cl/imgres': { type: 'search', name: 'Google Images' }, + 'google.cm/imgres': { type: 'search', name: 'Google Images' }, + 'google.cn/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.bw/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.ck/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.cr/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.id/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.il/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.in/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.jp/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.ke/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.kr/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.ls/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.ma/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.mz/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.nz/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.th/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.tz/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.ug/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.uk/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.uz/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.ve/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.vi/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.za/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.zm/imgres': { type: 'search', name: 'Google Images' }, + 'google.co.zw/imgres': { type: 'search', name: 'Google Images' }, + 'google.com/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.af/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.ag/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.ai/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.ar/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.au/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.bd/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.bh/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.bn/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.bo/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.br/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.by/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.bz/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.co/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.cu/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.cy/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.do/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.ec/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.eg/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.et/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.fj/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.gh/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.gi/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.gt/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.hk/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.jm/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.kh/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.kw/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.lb/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.lc/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.ly/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.mt/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.mx/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.my/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.na/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.nf/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.ng/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.ni/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.np/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.om/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.pa/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.pe/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.ph/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.pk/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.pr/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.py/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.qa/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.sa/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.sb/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.sg/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.sl/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.sv/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.tj/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.tn/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.tr/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.tw/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.ua/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.uy/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.vc/imgres': { type: 'search', name: 'Google Images' }, + 'google.com.vn/imgres': { type: 'search', name: 'Google Images' }, + 'google.cv/imgres': { type: 'search', name: 'Google Images' }, + 'google.cz/imgres': { type: 'search', name: 'Google Images' }, + 'google.de/imgres': { type: 'search', name: 'Google Images' }, + 'google.dj/imgres': { type: 'search', name: 'Google Images' }, + 'google.dk/imgres': { type: 'search', name: 'Google Images' }, + 'google.dm/imgres': { type: 'search', name: 'Google Images' }, + 'google.dz/imgres': { type: 'search', name: 'Google Images' }, + 'google.ee/imgres': { type: 'search', name: 'Google Images' }, + 'google.es/imgres': { type: 'search', name: 'Google Images' }, + 'google.fi/imgres': { type: 'search', name: 'Google Images' }, + 'google.fm/imgres': { type: 'search', name: 'Google Images' }, + 'google.fr/imgres': { type: 'search', name: 'Google Images' }, + 'google.ga/imgres': { type: 'search', name: 'Google Images' }, + 'google.gd/imgres': { type: 'search', name: 'Google Images' }, + 'google.ge/imgres': { type: 'search', name: 'Google Images' }, + 'google.gf/imgres': { type: 'search', name: 'Google Images' }, + 'google.gg/imgres': { type: 'search', name: 'Google Images' }, + 'google.gl/imgres': { type: 'search', name: 'Google Images' }, + 'google.gm/imgres': { type: 'search', name: 'Google Images' }, + 'google.gp/imgres': { type: 'search', name: 'Google Images' }, + 'google.gr/imgres': { type: 'search', name: 'Google Images' }, + 'google.gy/imgres': { type: 'search', name: 'Google Images' }, + 'google.hn/imgres': { type: 'search', name: 'Google Images' }, + 'google.hr/imgres': { type: 'search', name: 'Google Images' }, + 'google.ht/imgres': { type: 'search', name: 'Google Images' }, + 'google.hu/imgres': { type: 'search', name: 'Google Images' }, + 'google.ie/imgres': { type: 'search', name: 'Google Images' }, + 'google.im/imgres': { type: 'search', name: 'Google Images' }, + 'google.io/imgres': { type: 'search', name: 'Google Images' }, + 'google.iq/imgres': { type: 'search', name: 'Google Images' }, + 'google.is/imgres': { type: 'search', name: 'Google Images' }, + 'google.it/imgres': { type: 'search', name: 'Google Images' }, + 'google.it.ao/imgres': { type: 'search', name: 'Google Images' }, + 'google.je/imgres': { type: 'search', name: 'Google Images' }, + 'google.jo/imgres': { type: 'search', name: 'Google Images' }, + 'google.kg/imgres': { type: 'search', name: 'Google Images' }, + 'google.ki/imgres': { type: 'search', name: 'Google Images' }, + 'google.kz/imgres': { type: 'search', name: 'Google Images' }, + 'google.la/imgres': { type: 'search', name: 'Google Images' }, + 'google.li/imgres': { type: 'search', name: 'Google Images' }, + 'google.lk/imgres': { type: 'search', name: 'Google Images' }, + 'google.lt/imgres': { type: 'search', name: 'Google Images' }, + 'google.lu/imgres': { type: 'search', name: 'Google Images' }, + 'google.lv/imgres': { type: 'search', name: 'Google Images' }, + 'google.md/imgres': { type: 'search', name: 'Google Images' }, + 'google.me/imgres': { type: 'search', name: 'Google Images' }, + 'google.mg/imgres': { type: 'search', name: 'Google Images' }, + 'google.mk/imgres': { type: 'search', name: 'Google Images' }, + 'google.ml/imgres': { type: 'search', name: 'Google Images' }, + 'google.mn/imgres': { type: 'search', name: 'Google Images' }, + 'google.ms/imgres': { type: 'search', name: 'Google Images' }, + 'google.mu/imgres': { type: 'search', name: 'Google Images' }, + 'google.mv/imgres': { type: 'search', name: 'Google Images' }, + 'google.mw/imgres': { type: 'search', name: 'Google Images' }, + 'google.ne/imgres': { type: 'search', name: 'Google Images' }, + 'google.nl/imgres': { type: 'search', name: 'Google Images' }, + 'google.no/imgres': { type: 'search', name: 'Google Images' }, + 'google.nr/imgres': { type: 'search', name: 'Google Images' }, + 'google.nu/imgres': { type: 'search', name: 'Google Images' }, + 'google.pl/imgres': { type: 'search', name: 'Google Images' }, + 'google.pn/imgres': { type: 'search', name: 'Google Images' }, + 'google.ps/imgres': { type: 'search', name: 'Google Images' }, + 'google.pt/imgres': { type: 'search', name: 'Google Images' }, + 'google.ro/imgres': { type: 'search', name: 'Google Images' }, + 'google.rs/imgres': { type: 'search', name: 'Google Images' }, + 'google.ru/imgres': { type: 'search', name: 'Google Images' }, + 'google.rw/imgres': { type: 'search', name: 'Google Images' }, + 'google.sc/imgres': { type: 'search', name: 'Google Images' }, + 'google.se/imgres': { type: 'search', name: 'Google Images' }, + 'google.sh/imgres': { type: 'search', name: 'Google Images' }, + 'google.si/imgres': { type: 'search', name: 'Google Images' }, + 'google.sk/imgres': { type: 'search', name: 'Google Images' }, + 'google.sm/imgres': { type: 'search', name: 'Google Images' }, + 'google.sn/imgres': { type: 'search', name: 'Google Images' }, + 'google.so/imgres': { type: 'search', name: 'Google Images' }, + 'google.st/imgres': { type: 'search', name: 'Google Images' }, + 'google.td/imgres': { type: 'search', name: 'Google Images' }, + 'google.tg/imgres': { type: 'search', name: 'Google Images' }, + 'google.tk/imgres': { type: 'search', name: 'Google Images' }, + 'google.tl/imgres': { type: 'search', name: 'Google Images' }, + 'google.tm/imgres': { type: 'search', name: 'Google Images' }, + 'google.to/imgres': { type: 'search', name: 'Google Images' }, + 'google.tt/imgres': { type: 'search', name: 'Google Images' }, + 'google.us/imgres': { type: 'search', name: 'Google Images' }, + 'google.vg/imgres': { type: 'search', name: 'Google Images' }, + 'google.vu/imgres': { type: 'search', name: 'Google Images' }, + 'images.google.ws': { type: 'search', name: 'Google Images' }, + 'images.google.ac': { type: 'search', name: 'Google Images' }, + 'images.google.ad': { type: 'search', name: 'Google Images' }, + 'images.google.ae': { type: 'search', name: 'Google Images' }, + 'images.google.am': { type: 'search', name: 'Google Images' }, + 'images.google.as': { type: 'search', name: 'Google Images' }, + 'images.google.at': { type: 'search', name: 'Google Images' }, + 'images.google.az': { type: 'search', name: 'Google Images' }, + 'images.google.ba': { type: 'search', name: 'Google Images' }, + 'images.google.be': { type: 'search', name: 'Google Images' }, + 'images.google.bf': { type: 'search', name: 'Google Images' }, + 'images.google.bg': { type: 'search', name: 'Google Images' }, + 'images.google.bi': { type: 'search', name: 'Google Images' }, + 'images.google.bj': { type: 'search', name: 'Google Images' }, + 'images.google.bs': { type: 'search', name: 'Google Images' }, + 'images.google.by': { type: 'search', name: 'Google Images' }, + 'images.google.ca': { type: 'search', name: 'Google Images' }, + 'images.google.cat': { type: 'search', name: 'Google Images' }, + 'images.google.cc': { type: 'search', name: 'Google Images' }, + 'images.google.cd': { type: 'search', name: 'Google Images' }, + 'images.google.cf': { type: 'search', name: 'Google Images' }, + 'images.google.cg': { type: 'search', name: 'Google Images' }, + 'images.google.ch': { type: 'search', name: 'Google Images' }, + 'images.google.ci': { type: 'search', name: 'Google Images' }, + 'images.google.cl': { type: 'search', name: 'Google Images' }, + 'images.google.cm': { type: 'search', name: 'Google Images' }, + 'images.google.cn': { type: 'search', name: 'Google Images' }, + 'images.google.co.bw': { type: 'search', name: 'Google Images' }, + 'images.google.co.ck': { type: 'search', name: 'Google Images' }, + 'images.google.co.cr': { type: 'search', name: 'Google Images' }, + 'images.google.co.id': { type: 'search', name: 'Google Images' }, + 'images.google.co.il': { type: 'search', name: 'Google Images' }, + 'images.google.co.in': { type: 'search', name: 'Google Images' }, + 'images.google.co.jp': { type: 'search', name: 'Google Images' }, + 'images.google.co.ke': { type: 'search', name: 'Google Images' }, + 'images.google.co.kr': { type: 'search', name: 'Google Images' }, + 'images.google.co.ls': { type: 'search', name: 'Google Images' }, + 'images.google.co.ma': { type: 'search', name: 'Google Images' }, + 'images.google.co.mz': { type: 'search', name: 'Google Images' }, + 'images.google.co.nz': { type: 'search', name: 'Google Images' }, + 'images.google.co.th': { type: 'search', name: 'Google Images' }, + 'images.google.co.tz': { type: 'search', name: 'Google Images' }, + 'images.google.co.ug': { type: 'search', name: 'Google Images' }, + 'images.google.co.uk': { type: 'search', name: 'Google Images' }, + 'images.google.co.uz': { type: 'search', name: 'Google Images' }, + 'images.google.co.ve': { type: 'search', name: 'Google Images' }, + 'images.google.co.vi': { type: 'search', name: 'Google Images' }, + 'images.google.co.za': { type: 'search', name: 'Google Images' }, + 'images.google.co.zm': { type: 'search', name: 'Google Images' }, + 'images.google.co.zw': { type: 'search', name: 'Google Images' }, + 'images.google.com': { type: 'search', name: 'Google Images' }, + 'images.google.com.af': { type: 'search', name: 'Google Images' }, + 'images.google.com.ag': { type: 'search', name: 'Google Images' }, + 'images.google.com.ai': { type: 'search', name: 'Google Images' }, + 'images.google.com.ar': { type: 'search', name: 'Google Images' }, + 'images.google.com.au': { type: 'search', name: 'Google Images' }, + 'images.google.com.bd': { type: 'search', name: 'Google Images' }, + 'images.google.com.bh': { type: 'search', name: 'Google Images' }, + 'images.google.com.bn': { type: 'search', name: 'Google Images' }, + 'images.google.com.bo': { type: 'search', name: 'Google Images' }, + 'images.google.com.br': { type: 'search', name: 'Google Images' }, + 'images.google.com.by': { type: 'search', name: 'Google Images' }, + 'images.google.com.bz': { type: 'search', name: 'Google Images' }, + 'images.google.com.co': { type: 'search', name: 'Google Images' }, + 'images.google.com.cu': { type: 'search', name: 'Google Images' }, + 'images.google.com.cy': { type: 'search', name: 'Google Images' }, + 'images.google.com.do': { type: 'search', name: 'Google Images' }, + 'images.google.com.ec': { type: 'search', name: 'Google Images' }, + 'images.google.com.eg': { type: 'search', name: 'Google Images' }, + 'images.google.com.et': { type: 'search', name: 'Google Images' }, + 'images.google.com.fj': { type: 'search', name: 'Google Images' }, + 'images.google.com.gh': { type: 'search', name: 'Google Images' }, + 'images.google.com.gi': { type: 'search', name: 'Google Images' }, + 'images.google.com.gt': { type: 'search', name: 'Google Images' }, + 'images.google.com.hk': { type: 'search', name: 'Google Images' }, + 'images.google.com.jm': { type: 'search', name: 'Google Images' }, + 'images.google.com.kh': { type: 'search', name: 'Google Images' }, + 'images.google.com.kw': { type: 'search', name: 'Google Images' }, + 'images.google.com.lb': { type: 'search', name: 'Google Images' }, + 'images.google.com.lc': { type: 'search', name: 'Google Images' }, + 'images.google.com.ly': { type: 'search', name: 'Google Images' }, + 'images.google.com.mt': { type: 'search', name: 'Google Images' }, + 'images.google.com.mx': { type: 'search', name: 'Google Images' }, + 'images.google.com.my': { type: 'search', name: 'Google Images' }, + 'images.google.com.na': { type: 'search', name: 'Google Images' }, + 'images.google.com.nf': { type: 'search', name: 'Google Images' }, + 'images.google.com.ng': { type: 'search', name: 'Google Images' }, + 'images.google.com.ni': { type: 'search', name: 'Google Images' }, + 'images.google.com.np': { type: 'search', name: 'Google Images' }, + 'images.google.com.om': { type: 'search', name: 'Google Images' }, + 'images.google.com.pa': { type: 'search', name: 'Google Images' }, + 'images.google.com.pe': { type: 'search', name: 'Google Images' }, + 'images.google.com.ph': { type: 'search', name: 'Google Images' }, + 'images.google.com.pk': { type: 'search', name: 'Google Images' }, + 'images.google.com.pr': { type: 'search', name: 'Google Images' }, + 'images.google.com.py': { type: 'search', name: 'Google Images' }, + 'images.google.com.qa': { type: 'search', name: 'Google Images' }, + 'images.google.com.sa': { type: 'search', name: 'Google Images' }, + 'images.google.com.sb': { type: 'search', name: 'Google Images' }, + 'images.google.com.sg': { type: 'search', name: 'Google Images' }, + 'images.google.com.sl': { type: 'search', name: 'Google Images' }, + 'images.google.com.sv': { type: 'search', name: 'Google Images' }, + 'images.google.com.tj': { type: 'search', name: 'Google Images' }, + 'images.google.com.tn': { type: 'search', name: 'Google Images' }, + 'images.google.com.tr': { type: 'search', name: 'Google Images' }, + 'images.google.com.tw': { type: 'search', name: 'Google Images' }, + 'images.google.com.ua': { type: 'search', name: 'Google Images' }, + 'images.google.com.uy': { type: 'search', name: 'Google Images' }, + 'images.google.com.vc': { type: 'search', name: 'Google Images' }, + 'images.google.com.vn': { type: 'search', name: 'Google Images' }, + 'images.google.cv': { type: 'search', name: 'Google Images' }, + 'images.google.cz': { type: 'search', name: 'Google Images' }, + 'images.google.de': { type: 'search', name: 'Google Images' }, + 'images.google.dj': { type: 'search', name: 'Google Images' }, + 'images.google.dk': { type: 'search', name: 'Google Images' }, + 'images.google.dm': { type: 'search', name: 'Google Images' }, + 'images.google.dz': { type: 'search', name: 'Google Images' }, + 'images.google.ee': { type: 'search', name: 'Google Images' }, + 'images.google.es': { type: 'search', name: 'Google Images' }, + 'images.google.fi': { type: 'search', name: 'Google Images' }, + 'images.google.fm': { type: 'search', name: 'Google Images' }, + 'images.google.fr': { type: 'search', name: 'Google Images' }, + 'images.google.ga': { type: 'search', name: 'Google Images' }, + 'images.google.gd': { type: 'search', name: 'Google Images' }, + 'images.google.ge': { type: 'search', name: 'Google Images' }, + 'images.google.gf': { type: 'search', name: 'Google Images' }, + 'images.google.gg': { type: 'search', name: 'Google Images' }, + 'images.google.gl': { type: 'search', name: 'Google Images' }, + 'images.google.gm': { type: 'search', name: 'Google Images' }, + 'images.google.gp': { type: 'search', name: 'Google Images' }, + 'images.google.gr': { type: 'search', name: 'Google Images' }, + 'images.google.gy': { type: 'search', name: 'Google Images' }, + 'images.google.hn': { type: 'search', name: 'Google Images' }, + 'images.google.hr': { type: 'search', name: 'Google Images' }, + 'images.google.ht': { type: 'search', name: 'Google Images' }, + 'images.google.hu': { type: 'search', name: 'Google Images' }, + 'images.google.ie': { type: 'search', name: 'Google Images' }, + 'images.google.im': { type: 'search', name: 'Google Images' }, + 'images.google.io': { type: 'search', name: 'Google Images' }, + 'images.google.iq': { type: 'search', name: 'Google Images' }, + 'images.google.is': { type: 'search', name: 'Google Images' }, + 'images.google.it': { type: 'search', name: 'Google Images' }, + 'images.google.it.ao': { type: 'search', name: 'Google Images' }, + 'images.google.je': { type: 'search', name: 'Google Images' }, + 'images.google.jo': { type: 'search', name: 'Google Images' }, + 'images.google.kg': { type: 'search', name: 'Google Images' }, + 'images.google.ki': { type: 'search', name: 'Google Images' }, + 'images.google.kz': { type: 'search', name: 'Google Images' }, + 'images.google.la': { type: 'search', name: 'Google Images' }, + 'images.google.li': { type: 'search', name: 'Google Images' }, + 'images.google.lk': { type: 'search', name: 'Google Images' }, + 'images.google.lt': { type: 'search', name: 'Google Images' }, + 'images.google.lu': { type: 'search', name: 'Google Images' }, + 'images.google.lv': { type: 'search', name: 'Google Images' }, + 'images.google.md': { type: 'search', name: 'Google Images' }, + 'images.google.me': { type: 'search', name: 'Google Images' }, + 'images.google.mg': { type: 'search', name: 'Google Images' }, + 'images.google.mk': { type: 'search', name: 'Google Images' }, + 'images.google.ml': { type: 'search', name: 'Google Images' }, + 'images.google.mn': { type: 'search', name: 'Google Images' }, + 'images.google.ms': { type: 'search', name: 'Google Images' }, + 'images.google.mu': { type: 'search', name: 'Google Images' }, + 'images.google.mv': { type: 'search', name: 'Google Images' }, + 'images.google.mw': { type: 'search', name: 'Google Images' }, + 'images.google.ne': { type: 'search', name: 'Google Images' }, + 'images.google.nl': { type: 'search', name: 'Google Images' }, + 'images.google.no': { type: 'search', name: 'Google Images' }, + 'images.google.nr': { type: 'search', name: 'Google Images' }, + 'images.google.nu': { type: 'search', name: 'Google Images' }, + 'images.google.pl': { type: 'search', name: 'Google Images' }, + 'images.google.pn': { type: 'search', name: 'Google Images' }, + 'images.google.ps': { type: 'search', name: 'Google Images' }, + 'images.google.pt': { type: 'search', name: 'Google Images' }, + 'images.google.ro': { type: 'search', name: 'Google Images' }, + 'images.google.rs': { type: 'search', name: 'Google Images' }, + 'images.google.ru': { type: 'search', name: 'Google Images' }, + 'images.google.rw': { type: 'search', name: 'Google Images' }, + 'images.google.sc': { type: 'search', name: 'Google Images' }, + 'images.google.se': { type: 'search', name: 'Google Images' }, + 'images.google.sh': { type: 'search', name: 'Google Images' }, + 'images.google.si': { type: 'search', name: 'Google Images' }, + 'images.google.sk': { type: 'search', name: 'Google Images' }, + 'images.google.sm': { type: 'search', name: 'Google Images' }, + 'images.google.sn': { type: 'search', name: 'Google Images' }, + 'images.google.so': { type: 'search', name: 'Google Images' }, + 'images.google.st': { type: 'search', name: 'Google Images' }, + 'images.google.td': { type: 'search', name: 'Google Images' }, + 'images.google.tg': { type: 'search', name: 'Google Images' }, + 'images.google.tk': { type: 'search', name: 'Google Images' }, + 'images.google.tl': { type: 'search', name: 'Google Images' }, + 'images.google.tm': { type: 'search', name: 'Google Images' }, + 'images.google.to': { type: 'search', name: 'Google Images' }, + 'images.google.tt': { type: 'search', name: 'Google Images' }, + 'images.google.us': { type: 'search', name: 'Google Images' }, + 'images.google.vg': { type: 'search', name: 'Google Images' }, + 'images.google.vu': { type: 'search', name: 'Google Images' }, + 'abcsolk.no': { type: 'search', name: 'ABCsøk' }, + 'verden.abcsok.no': { type: 'search', name: 'ABCsøk' }, + 'google.ac/products': { type: 'search', name: 'Google Product Search' }, + 'google.ad/products': { type: 'search', name: 'Google Product Search' }, + 'google.ae/products': { type: 'search', name: 'Google Product Search' }, + 'google.am/products': { type: 'search', name: 'Google Product Search' }, + 'google.as/products': { type: 'search', name: 'Google Product Search' }, + 'google.at/products': { type: 'search', name: 'Google Product Search' }, + 'google.az/products': { type: 'search', name: 'Google Product Search' }, + 'google.ba/products': { type: 'search', name: 'Google Product Search' }, + 'google.be/products': { type: 'search', name: 'Google Product Search' }, + 'google.bf/products': { type: 'search', name: 'Google Product Search' }, + 'google.bg/products': { type: 'search', name: 'Google Product Search' }, + 'google.bi/products': { type: 'search', name: 'Google Product Search' }, + 'google.bj/products': { type: 'search', name: 'Google Product Search' }, + 'google.bs/products': { type: 'search', name: 'Google Product Search' }, + 'google.by/products': { type: 'search', name: 'Google Product Search' }, + 'google.ca/products': { type: 'search', name: 'Google Product Search' }, + 'google.cat/products': { type: 'search', name: 'Google Product Search' }, + 'google.cc/products': { type: 'search', name: 'Google Product Search' }, + 'google.cd/products': { type: 'search', name: 'Google Product Search' }, + 'google.cf/products': { type: 'search', name: 'Google Product Search' }, + 'google.cg/products': { type: 'search', name: 'Google Product Search' }, + 'google.ch/products': { type: 'search', name: 'Google Product Search' }, + 'google.ci/products': { type: 'search', name: 'Google Product Search' }, + 'google.cl/products': { type: 'search', name: 'Google Product Search' }, + 'google.cm/products': { type: 'search', name: 'Google Product Search' }, + 'google.cn/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.bw/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.ck/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.cr/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.id/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.il/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.in/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.jp/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.ke/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.kr/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.ls/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.ma/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.mz/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.nz/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.th/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.tz/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.ug/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.uk/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.uz/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.ve/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.vi/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.za/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.zm/products': { type: 'search', name: 'Google Product Search' }, + 'google.co.zw/products': { type: 'search', name: 'Google Product Search' }, + 'google.com/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.af/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.ag/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.ai/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.ar/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.au/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.bd/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.bh/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.bn/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.bo/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.br/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.by/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.bz/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.co/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.cu/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.cy/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.do/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.ec/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.eg/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.et/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.fj/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.gh/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.gi/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.gt/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.hk/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.jm/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.kh/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.kw/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.lb/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.lc/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.ly/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.mt/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.mx/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.my/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.na/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.nf/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.ng/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.ni/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.np/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.om/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.pa/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.pe/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.ph/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.pk/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.pr/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.py/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.qa/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.sa/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.sb/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.sg/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.sl/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.sv/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.tj/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.tn/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.tr/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.tw/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.ua/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.uy/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.vc/products': { type: 'search', name: 'Google Product Search' }, + 'google.com.vn/products': { type: 'search', name: 'Google Product Search' }, + 'google.cv/products': { type: 'search', name: 'Google Product Search' }, + 'google.cz/products': { type: 'search', name: 'Google Product Search' }, + 'google.de/products': { type: 'search', name: 'Google Product Search' }, + 'google.dj/products': { type: 'search', name: 'Google Product Search' }, + 'google.dk/products': { type: 'search', name: 'Google Product Search' }, + 'google.dm/products': { type: 'search', name: 'Google Product Search' }, + 'google.dz/products': { type: 'search', name: 'Google Product Search' }, + 'google.ee/products': { type: 'search', name: 'Google Product Search' }, + 'google.es/products': { type: 'search', name: 'Google Product Search' }, + 'google.fi/products': { type: 'search', name: 'Google Product Search' }, + 'google.fm/products': { type: 'search', name: 'Google Product Search' }, + 'google.fr/products': { type: 'search', name: 'Google Product Search' }, + 'google.ga/products': { type: 'search', name: 'Google Product Search' }, + 'google.gd/products': { type: 'search', name: 'Google Product Search' }, + 'google.ge/products': { type: 'search', name: 'Google Product Search' }, + 'google.gf/products': { type: 'search', name: 'Google Product Search' }, + 'google.gg/products': { type: 'search', name: 'Google Product Search' }, + 'google.gl/products': { type: 'search', name: 'Google Product Search' }, + 'google.gm/products': { type: 'search', name: 'Google Product Search' }, + 'google.gp/products': { type: 'search', name: 'Google Product Search' }, + 'google.gr/products': { type: 'search', name: 'Google Product Search' }, + 'google.gy/products': { type: 'search', name: 'Google Product Search' }, + 'google.hn/products': { type: 'search', name: 'Google Product Search' }, + 'google.hr/products': { type: 'search', name: 'Google Product Search' }, + 'google.ht/products': { type: 'search', name: 'Google Product Search' }, + 'google.hu/products': { type: 'search', name: 'Google Product Search' }, + 'google.ie/products': { type: 'search', name: 'Google Product Search' }, + 'google.im/products': { type: 'search', name: 'Google Product Search' }, + 'google.io/products': { type: 'search', name: 'Google Product Search' }, + 'google.iq/products': { type: 'search', name: 'Google Product Search' }, + 'google.is/products': { type: 'search', name: 'Google Product Search' }, + 'google.it/products': { type: 'search', name: 'Google Product Search' }, + 'google.it.ao/products': { type: 'search', name: 'Google Product Search' }, + 'google.je/products': { type: 'search', name: 'Google Product Search' }, + 'google.jo/products': { type: 'search', name: 'Google Product Search' }, + 'google.kg/products': { type: 'search', name: 'Google Product Search' }, + 'google.ki/products': { type: 'search', name: 'Google Product Search' }, + 'google.kz/products': { type: 'search', name: 'Google Product Search' }, + 'google.la/products': { type: 'search', name: 'Google Product Search' }, + 'google.li/products': { type: 'search', name: 'Google Product Search' }, + 'google.lk/products': { type: 'search', name: 'Google Product Search' }, + 'google.lt/products': { type: 'search', name: 'Google Product Search' }, + 'google.lu/products': { type: 'search', name: 'Google Product Search' }, + 'google.lv/products': { type: 'search', name: 'Google Product Search' }, + 'google.md/products': { type: 'search', name: 'Google Product Search' }, + 'google.me/products': { type: 'search', name: 'Google Product Search' }, + 'google.mg/products': { type: 'search', name: 'Google Product Search' }, + 'google.mk/products': { type: 'search', name: 'Google Product Search' }, + 'google.ml/products': { type: 'search', name: 'Google Product Search' }, + 'google.mn/products': { type: 'search', name: 'Google Product Search' }, + 'google.ms/products': { type: 'search', name: 'Google Product Search' }, + 'google.mu/products': { type: 'search', name: 'Google Product Search' }, + 'google.mv/products': { type: 'search', name: 'Google Product Search' }, + 'google.mw/products': { type: 'search', name: 'Google Product Search' }, + 'google.ne/products': { type: 'search', name: 'Google Product Search' }, + 'google.nl/products': { type: 'search', name: 'Google Product Search' }, + 'google.no/products': { type: 'search', name: 'Google Product Search' }, + 'google.nr/products': { type: 'search', name: 'Google Product Search' }, + 'google.nu/products': { type: 'search', name: 'Google Product Search' }, + 'google.pl/products': { type: 'search', name: 'Google Product Search' }, + 'google.pn/products': { type: 'search', name: 'Google Product Search' }, + 'google.ps/products': { type: 'search', name: 'Google Product Search' }, + 'google.pt/products': { type: 'search', name: 'Google Product Search' }, + 'google.ro/products': { type: 'search', name: 'Google Product Search' }, + 'google.rs/products': { type: 'search', name: 'Google Product Search' }, + 'google.ru/products': { type: 'search', name: 'Google Product Search' }, + 'google.rw/products': { type: 'search', name: 'Google Product Search' }, + 'google.sc/products': { type: 'search', name: 'Google Product Search' }, + 'google.se/products': { type: 'search', name: 'Google Product Search' }, + 'google.sh/products': { type: 'search', name: 'Google Product Search' }, + 'google.si/products': { type: 'search', name: 'Google Product Search' }, + 'google.sk/products': { type: 'search', name: 'Google Product Search' }, + 'google.sm/products': { type: 'search', name: 'Google Product Search' }, + 'google.sn/products': { type: 'search', name: 'Google Product Search' }, + 'google.so/products': { type: 'search', name: 'Google Product Search' }, + 'google.st/products': { type: 'search', name: 'Google Product Search' }, + 'google.td/products': { type: 'search', name: 'Google Product Search' }, + 'google.tg/products': { type: 'search', name: 'Google Product Search' }, + 'google.tk/products': { type: 'search', name: 'Google Product Search' }, + 'google.tl/products': { type: 'search', name: 'Google Product Search' }, + 'google.tm/products': { type: 'search', name: 'Google Product Search' }, + 'google.to/products': { type: 'search', name: 'Google Product Search' }, + 'google.tt/products': { type: 'search', name: 'Google Product Search' }, + 'google.us/products': { type: 'search', name: 'Google Product Search' }, + 'google.vg/products': { type: 'search', name: 'Google Product Search' }, + 'google.vu/products': { type: 'search', name: 'Google Product Search' }, + 'google.ws/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ac/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ad/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ae/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.am/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.as/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.at/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.az/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ba/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.be/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.bf/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.bg/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.bi/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.bj/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.bs/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.by/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ca/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.cat/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.cc/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.cd/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.cf/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.cg/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ch/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ci/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.cl/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.cm/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.cn/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.co.bw/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.ck/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.cr/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.id/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.il/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.in/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.jp/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.ke/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.kr/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.ls/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.ma/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.mz/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.nz/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.th/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.tz/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.ug/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.uk/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.uz/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.ve/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.vi/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.za/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.zm/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.co.zw/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.com.af/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.ag/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.ai/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.ar/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.au/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.bd/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.bh/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.bn/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.bo/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.br/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.by/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.bz/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.co/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.cu/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.cy/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.do/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.ec/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.eg/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.et/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.fj/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.gh/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.gi/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.gt/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.hk/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.jm/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.kh/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.kw/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.lb/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.lc/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.ly/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.mt/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.mx/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.my/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.na/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.nf/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.ng/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.ni/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.np/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.om/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.pa/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.pe/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.ph/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.pk/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.pr/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.py/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.qa/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.sa/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.sb/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.sg/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.sl/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.sv/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.tj/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.tn/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.tr/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.tw/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.ua/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.uy/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.vc/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.com.vn/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.cv/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.cz/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.de/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.dj/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.dk/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.dm/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.dz/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ee/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.es/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.fi/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.fm/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.fr/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ga/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.gd/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ge/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.gf/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.gg/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.gl/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.gm/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.gp/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.gr/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.gy/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.hn/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.hr/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ht/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.hu/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ie/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.im/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.io/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.iq/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.is/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.it/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.it.ao/products': { + type: 'search', + name: 'Google Product Search', + }, + 'www.google.je/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.jo/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.kg/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ki/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.kz/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.la/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.li/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.lk/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.lt/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.lu/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.lv/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.md/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.me/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.mg/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.mk/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ml/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.mn/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ms/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.mu/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.mv/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.mw/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ne/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.nl/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.no/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.nr/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.nu/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.pl/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.pn/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ps/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.pt/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ro/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.rs/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ru/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.rw/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.sc/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.se/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.sh/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.si/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.sk/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.sm/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.sn/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.so/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.st/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.td/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.tg/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.tk/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.tl/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.tm/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.to/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.tt/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.us/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.vg/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.vu/products': { type: 'search', name: 'Google Product Search' }, + 'www.google.ws/products': { type: 'search', name: 'Google Product Search' }, + 'www.dasoertliche.de': { type: 'search', name: 'DasOertliche' }, + 'infospace.com': { type: 'search', name: 'InfoSpace' }, + 'dogpile.com': { type: 'search', name: 'InfoSpace' }, + 'www.dogpile.com': { type: 'search', name: 'InfoSpace' }, + 'metacrawler.com': { type: 'search', name: 'InfoSpace' }, + 'webfetch.com': { type: 'search', name: 'InfoSpace' }, + 'webcrawler.com': { type: 'search', name: 'InfoSpace' }, + 'search.kiwee.com': { type: 'search', name: 'InfoSpace' }, + 'isearch.babylon.com': { type: 'search', name: 'InfoSpace' }, + 'start.facemoods.com': { type: 'search', name: 'InfoSpace' }, + 'search.magnetic.com': { type: 'search', name: 'InfoSpace' }, + 'search.searchcompletion.com': { type: 'search', name: 'InfoSpace' }, + 'clusty.com': { type: 'search', name: 'InfoSpace' }, + 'www.weborama.com': { type: 'search', name: 'Weborama' }, + 'search.bluewin.ch': { type: 'search', name: 'Bluewin' }, + 'search.bt.com': { type: 'search', name: 'British Telecommunications' }, + 'www.neti.ee': { type: 'search', name: 'Neti' }, + 'nigma.ru': { type: 'search', name: 'Nigma' }, + 'image.yahoo.cn': { type: 'search', name: 'Yahoo! Images' }, + 'images.search.yahoo.com': { type: 'search', name: 'Yahoo! Images' }, + 'www.exalead.fr': { type: 'search', name: 'Exalead' }, + 'www.exalead.com': { type: 'search', name: 'Exalead' }, + 'www.teoma.com': { type: 'search', name: 'Teoma' }, + 'ko.search.need2find.com': { type: 'search', name: 'Needtofind' }, + 'www.looksmart.com': { type: 'search', name: 'Looksmart' }, + 'inspsearch.com': { type: 'search', name: 'Flyingbird' }, + 'viview.inspsearch.com': { type: 'search', name: 'Flyingbird' }, + 'www.everyclick.com': { type: 'search', name: 'Everyclick' }, + 'szukaj.wp.pl': { type: 'search', name: 'Wirtualna Polska' }, + 'www.toolbarhome.com': { type: 'search', name: 'Toolbarhome' }, + 'vshare.toolbarhome.com': { type: 'search', name: 'Toolbarhome' }, + 'searchalot.com': { type: 'search', name: 'Searchalot' }, + 'yandex.ru': { type: 'search', name: 'Yandex' }, + 'yandex.ua': { type: 'search', name: 'Yandex' }, + 'yandex.com': { type: 'search', name: 'Yandex' }, + 'yandex.by': { type: 'search', name: 'Yandex' }, + 'www.yandex.ru': { type: 'search', name: 'Yandex' }, + 'www.yandex.ua': { type: 'search', name: 'Yandex' }, + 'www.yandex.com': { type: 'search', name: 'Yandex' }, + 'www.yandex.by': { type: 'search', name: 'Yandex' }, + 'clck.yandex.ru': { type: 'search', name: 'Yandex' }, + 'clck.yandex.ua': { type: 'search', name: 'Yandex' }, + 'clck.yandex.com': { type: 'search', name: 'Yandex' }, + 'clck.yandex.by': { type: 'search', name: 'Yandex' }, + 'de.indeed.com': { type: 'search', name: 'Indeed' }, + 'at.indeed.com': { type: 'search', name: 'Indeed' }, + 'fr.indeed.com': { type: 'search', name: 'Indeed' }, + 'it.indeed.com': { type: 'search', name: 'Indeed' }, + 'ch.indeed.com': { type: 'search', name: 'Indeed' }, + 'au.indeed.com': { type: 'search', name: 'Indeed' }, + 'web.canoe.ca': { type: 'search', name: 'canoe.ca' }, + 'websearch.cs.com': { type: 'search', name: 'Compuserve' }, + 'www.blogdigger.com': { type: 'search', name: 'Blogdigger' }, + 'startgoogle.startpagina.nl': { type: 'search', name: 'Startpagina' }, + 'eo.st': { type: 'search', name: 'eo' }, + 'p.zhongsou.com': { type: 'search', name: 'Zhongsou' }, + 'www.toile.com': { type: 'search', name: 'La Toile Du Quebec Via Google' }, + 'web.toile.com': { type: 'search', name: 'La Toile Du Quebec Via Google' }, + 'www.paperball.de': { type: 'search', name: 'Paperball' }, + 'www.stepstone.de': { type: 'search', name: 'StepStone' }, + 'www.stepstone.at': { type: 'search', name: 'StepStone' }, + 'www.stepstone.be': { type: 'search', name: 'StepStone' }, + 'www.stepstone.fr': { type: 'search', name: 'StepStone' }, + 'www.stepstone.nl': { type: 'search', name: 'StepStone' }, + 'www.stepstone.dk': { type: 'search', name: 'StepStone' }, + 'www.stepstone.se': { type: 'search', name: 'StepStone' }, + 'www.jungle-spider.de': { type: 'search', name: 'Jungle Spider' }, + 'search.peoplepc.com': { type: 'search', name: 'PeoplePC' }, + 'thesmartsearch.net': { type: 'search', name: 'The Smart Search' }, + 'www.thesmartsearch.net': { type: 'search', name: 'The Smart Search' }, + 's1.metacrawler.de': { type: 'search', name: 'MetaCrawler.de' }, + 's2.metacrawler.de': { type: 'search', name: 'MetaCrawler.de' }, + 's3.metacrawler.de': { type: 'search', name: 'MetaCrawler.de' }, + 'busca.orange.es': { type: 'search', name: 'Orange' }, + 'search.orange.co.uk': { type: 'search', name: 'Orange' }, + 'lemoteur.orange.fr': { type: 'search', name: 'Orange' }, + 'www.gulesider.no': { type: 'search', name: 'Gule Sider' }, + 'search.i.ua': { type: 'search', name: 'I.ua' }, + 'recherche.francite.com': { type: 'search', name: 'Francite' }, + 'search.tb.ask.com': { type: 'search', name: 'Ask Toolbar' }, + 'search.tut.by': { type: 'search', name: 'Tut.by' }, + 'www.trusted--search.com': { type: 'search', name: 'Trusted-Search' }, + 'search.goo.ne.jp': { type: 'search', name: 'goo' }, + 'ocnsearch.goo.ne.jp': { type: 'search', name: 'goo' }, + 'www.fastbrowsersearch.com': { type: 'search', name: 'Fast Browser Search' }, + 'kununu.com': { type: 'search', name: 'kununu' }, + 'web.volny.cz': { type: 'search', name: 'Volny' }, + 'blogs.icerocket.com': { type: 'search', name: 'Icerockeet' }, + 'buscador.terra.es': { type: 'search', name: 'Terra' }, + 'buscador.terra.cl': { type: 'search', name: 'Terra' }, + 'buscador.terra.com.br': { type: 'search', name: 'Terra' }, + 'amazon.com': { type: 'search', name: 'Amazon' }, + 'www.amazon.com': { type: 'search', name: 'Amazon' }, + 'szukaj.onet.pl': { type: 'search', name: 'Onet' }, + 'digg.com': { type: 'search', name: 'Digg' }, + 'www.abacho.de': { type: 'search', name: 'Abacho' }, + 'www.abacho.com': { type: 'search', name: 'Abacho' }, + 'www.abacho.co.uk': { type: 'search', name: 'Abacho' }, + 'www.se.abacho.com': { type: 'search', name: 'Abacho' }, + 'www.tr.abacho.com': { type: 'search', name: 'Abacho' }, + 'www.abacho.at': { type: 'search', name: 'Abacho' }, + 'www.abacho.fr': { type: 'search', name: 'Abacho' }, + 'www.abacho.es': { type: 'search', name: 'Abacho' }, + 'www.abacho.ch': { type: 'search', name: 'Abacho' }, + 'www.abacho.it': { type: 'search', name: 'Abacho' }, + 'www.maailm.com': { type: 'search', name: 'maailm' }, + 'www.flix.de': { type: 'search', name: 'Flix' }, + 'inbox.com/search/': { type: 'search', name: 'Inbox.com' }, + 'suche.freenet.de': { type: 'search', name: 'Freenet' }, + 'www.suchnase.de': { type: 'search', name: 'Suchnase' }, + 'google.dodo.com.au': { type: 'search', name: 'Dodo' }, + 'blogsearch.google.ac': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ad': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ae': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.am': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.as': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.at': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.az': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ba': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.be': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.bf': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.bg': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.bi': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.bj': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.bs': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.by': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ca': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.cat': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.cc': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.cd': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.cf': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.cg': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ch': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ci': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.cl': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.cm': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.cn': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.bw': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.ck': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.cr': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.id': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.il': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.in': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.jp': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.ke': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.kr': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.ls': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.ma': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.mz': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.nz': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.th': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.tz': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.ug': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.uk': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.uz': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.ve': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.vi': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.za': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.zm': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.co.zw': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.af': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.ag': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.ai': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.ar': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.au': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.bd': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.bh': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.bn': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.bo': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.br': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.by': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.bz': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.co': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.cu': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.cy': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.do': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.ec': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.eg': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.et': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.fj': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.gh': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.gi': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.gt': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.hk': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.jm': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.kh': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.kw': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.lb': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.lc': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.ly': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.mt': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.mx': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.my': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.na': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.nf': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.ng': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.ni': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.np': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.om': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.pa': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.pe': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.ph': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.pk': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.pr': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.py': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.qa': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.sa': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.sb': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.sg': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.sl': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.sv': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.tj': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.tn': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.tr': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.tw': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.ua': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.uy': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.vc': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.com.vn': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.cv': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.cz': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.de': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.dj': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.dk': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.dm': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.dz': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ee': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.es': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.fi': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.fm': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.fr': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ga': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.gd': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ge': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.gf': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.gg': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.gl': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.gm': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.gp': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.gr': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.gy': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.hn': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.hr': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ht': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.hu': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ie': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.im': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.io': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.iq': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.is': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.it': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.it.ao': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.je': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.jo': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.kg': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ki': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.kz': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.la': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.li': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.lk': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.lt': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.lu': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.lv': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.md': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.me': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.mg': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.mk': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ml': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.mn': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ms': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.mu': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.mv': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.mw': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ne': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.nl': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.no': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.nr': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.nu': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.pl': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.pn': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ps': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.pt': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ro': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.rs': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ru': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.rw': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.sc': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.se': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.sh': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.si': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.sk': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.sm': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.sn': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.so': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.st': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.td': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.tg': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.tk': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.tl': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.tm': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.to': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.tt': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.us': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.vg': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.vu': { type: 'search', name: 'Google Blogsearch' }, + 'blogsearch.google.ws': { type: 'search', name: 'Google Blogsearch' }, + 'poisk.ru': { type: 'search', name: 'Poisk.ru' }, + 'www.sharelook.fr': { type: 'search', name: 'Sharelook' }, + 'www.finderoo.com': { type: 'search', name: 'Finderoo' }, + 'www.najdi.si': { type: 'search', name: 'Najdi' }, + 'www.picsearch.com': { type: 'search', name: 'Picsearch' }, + 'mail.ru': { type: 'search', name: 'Mail.ru' }, + 'm.mail.ru': { type: 'search', name: 'Mail.ru' }, + 'go.mail.ru': { type: 'search', name: 'Mail.ru' }, + 'alexa.com': { type: 'search', name: 'Alexa' }, + 'search.toolbars.alexa.com': { type: 'search', name: 'Alexa' }, + 'meta.rrzn.uni-hannover.de': { type: 'search', name: 'Metager' }, + 'www.metager.de': { type: 'search', name: 'Metager' }, + 'technorati.com': { type: 'search', name: 'Technorati' }, + 'searches.globososo.com': { type: 'search', name: 'Globososo' }, + 'search.globososo.com': { type: 'search', name: 'Globososo' }, + 'search.www.ee': { type: 'search', name: 'WWW' }, + 'www.trouvez.com': { type: 'search', name: 'Trouvez.com' }, + 'ixquick.com': { type: 'search', name: 'IXquick' }, + 'www.eu.ixquick.com': { type: 'search', name: 'IXquick' }, + 'ixquick.de': { type: 'search', name: 'IXquick' }, + 'www.ixquick.de': { type: 'search', name: 'IXquick' }, + 'us.ixquick.com': { type: 'search', name: 'IXquick' }, + 's1.us.ixquick.com': { type: 'search', name: 'IXquick' }, + 's2.us.ixquick.com': { type: 'search', name: 'IXquick' }, + 's3.us.ixquick.com': { type: 'search', name: 'IXquick' }, + 's4.us.ixquick.com': { type: 'search', name: 'IXquick' }, + 's5.us.ixquick.com': { type: 'search', name: 'IXquick' }, + 'eu.ixquick.com': { type: 'search', name: 'IXquick' }, + 's8-eu.ixquick.com': { type: 'search', name: 'IXquick' }, + 's1-eu.ixquick.de': { type: 'search', name: 'IXquick' }, + 'image.search.naver.com': { type: 'search', name: 'Naver Images' }, + 'imagesearch.naver.com': { type: 'search', name: 'Naver Images' }, + 'www.zapmeta.com': { type: 'search', name: 'Zapmeta' }, + 'www.zapmeta.nl': { type: 'search', name: 'Zapmeta' }, + 'www.zapmeta.de': { type: 'search', name: 'Zapmeta' }, + 'uk.zapmeta.com': { type: 'search', name: 'Zapmeta' }, + 'search.yippy.com': { type: 'search', name: 'Yippy' }, + 'pesquisa.clix.pt': { type: 'search', name: 'Clix' }, + 'www.walhello.info': { type: 'search', name: 'Walhello' }, + 'www.walhello.com': { type: 'search', name: 'Walhello' }, + 'www.walhello.de': { type: 'search', name: 'Walhello' }, + 'www.walhello.nl': { type: 'search', name: 'Walhello' }, + 'meta.ua': { type: 'search', name: 'Meta' }, + 'www.skynet.be': { type: 'search', name: 'Skynet' }, + 'www.searchy.co.uk': { type: 'search', name: 'Searchy' }, + 'search.findwide.com': { type: 'search', name: 'Findwide' }, + 'www.websearch.com': { type: 'search', name: 'WebSearch' }, + 'nova.rambler.ru': { type: 'search', name: 'Rambler' }, + 'www.latne.lv': { type: 'search', name: 'Latne' }, + 'mysearch.com': { type: 'search', name: 'MySearch' }, + 'www.mysearch.com': { type: 'search', name: 'MySearch' }, + 'ms114.mysearch.com': { type: 'search', name: 'MySearch' }, + 'ms146.mysearch.com': { type: 'search', name: 'MySearch' }, + 'kf.mysearch.myway.com': { type: 'search', name: 'MySearch' }, + 'ki.mysearch.myway.com': { type: 'search', name: 'MySearch' }, + 'search.myway.com': { type: 'search', name: 'MySearch' }, + 'search.mywebsearch.com': { type: 'search', name: 'MySearch' }, + 'www.cuil.com': { type: 'search', name: 'Cuil' }, + 'www.tixuma.de': { type: 'search', name: 'Tixuma' }, + 'pesquisa.sapo.pt': { type: 'search', name: 'Sapo' }, + 'www.gnadenmeer.de': { type: 'search', name: 'Gnadenmeer' }, + 'search.lilo.org': { type: 'search', name: 'Lilo' }, + 'search.naver.com': { type: 'search', name: 'Naver' }, + 'www.zoeken.nl': { type: 'search', name: 'Zoeken' }, + 'www.startsiden.no': { type: 'search', name: 'Startsiden' }, + 'search.yam.com': { type: 'search', name: 'Yam' }, + 'www.eniro.se': { type: 'search', name: 'Eniro' }, + 'apollo7.de': { type: 'search', name: 'APOLL07' }, + 'cgi.search.biglobe.ne.jp': { type: 'search', name: 'Biglobe' }, + 'www.mozbot.fr': { type: 'search', name: 'Mozbot' }, + 'www.mozbot.co.uk': { type: 'search', name: 'Mozbot' }, + 'www.mozbot.com': { type: 'search', name: 'Mozbot' }, + 'www.icq.com': { type: 'search', name: 'ICQ' }, + 'search.icq.com': { type: 'search', name: 'ICQ' }, + 'www.baidu.com': { type: 'search', name: 'Baidu' }, + 'www1.baidu.com': { type: 'search', name: 'Baidu' }, + 'zhidao.baidu.com': { type: 'search', name: 'Baidu' }, + 'tieba.baidu.com': { type: 'search', name: 'Baidu' }, + 'news.baidu.com': { type: 'search', name: 'Baidu' }, + 'web.gougou.com': { type: 'search', name: 'Baidu' }, + 'm.baidu.com': { type: 'search', name: 'Baidu' }, + 'search.conduit.com': { type: 'search', name: 'Conduit' }, + 'www.vindex.nl': { type: 'search', name: 'Vindex' }, + 'search.vindex.nl': { type: 'search', name: 'Vindex' }, + 'search.babylon.com': { type: 'search', name: 'Babylon' }, + 'searchassist.babylon.com': { type: 'search', name: 'Babylon' }, + 'www.trovarapido.com': { type: 'search', name: 'TrovaRapido' }, + 'search.winamp.com': { type: 'search', name: 'Winamp' }, + 'www.suchmaschine.com': { type: 'search', name: 'Suchmaschine.com' }, + 'search.lycos.com': { type: 'search', name: 'Lycos' }, + 'www.lycos.com': { type: 'search', name: 'Lycos' }, + 'lycos.com': { type: 'search', name: 'Lycos' }, + 'www.vinden.nl': { type: 'search', name: 'Vinden' }, + 'www.altavista.com': { type: 'search', name: 'Altavista' }, + 'search.altavista.com': { type: 'search', name: 'Altavista' }, + 'listings.altavista.com': { type: 'search', name: 'Altavista' }, + 'altavista.de': { type: 'search', name: 'Altavista' }, + 'altavista.fr': { type: 'search', name: 'Altavista' }, + 'be-nl.altavista.com': { type: 'search', name: 'Altavista' }, + 'be-fr.altavista.com': { type: 'search', name: 'Altavista' }, + 'dmoz.org': { type: 'search', name: 'dmoz' }, + 'editors.dmoz.org': { type: 'search', name: 'dmoz' }, + 'ecosia.org': { type: 'search', name: 'Ecosia' }, + 'maxwebsearch.com': { type: 'search', name: 'Maxwebsearch' }, + 'www.euroseek.com': { type: 'search', name: 'Euroseek' }, + 'www.qwant.com': { type: 'search', name: 'Qwant' }, + 'lite.qwant.com': { type: 'search', name: 'Qwant' }, + 'www.x-recherche.com': { type: 'search', name: 'X-recherche' }, + 'images.yandex.ru': { type: 'search', name: 'Yandex Images' }, + 'images.yandex.ua': { type: 'search', name: 'Yandex Images' }, + 'images.yandex.com': { type: 'search', name: 'Yandex Images' }, + 'images.yandex.by': { type: 'search', name: 'Yandex Images' }, + 'suche.gmx.net': { type: 'search', name: 'GMX' }, + 'daemon-search.com': { type: 'search', name: 'Daemon search' }, + 'my.daemon-search.com': { type: 'search', name: 'Daemon search' }, + 'so.m.sm.cn': { type: 'search', name: 'Shenma' }, + 'yz.m.sm.cn': { type: 'search', name: 'Shenma' }, + 'm.sm.cn': { type: 'search', name: 'Shenma' }, + 'quark.sm.cn': { type: 'search', name: 'Shenma' }, + 'm.sp.sm.cn': { type: 'search', name: 'Shenma' }, + 'm.yz2.sm.cn': { type: 'search', name: 'Shenma' }, + 'm.yz.sm.cn': { type: 'search', name: 'Shenma' }, + 'www.firstsfind.com': { type: 'search', name: 'Firstfind' }, + 'www.crawler.com': { type: 'search', name: 'Crawler' }, + 'holmes.ge': { type: 'search', name: 'Holmes' }, + 'www.charter.net': { type: 'search', name: 'Charter' }, + 'www.ilse.nl': { type: 'search', name: 'Ilse' }, + 'search.earthlink.net': { type: 'search', name: 'earthlink' }, + 'www.qualigo.at': { type: 'search', name: 'Qualigo' }, + 'www.qualigo.ch': { type: 'search', name: 'Qualigo' }, + 'www.qualigo.de': { type: 'search', name: 'Qualigo' }, + 'www.qualigo.nl': { type: 'search', name: 'Qualigo' }, + 'ariadna.elmundo.es': { type: 'search', name: 'El Mundo' }, + 'metager2.de': { type: 'search', name: 'Metager2' }, + 'forestle.org': { type: 'search', name: 'Forestle' }, + 'www.forestle.org': { type: 'search', name: 'Forestle' }, + 'forestle.mobi': { type: 'search', name: 'Forestle' }, + 'www.search.ch': { type: 'search', name: 'Search.ch' }, + 'liveinternet.ru': { type: 'search', name: 'Liveinternet' }, + 'www.meinestadt.de': { type: 'search', name: 'Meinestadt' }, + 'www.fresh-weather.com': { type: 'search', name: 'Freshweather' }, + 'www.alltheweb.com': { type: 'search', name: 'AllTheWeb' }, + 'coccoc.com': { type: 'search', name: 'Coccoc' }, + 'search.snapdo.com': { type: 'search', name: 'Snapdo' }, + 'search.ukr.net': { type: 'search', name: 'UKR.net' }, + 'www3.zoek.nl': { type: 'search', name: 'Zoek' }, + 'search.daum.net': { type: 'search', name: 'Daum' }, + 'www.marktplaats.nl': { type: 'search', name: 'Marktplaats' }, + 'suche.info': { type: 'search', name: 'suche.info' }, + 'news.google.ac': { type: 'search', name: 'Google News' }, + 'news.google.ad': { type: 'search', name: 'Google News' }, + 'news.google.ae': { type: 'search', name: 'Google News' }, + 'news.google.am': { type: 'search', name: 'Google News' }, + 'news.google.as': { type: 'search', name: 'Google News' }, + 'news.google.at': { type: 'search', name: 'Google News' }, + 'news.google.az': { type: 'search', name: 'Google News' }, + 'news.google.ba': { type: 'search', name: 'Google News' }, + 'news.google.be': { type: 'search', name: 'Google News' }, + 'news.google.bf': { type: 'search', name: 'Google News' }, + 'news.google.bg': { type: 'search', name: 'Google News' }, + 'news.google.bi': { type: 'search', name: 'Google News' }, + 'news.google.bj': { type: 'search', name: 'Google News' }, + 'news.google.bs': { type: 'search', name: 'Google News' }, + 'news.google.by': { type: 'search', name: 'Google News' }, + 'news.google.ca': { type: 'search', name: 'Google News' }, + 'news.google.cat': { type: 'search', name: 'Google News' }, + 'news.google.cc': { type: 'search', name: 'Google News' }, + 'news.google.cd': { type: 'search', name: 'Google News' }, + 'news.google.cf': { type: 'search', name: 'Google News' }, + 'news.google.cg': { type: 'search', name: 'Google News' }, + 'news.google.ch': { type: 'search', name: 'Google News' }, + 'news.google.ci': { type: 'search', name: 'Google News' }, + 'news.google.cl': { type: 'search', name: 'Google News' }, + 'news.google.cm': { type: 'search', name: 'Google News' }, + 'news.google.cn': { type: 'search', name: 'Google News' }, + 'news.google.co.bw': { type: 'search', name: 'Google News' }, + 'news.google.co.ck': { type: 'search', name: 'Google News' }, + 'news.google.co.cr': { type: 'search', name: 'Google News' }, + 'news.google.co.id': { type: 'search', name: 'Google News' }, + 'news.google.co.il': { type: 'search', name: 'Google News' }, + 'news.google.co.in': { type: 'search', name: 'Google News' }, + 'news.google.co.jp': { type: 'search', name: 'Google News' }, + 'news.google.co.ke': { type: 'search', name: 'Google News' }, + 'news.google.co.kr': { type: 'search', name: 'Google News' }, + 'news.google.co.ls': { type: 'search', name: 'Google News' }, + 'news.google.co.ma': { type: 'search', name: 'Google News' }, + 'news.google.co.mz': { type: 'search', name: 'Google News' }, + 'news.google.co.nz': { type: 'search', name: 'Google News' }, + 'news.google.co.th': { type: 'search', name: 'Google News' }, + 'news.google.co.tz': { type: 'search', name: 'Google News' }, + 'news.google.co.ug': { type: 'search', name: 'Google News' }, + 'news.google.co.uk': { type: 'search', name: 'Google News' }, + 'news.google.co.uz': { type: 'search', name: 'Google News' }, + 'news.google.co.ve': { type: 'search', name: 'Google News' }, + 'news.google.co.vi': { type: 'search', name: 'Google News' }, + 'news.google.co.za': { type: 'search', name: 'Google News' }, + 'news.google.co.zm': { type: 'search', name: 'Google News' }, + 'news.google.co.zw': { type: 'search', name: 'Google News' }, + 'news.google.com': { type: 'search', name: 'Google News' }, + 'news.google.com.af': { type: 'search', name: 'Google News' }, + 'news.google.com.ag': { type: 'search', name: 'Google News' }, + 'news.google.com.ai': { type: 'search', name: 'Google News' }, + 'news.google.com.ar': { type: 'search', name: 'Google News' }, + 'news.google.com.au': { type: 'search', name: 'Google News' }, + 'news.google.com.bd': { type: 'search', name: 'Google News' }, + 'news.google.com.bh': { type: 'search', name: 'Google News' }, + 'news.google.com.bn': { type: 'search', name: 'Google News' }, + 'news.google.com.bo': { type: 'search', name: 'Google News' }, + 'news.google.com.br': { type: 'search', name: 'Google News' }, + 'news.google.com.by': { type: 'search', name: 'Google News' }, + 'news.google.com.bz': { type: 'search', name: 'Google News' }, + 'news.google.com.co': { type: 'search', name: 'Google News' }, + 'news.google.com.cu': { type: 'search', name: 'Google News' }, + 'news.google.com.cy': { type: 'search', name: 'Google News' }, + 'news.google.com.do': { type: 'search', name: 'Google News' }, + 'news.google.com.ec': { type: 'search', name: 'Google News' }, + 'news.google.com.eg': { type: 'search', name: 'Google News' }, + 'news.google.com.et': { type: 'search', name: 'Google News' }, + 'news.google.com.fj': { type: 'search', name: 'Google News' }, + 'news.google.com.gh': { type: 'search', name: 'Google News' }, + 'news.google.com.gi': { type: 'search', name: 'Google News' }, + 'news.google.com.gt': { type: 'search', name: 'Google News' }, + 'news.google.com.hk': { type: 'search', name: 'Google News' }, + 'news.google.com.jm': { type: 'search', name: 'Google News' }, + 'news.google.com.kh': { type: 'search', name: 'Google News' }, + 'news.google.com.kw': { type: 'search', name: 'Google News' }, + 'news.google.com.lb': { type: 'search', name: 'Google News' }, + 'news.google.com.lc': { type: 'search', name: 'Google News' }, + 'news.google.com.ly': { type: 'search', name: 'Google News' }, + 'news.google.com.mt': { type: 'search', name: 'Google News' }, + 'news.google.com.mx': { type: 'search', name: 'Google News' }, + 'news.google.com.my': { type: 'search', name: 'Google News' }, + 'news.google.com.na': { type: 'search', name: 'Google News' }, + 'news.google.com.nf': { type: 'search', name: 'Google News' }, + 'news.google.com.ng': { type: 'search', name: 'Google News' }, + 'news.google.com.ni': { type: 'search', name: 'Google News' }, + 'news.google.com.np': { type: 'search', name: 'Google News' }, + 'news.google.com.om': { type: 'search', name: 'Google News' }, + 'news.google.com.pa': { type: 'search', name: 'Google News' }, + 'news.google.com.pe': { type: 'search', name: 'Google News' }, + 'news.google.com.ph': { type: 'search', name: 'Google News' }, + 'news.google.com.pk': { type: 'search', name: 'Google News' }, + 'news.google.com.pr': { type: 'search', name: 'Google News' }, + 'news.google.com.py': { type: 'search', name: 'Google News' }, + 'news.google.com.qa': { type: 'search', name: 'Google News' }, + 'news.google.com.sa': { type: 'search', name: 'Google News' }, + 'news.google.com.sb': { type: 'search', name: 'Google News' }, + 'news.google.com.sg': { type: 'search', name: 'Google News' }, + 'news.google.com.sl': { type: 'search', name: 'Google News' }, + 'news.google.com.sv': { type: 'search', name: 'Google News' }, + 'news.google.com.tj': { type: 'search', name: 'Google News' }, + 'news.google.com.tn': { type: 'search', name: 'Google News' }, + 'news.google.com.tr': { type: 'search', name: 'Google News' }, + 'news.google.com.tw': { type: 'search', name: 'Google News' }, + 'news.google.com.ua': { type: 'search', name: 'Google News' }, + 'news.google.com.uy': { type: 'search', name: 'Google News' }, + 'news.google.com.vc': { type: 'search', name: 'Google News' }, + 'news.google.com.vn': { type: 'search', name: 'Google News' }, + 'news.google.cv': { type: 'search', name: 'Google News' }, + 'news.google.cz': { type: 'search', name: 'Google News' }, + 'news.google.de': { type: 'search', name: 'Google News' }, + 'news.google.dj': { type: 'search', name: 'Google News' }, + 'news.google.dk': { type: 'search', name: 'Google News' }, + 'news.google.dm': { type: 'search', name: 'Google News' }, + 'news.google.dz': { type: 'search', name: 'Google News' }, + 'news.google.ee': { type: 'search', name: 'Google News' }, + 'news.google.es': { type: 'search', name: 'Google News' }, + 'news.google.fi': { type: 'search', name: 'Google News' }, + 'news.google.fm': { type: 'search', name: 'Google News' }, + 'news.google.fr': { type: 'search', name: 'Google News' }, + 'news.google.ga': { type: 'search', name: 'Google News' }, + 'news.google.gd': { type: 'search', name: 'Google News' }, + 'news.google.ge': { type: 'search', name: 'Google News' }, + 'news.google.gf': { type: 'search', name: 'Google News' }, + 'news.google.gg': { type: 'search', name: 'Google News' }, + 'news.google.gl': { type: 'search', name: 'Google News' }, + 'news.google.gm': { type: 'search', name: 'Google News' }, + 'news.google.gp': { type: 'search', name: 'Google News' }, + 'news.google.gr': { type: 'search', name: 'Google News' }, + 'news.google.gy': { type: 'search', name: 'Google News' }, + 'news.google.hn': { type: 'search', name: 'Google News' }, + 'news.google.hr': { type: 'search', name: 'Google News' }, + 'news.google.ht': { type: 'search', name: 'Google News' }, + 'news.google.hu': { type: 'search', name: 'Google News' }, + 'news.google.ie': { type: 'search', name: 'Google News' }, + 'news.google.im': { type: 'search', name: 'Google News' }, + 'news.google.io': { type: 'search', name: 'Google News' }, + 'news.google.iq': { type: 'search', name: 'Google News' }, + 'news.google.is': { type: 'search', name: 'Google News' }, + 'news.google.it': { type: 'search', name: 'Google News' }, + 'news.google.it.ao': { type: 'search', name: 'Google News' }, + 'news.google.je': { type: 'search', name: 'Google News' }, + 'news.google.jo': { type: 'search', name: 'Google News' }, + 'news.google.kg': { type: 'search', name: 'Google News' }, + 'news.google.ki': { type: 'search', name: 'Google News' }, + 'news.google.kz': { type: 'search', name: 'Google News' }, + 'news.google.la': { type: 'search', name: 'Google News' }, + 'news.google.li': { type: 'search', name: 'Google News' }, + 'news.google.lk': { type: 'search', name: 'Google News' }, + 'news.google.lt': { type: 'search', name: 'Google News' }, + 'news.google.lu': { type: 'search', name: 'Google News' }, + 'news.google.lv': { type: 'search', name: 'Google News' }, + 'news.google.md': { type: 'search', name: 'Google News' }, + 'news.google.me': { type: 'search', name: 'Google News' }, + 'news.google.mg': { type: 'search', name: 'Google News' }, + 'news.google.mk': { type: 'search', name: 'Google News' }, + 'news.google.ml': { type: 'search', name: 'Google News' }, + 'news.google.mn': { type: 'search', name: 'Google News' }, + 'news.google.ms': { type: 'search', name: 'Google News' }, + 'news.google.mu': { type: 'search', name: 'Google News' }, + 'news.google.mv': { type: 'search', name: 'Google News' }, + 'news.google.mw': { type: 'search', name: 'Google News' }, + 'news.google.ne': { type: 'search', name: 'Google News' }, + 'news.google.nl': { type: 'search', name: 'Google News' }, + 'news.google.no': { type: 'search', name: 'Google News' }, + 'news.google.nr': { type: 'search', name: 'Google News' }, + 'news.google.nu': { type: 'search', name: 'Google News' }, + 'news.google.pl': { type: 'search', name: 'Google News' }, + 'news.google.pn': { type: 'search', name: 'Google News' }, + 'news.google.ps': { type: 'search', name: 'Google News' }, + 'news.google.pt': { type: 'search', name: 'Google News' }, + 'news.google.ro': { type: 'search', name: 'Google News' }, + 'news.google.rs': { type: 'search', name: 'Google News' }, + 'news.google.ru': { type: 'search', name: 'Google News' }, + 'news.google.rw': { type: 'search', name: 'Google News' }, + 'news.google.sc': { type: 'search', name: 'Google News' }, + 'news.google.se': { type: 'search', name: 'Google News' }, + 'news.google.sh': { type: 'search', name: 'Google News' }, + 'news.google.si': { type: 'search', name: 'Google News' }, + 'news.google.sk': { type: 'search', name: 'Google News' }, + 'news.google.sm': { type: 'search', name: 'Google News' }, + 'news.google.sn': { type: 'search', name: 'Google News' }, + 'news.google.so': { type: 'search', name: 'Google News' }, + 'news.google.st': { type: 'search', name: 'Google News' }, + 'news.google.td': { type: 'search', name: 'Google News' }, + 'news.google.tg': { type: 'search', name: 'Google News' }, + 'news.google.tk': { type: 'search', name: 'Google News' }, + 'news.google.tl': { type: 'search', name: 'Google News' }, + 'news.google.tm': { type: 'search', name: 'Google News' }, + 'news.google.to': { type: 'search', name: 'Google News' }, + 'news.google.tt': { type: 'search', name: 'Google News' }, + 'news.google.us': { type: 'search', name: 'Google News' }, + 'news.google.vg': { type: 'search', name: 'Google News' }, + 'news.google.vu': { type: 'search', name: 'Google News' }, + 'news.google.ws': { type: 'search', name: 'Google News' }, + 'zoohoo.cz': { type: 'search', name: 'Zoohoo' }, + 'search.seznam.cz': { type: 'search', name: 'Seznam' }, + 'online.no': { type: 'search', name: 'Online.no' }, + 'www.eurip.com': { type: 'search', name: 'Eurip' }, + 'all.by': { type: 'search', name: 'all.by' }, + 'search.rr.com': { type: 'search', name: 'Road Runner Search' }, + 'www.1881.no': { type: 'search', name: 'Opplysningen 1881' }, + 'www.yougoo.fr': { type: 'search', name: 'YouGoo' }, + 'bing.com/images/search': { type: 'search', name: 'Bing Images' }, + 'www.bing.com/images/search': { type: 'search', name: 'Bing Images' }, + 'geona.net': { type: 'search', name: 'Geona' }, + 'search.nate.com': { type: 'search', name: 'Nate' }, + 'www.searchthis.com': { type: 'search', name: 'Search This' }, + 'duckduckgo.com': { type: 'search', name: 'DuckDuckGo' }, + 'www.monster.be': { type: 'search', name: 'Monster' }, + 'www.monster.cz': { type: 'search', name: 'Monster' }, + 'www.monster.de': { type: 'search', name: 'Monster' }, + 'www.monster.fi': { type: 'search', name: 'Monster' }, + 'www.monster.fr': { type: 'search', name: 'Monster' }, + 'www.monster.ie': { type: 'search', name: 'Monster' }, + 'www.monster.it': { type: 'search', name: 'Monster' }, + 'www.monster.lu': { type: 'search', name: 'Monster' }, + 'www.monster.ch': { type: 'search', name: 'Monster' }, + 'www.monster.co.uk': { type: 'search', name: 'Monster' }, + 'www.hotbot.com': { type: 'search', name: 'Hotbot' }, + 'www.kvasir.no': { type: 'search', name: 'Kvasir' }, + 'www2.austronaut.at': { type: 'search', name: 'Austronaut' }, + 'www1.astronaut.at': { type: 'search', name: 'Austronaut' }, + 'sosodesktop.com': { type: 'search', name: 'SoSoDesk' }, + 'search.sosodesktop.com': { type: 'search', name: 'SoSoDesk' }, + 'search.excite.it': { type: 'search', name: 'Excite' }, + 'search.excite.fr': { type: 'search', name: 'Excite' }, + 'search.excite.de': { type: 'search', name: 'Excite' }, + 'search.excite.co.uk': { type: 'search', name: 'Excite' }, + 'serach.excite.es': { type: 'search', name: 'Excite' }, + 'search.excite.nl': { type: 'search', name: 'Excite' }, + 'msxml.excite.com': { type: 'search', name: 'Excite' }, + 'www.excite.co.jp': { type: 'search', name: 'Excite' }, + 'search.1and1.com': { type: 'search', name: '1&1' }, + 'search.qip.ru': { type: 'search', name: 'qip' }, + 'search.certified-toolbar.com': { type: 'search', name: 'Certified-Toolbar' }, + 'search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'ar.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'ar.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'au.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'au.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'br.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'br.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'ca.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'ca.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'cade.searchde.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'cade.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'chinese.searchinese.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'chinese.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'cn.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'cn.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'de.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'de.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'dk.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'dk.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'es.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'es.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'espanol.searchpanol.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'espanol.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'fr.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'fr.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'hk.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'hk.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'ie.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'ie.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'in.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'in.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'it.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'it.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'kr.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'kr.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'mx.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'mx.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'no.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'no.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'nz.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'nz.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'one.cn.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'one.searchn.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'qc.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'qc.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'ru.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'ru.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'se.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'se.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'search.searcharch.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'tw.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'tw.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'uk.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'uk.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'us.search.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'us.yahoo.com': { type: 'search', name: 'Yahoo!' }, + 'www.yahoo.co.jp': { type: 'search', name: 'Yahoo!' }, + 'search.yahoo.co.jp': { type: 'search', name: 'Yahoo!' }, + 'www.cercato.it': { type: 'search', name: 'Yahoo!' }, + 'search.offerbox.com': { type: 'search', name: 'Yahoo!' }, + 'ys.mirostart.com': { type: 'search', name: 'Yahoo!' }, + 'www.url.org': { type: 'search', name: 'URL.ORGanizier' }, + 'www.witch.de': { type: 'search', name: 'Witch' }, + 'www.mister-wong.com': { type: 'search', name: 'Mister Wong' }, + 'www.mister-wong.de': { type: 'search', name: 'Mister Wong' }, + 'sm.aport.ru': { type: 'search', name: 'Aport' }, + 'suche.web.de': { type: 'search', name: 'Web.de' }, + 'ask.com': { type: 'search', name: 'Ask' }, + 'www.ask.com': { type: 'search', name: 'Ask' }, + 'web.ask.com': { type: 'search', name: 'Ask' }, + 'int.ask.com': { type: 'search', name: 'Ask' }, + 'mws.ask.com': { type: 'search', name: 'Ask' }, + 'uk.ask.com': { type: 'search', name: 'Ask' }, + 'images.ask.com': { type: 'search', name: 'Ask' }, + 'ask.reference.com': { type: 'search', name: 'Ask' }, + 'www.askkids.com': { type: 'search', name: 'Ask' }, + 'iwon.ask.com': { type: 'search', name: 'Ask' }, + 'www.ask.co.uk': { type: 'search', name: 'Ask' }, + 'www.qbyrd.com': { type: 'search', name: 'Ask' }, + 'search-results.com': { type: 'search', name: 'Ask' }, + 'uk.search-results.com': { type: 'search', name: 'Ask' }, + 'www.search-results.com': { type: 'search', name: 'Ask' }, + 'int.search-results.com': { type: 'search', name: 'Ask' }, + 'serach.centrum.cz': { type: 'search', name: 'Centrum' }, + 'morfeo.centrum.cz': { type: 'search', name: 'Centrum' }, + 'bing.com': { type: 'search', name: 'Bing' }, + 'www.bing.com': { type: 'search', name: 'Bing' }, + 'msnbc.msn.com': { type: 'search', name: 'Bing' }, + 'dizionario.it.msn.com': { type: 'search', name: 'Bing' }, + 'cc.bingj.com': { type: 'search', name: 'Bing' }, + 'm.bing.com': { type: 'search', name: 'Bing' }, + 'video.google.com': { type: 'search', name: 'Google Video' }, + 'otsing.delfi.ee': { type: 'search', name: 'Delfi' }, + 'blekko.com': { type: 'search', name: 'blekko' }, + 'jyxo.1188.cz': { type: 'search', name: 'Jyxo' }, + 'www.kataweb.it': { type: 'search', name: 'Kataweb' }, + 'busca.uol.com.br': { type: 'search', name: 'uol.com.br' }, + 'arianna.libero.it': { type: 'search', name: 'Arianna' }, + 'www.arianna.com': { type: 'search', name: 'Arianna' }, + 'www.mamma.com': { type: 'search', name: 'Mamma' }, + 'mamma75.mamma.com': { type: 'search', name: 'Mamma' }, + 'www.yatedo.com': { type: 'search', name: 'Yatedo' }, + 'www.yatedo.fr': { type: 'search', name: 'Yatedo' }, + 'www.twingly.com': { type: 'search', name: 'Twingly' }, + 'smart.delfi.lv': { type: 'search', name: 'Delfi latvia' }, + 'www.pricerunner.co.uk': { type: 'search', name: 'PriceRunner' }, + 'websearch.rakuten.co.jp': { type: 'search', name: 'Rakuten' }, + 'www.google.com': { type: 'search', name: 'Google' }, + 'www.google.ac': { type: 'search', name: 'Google' }, + 'www.google.ad': { type: 'search', name: 'Google' }, + 'www.google.com.af': { type: 'search', name: 'Google' }, + 'www.google.com.ag': { type: 'search', name: 'Google' }, + 'www.google.com.ai': { type: 'search', name: 'Google' }, + 'www.google.am': { type: 'search', name: 'Google' }, + 'www.google.it.ao': { type: 'search', name: 'Google' }, + 'www.google.com.ar': { type: 'search', name: 'Google' }, + 'www.google.as': { type: 'search', name: 'Google' }, + 'www.google.at': { type: 'search', name: 'Google' }, + 'www.google.com.au': { type: 'search', name: 'Google' }, + 'www.google.az': { type: 'search', name: 'Google' }, + 'www.google.ba': { type: 'search', name: 'Google' }, + 'www.google.com.bd': { type: 'search', name: 'Google' }, + 'www.google.be': { type: 'search', name: 'Google' }, + 'www.google.bf': { type: 'search', name: 'Google' }, + 'www.google.bg': { type: 'search', name: 'Google' }, + 'www.google.com.bh': { type: 'search', name: 'Google' }, + 'www.google.bi': { type: 'search', name: 'Google' }, + 'www.google.bj': { type: 'search', name: 'Google' }, + 'www.google.com.bn': { type: 'search', name: 'Google' }, + 'www.google.com.bo': { type: 'search', name: 'Google' }, + 'www.google.com.br': { type: 'search', name: 'Google' }, + 'www.google.bs': { type: 'search', name: 'Google' }, + 'www.google.co.bw': { type: 'search', name: 'Google' }, + 'www.google.com.by': { type: 'search', name: 'Google' }, + 'www.google.by': { type: 'search', name: 'Google' }, + 'www.google.com.bz': { type: 'search', name: 'Google' }, + 'www.google.ca': { type: 'search', name: 'Google' }, + 'www.google.com.kh': { type: 'search', name: 'Google' }, + 'www.google.cc': { type: 'search', name: 'Google' }, + 'www.google.cd': { type: 'search', name: 'Google' }, + 'www.google.cf': { type: 'search', name: 'Google' }, + 'www.google.cat': { type: 'search', name: 'Google' }, + 'www.google.cg': { type: 'search', name: 'Google' }, + 'www.google.ch': { type: 'search', name: 'Google' }, + 'www.google.ci': { type: 'search', name: 'Google' }, + 'www.google.co.ck': { type: 'search', name: 'Google' }, + 'www.google.cl': { type: 'search', name: 'Google' }, + 'www.google.cm': { type: 'search', name: 'Google' }, + 'www.google.cn': { type: 'search', name: 'Google' }, + 'www.google.com.co': { type: 'search', name: 'Google' }, + 'www.google.co.cr': { type: 'search', name: 'Google' }, + 'www.google.com.cu': { type: 'search', name: 'Google' }, + 'www.google.cv': { type: 'search', name: 'Google' }, + 'www.google.com.cy': { type: 'search', name: 'Google' }, + 'www.google.cz': { type: 'search', name: 'Google' }, + 'www.google.de': { type: 'search', name: 'Google' }, + 'www.google.dj': { type: 'search', name: 'Google' }, + 'www.google.dk': { type: 'search', name: 'Google' }, + 'www.google.dm': { type: 'search', name: 'Google' }, + 'www.google.com.do': { type: 'search', name: 'Google' }, + 'www.google.dz': { type: 'search', name: 'Google' }, + 'www.google.com.ec': { type: 'search', name: 'Google' }, + 'www.google.ee': { type: 'search', name: 'Google' }, + 'www.google.com.eg': { type: 'search', name: 'Google' }, + 'www.google.es': { type: 'search', name: 'Google' }, + 'www.google.com.et': { type: 'search', name: 'Google' }, + 'www.google.fi': { type: 'search', name: 'Google' }, + 'www.google.com.fj': { type: 'search', name: 'Google' }, + 'www.google.fm': { type: 'search', name: 'Google' }, + 'www.google.fr': { type: 'search', name: 'Google' }, + 'www.google.ga': { type: 'search', name: 'Google' }, + 'www.google.gd': { type: 'search', name: 'Google' }, + 'www.google.ge': { type: 'search', name: 'Google' }, + 'www.google.gf': { type: 'search', name: 'Google' }, + 'www.google.gg': { type: 'search', name: 'Google' }, + 'www.google.com.gh': { type: 'search', name: 'Google' }, + 'www.google.com.gi': { type: 'search', name: 'Google' }, + 'www.google.gl': { type: 'search', name: 'Google' }, + 'www.google.gm': { type: 'search', name: 'Google' }, + 'www.google.gp': { type: 'search', name: 'Google' }, + 'www.google.gr': { type: 'search', name: 'Google' }, + 'www.google.com.gt': { type: 'search', name: 'Google' }, + 'www.google.gy': { type: 'search', name: 'Google' }, + 'www.google.com.hk': { type: 'search', name: 'Google' }, + 'www.google.hn': { type: 'search', name: 'Google' }, + 'www.google.hr': { type: 'search', name: 'Google' }, + 'www.google.ht': { type: 'search', name: 'Google' }, + 'www.google.hu': { type: 'search', name: 'Google' }, + 'www.google.co.id': { type: 'search', name: 'Google' }, + 'www.google.iq': { type: 'search', name: 'Google' }, + 'www.google.ie': { type: 'search', name: 'Google' }, + 'www.google.co.il': { type: 'search', name: 'Google' }, + 'www.google.im': { type: 'search', name: 'Google' }, + 'www.google.co.in': { type: 'search', name: 'Google' }, + 'www.google.io': { type: 'search', name: 'Google' }, + 'www.google.is': { type: 'search', name: 'Google' }, + 'www.google.it': { type: 'search', name: 'Google' }, + 'www.google.je': { type: 'search', name: 'Google' }, + 'www.google.com.jm': { type: 'search', name: 'Google' }, + 'www.google.jo': { type: 'search', name: 'Google' }, + 'www.google.co.jp': { type: 'search', name: 'Google' }, + 'www.google.co.ke': { type: 'search', name: 'Google' }, + 'www.google.ki': { type: 'search', name: 'Google' }, + 'www.google.kg': { type: 'search', name: 'Google' }, + 'www.google.co.kr': { type: 'search', name: 'Google' }, + 'www.google.com.kw': { type: 'search', name: 'Google' }, + 'www.google.kz': { type: 'search', name: 'Google' }, + 'www.google.la': { type: 'search', name: 'Google' }, + 'www.google.com.lb': { type: 'search', name: 'Google' }, + 'www.google.com.lc': { type: 'search', name: 'Google' }, + 'www.google.li': { type: 'search', name: 'Google' }, + 'www.google.lk': { type: 'search', name: 'Google' }, + 'www.google.co.ls': { type: 'search', name: 'Google' }, + 'www.google.lt': { type: 'search', name: 'Google' }, + 'www.google.lu': { type: 'search', name: 'Google' }, + 'www.google.lv': { type: 'search', name: 'Google' }, + 'www.google.com.ly': { type: 'search', name: 'Google' }, + 'www.google.co.ma': { type: 'search', name: 'Google' }, + 'www.google.md': { type: 'search', name: 'Google' }, + 'www.google.me': { type: 'search', name: 'Google' }, + 'www.google.mg': { type: 'search', name: 'Google' }, + 'www.google.mk': { type: 'search', name: 'Google' }, + 'www.google.ml': { type: 'search', name: 'Google' }, + 'www.google.mn': { type: 'search', name: 'Google' }, + 'www.google.ms': { type: 'search', name: 'Google' }, + 'www.google.com.mt': { type: 'search', name: 'Google' }, + 'www.google.mu': { type: 'search', name: 'Google' }, + 'www.google.mv': { type: 'search', name: 'Google' }, + 'www.google.mw': { type: 'search', name: 'Google' }, + 'www.google.com.mx': { type: 'search', name: 'Google' }, + 'www.google.com.my': { type: 'search', name: 'Google' }, + 'www.google.co.mz': { type: 'search', name: 'Google' }, + 'www.google.com.na': { type: 'search', name: 'Google' }, + 'www.google.ne': { type: 'search', name: 'Google' }, + 'www.google.com.nf': { type: 'search', name: 'Google' }, + 'www.google.com.ng': { type: 'search', name: 'Google' }, + 'www.google.com.ni': { type: 'search', name: 'Google' }, + 'www.google.nl': { type: 'search', name: 'Google' }, + 'www.google.no': { type: 'search', name: 'Google' }, + 'www.google.com.np': { type: 'search', name: 'Google' }, + 'www.google.nr': { type: 'search', name: 'Google' }, + 'www.google.nu': { type: 'search', name: 'Google' }, + 'www.google.co.nz': { type: 'search', name: 'Google' }, + 'www.google.com.om': { type: 'search', name: 'Google' }, + 'www.google.com.pa': { type: 'search', name: 'Google' }, + 'www.google.com.pe': { type: 'search', name: 'Google' }, + 'www.google.com.ph': { type: 'search', name: 'Google' }, + 'www.google.com.pk': { type: 'search', name: 'Google' }, + 'www.google.pl': { type: 'search', name: 'Google' }, + 'www.google.pn': { type: 'search', name: 'Google' }, + 'www.google.com.pr': { type: 'search', name: 'Google' }, + 'www.google.ps': { type: 'search', name: 'Google' }, + 'www.google.pt': { type: 'search', name: 'Google' }, + 'www.google.com.py': { type: 'search', name: 'Google' }, + 'www.google.com.qa': { type: 'search', name: 'Google' }, + 'www.google.ro': { type: 'search', name: 'Google' }, + 'www.google.rs': { type: 'search', name: 'Google' }, + 'www.google.ru': { type: 'search', name: 'Google' }, + 'www.google.rw': { type: 'search', name: 'Google' }, + 'www.google.com.sa': { type: 'search', name: 'Google' }, + 'www.google.com.sb': { type: 'search', name: 'Google' }, + 'www.google.sc': { type: 'search', name: 'Google' }, + 'www.google.se': { type: 'search', name: 'Google' }, + 'www.google.com.sg': { type: 'search', name: 'Google' }, + 'www.google.sh': { type: 'search', name: 'Google' }, + 'www.google.si': { type: 'search', name: 'Google' }, + 'www.google.sk': { type: 'search', name: 'Google' }, + 'www.google.com.sl': { type: 'search', name: 'Google' }, + 'www.google.sn': { type: 'search', name: 'Google' }, + 'www.google.sm': { type: 'search', name: 'Google' }, + 'www.google.so': { type: 'search', name: 'Google' }, + 'www.google.st': { type: 'search', name: 'Google' }, + 'www.google.com.sv': { type: 'search', name: 'Google' }, + 'www.google.td': { type: 'search', name: 'Google' }, + 'www.google.tg': { type: 'search', name: 'Google' }, + 'www.google.co.th': { type: 'search', name: 'Google' }, + 'www.google.com.tj': { type: 'search', name: 'Google' }, + 'www.google.tk': { type: 'search', name: 'Google' }, + 'www.google.tl': { type: 'search', name: 'Google' }, + 'www.google.tm': { type: 'search', name: 'Google' }, + 'www.google.to': { type: 'search', name: 'Google' }, + 'www.google.com.tn': { type: 'search', name: 'Google' }, + 'www.google.tn': { type: 'search', name: 'Google' }, + 'www.google.com.tr': { type: 'search', name: 'Google' }, + 'www.google.tt': { type: 'search', name: 'Google' }, + 'www.google.com.tw': { type: 'search', name: 'Google' }, + 'www.google.co.tz': { type: 'search', name: 'Google' }, + 'www.google.com.ua': { type: 'search', name: 'Google' }, + 'www.google.co.ug': { type: 'search', name: 'Google' }, + 'www.google.ae': { type: 'search', name: 'Google' }, + 'www.google.co.uk': { type: 'search', name: 'Google' }, + 'www.google.us': { type: 'search', name: 'Google' }, + 'www.google.com.uy': { type: 'search', name: 'Google' }, + 'www.google.co.uz': { type: 'search', name: 'Google' }, + 'www.google.com.vc': { type: 'search', name: 'Google' }, + 'www.google.co.ve': { type: 'search', name: 'Google' }, + 'www.google.vg': { type: 'search', name: 'Google' }, + 'www.google.co.vi': { type: 'search', name: 'Google' }, + 'www.google.com.vn': { type: 'search', name: 'Google' }, + 'www.google.vu': { type: 'search', name: 'Google' }, + 'www.google.ws': { type: 'search', name: 'Google' }, + 'www.google.co.za': { type: 'search', name: 'Google' }, + 'www.google.co.zm': { type: 'search', name: 'Google' }, + 'www.google.co.zw': { type: 'search', name: 'Google' }, + 'google.com': { type: 'search', name: 'Google' }, + 'google.ac': { type: 'search', name: 'Google' }, + 'google.ad': { type: 'search', name: 'Google' }, + 'google.com.af': { type: 'search', name: 'Google' }, + 'google.com.ag': { type: 'search', name: 'Google' }, + 'google.com.ai': { type: 'search', name: 'Google' }, + 'google.am': { type: 'search', name: 'Google' }, + 'google.it.ao': { type: 'search', name: 'Google' }, + 'google.com.ar': { type: 'search', name: 'Google' }, + 'google.as': { type: 'search', name: 'Google' }, + 'google.at': { type: 'search', name: 'Google' }, + 'google.com.au': { type: 'search', name: 'Google' }, + 'google.az': { type: 'search', name: 'Google' }, + 'google.ba': { type: 'search', name: 'Google' }, + 'google.com.bd': { type: 'search', name: 'Google' }, + 'google.be': { type: 'search', name: 'Google' }, + 'google.bf': { type: 'search', name: 'Google' }, + 'google.bg': { type: 'search', name: 'Google' }, + 'google.com.bh': { type: 'search', name: 'Google' }, + 'google.bi': { type: 'search', name: 'Google' }, + 'google.bj': { type: 'search', name: 'Google' }, + 'google.com.bn': { type: 'search', name: 'Google' }, + 'google.com.bo': { type: 'search', name: 'Google' }, + 'google.com.br': { type: 'search', name: 'Google' }, + 'google.bs': { type: 'search', name: 'Google' }, + 'google.co.bw': { type: 'search', name: 'Google' }, + 'google.com.by': { type: 'search', name: 'Google' }, + 'google.by': { type: 'search', name: 'Google' }, + 'google.com.bz': { type: 'search', name: 'Google' }, + 'google.ca': { type: 'search', name: 'Google' }, + 'google.com.kh': { type: 'search', name: 'Google' }, + 'google.cc': { type: 'search', name: 'Google' }, + 'google.cd': { type: 'search', name: 'Google' }, + 'google.cf': { type: 'search', name: 'Google' }, + 'google.cat': { type: 'search', name: 'Google' }, + 'google.cg': { type: 'search', name: 'Google' }, + 'google.ch': { type: 'search', name: 'Google' }, + 'google.ci': { type: 'search', name: 'Google' }, + 'google.co.ck': { type: 'search', name: 'Google' }, + 'google.cl': { type: 'search', name: 'Google' }, + 'google.cm': { type: 'search', name: 'Google' }, + 'google.cn': { type: 'search', name: 'Google' }, + 'google.com.co': { type: 'search', name: 'Google' }, + 'google.co.cr': { type: 'search', name: 'Google' }, + 'google.com.cu': { type: 'search', name: 'Google' }, + 'google.cv': { type: 'search', name: 'Google' }, + 'google.com.cy': { type: 'search', name: 'Google' }, + 'google.cz': { type: 'search', name: 'Google' }, + 'google.de': { type: 'search', name: 'Google' }, + 'google.dj': { type: 'search', name: 'Google' }, + 'google.dk': { type: 'search', name: 'Google' }, + 'google.dm': { type: 'search', name: 'Google' }, + 'google.com.do': { type: 'search', name: 'Google' }, + 'google.dz': { type: 'search', name: 'Google' }, + 'google.com.ec': { type: 'search', name: 'Google' }, + 'google.ee': { type: 'search', name: 'Google' }, + 'google.com.eg': { type: 'search', name: 'Google' }, + 'google.es': { type: 'search', name: 'Google' }, + 'google.com.et': { type: 'search', name: 'Google' }, + 'google.fi': { type: 'search', name: 'Google' }, + 'google.com.fj': { type: 'search', name: 'Google' }, + 'google.fm': { type: 'search', name: 'Google' }, + 'google.fr': { type: 'search', name: 'Google' }, + 'google.ga': { type: 'search', name: 'Google' }, + 'google.gd': { type: 'search', name: 'Google' }, + 'google.ge': { type: 'search', name: 'Google' }, + 'google.gf': { type: 'search', name: 'Google' }, + 'google.gg': { type: 'search', name: 'Google' }, + 'google.com.gh': { type: 'search', name: 'Google' }, + 'google.com.gi': { type: 'search', name: 'Google' }, + 'google.gl': { type: 'search', name: 'Google' }, + 'google.gm': { type: 'search', name: 'Google' }, + 'google.gp': { type: 'search', name: 'Google' }, + 'google.gr': { type: 'search', name: 'Google' }, + 'google.com.gt': { type: 'search', name: 'Google' }, + 'google.gy': { type: 'search', name: 'Google' }, + 'google.com.hk': { type: 'search', name: 'Google' }, + 'google.hn': { type: 'search', name: 'Google' }, + 'google.hr': { type: 'search', name: 'Google' }, + 'google.ht': { type: 'search', name: 'Google' }, + 'google.hu': { type: 'search', name: 'Google' }, + 'google.co.id': { type: 'search', name: 'Google' }, + 'google.iq': { type: 'search', name: 'Google' }, + 'google.ie': { type: 'search', name: 'Google' }, + 'google.co.il': { type: 'search', name: 'Google' }, + 'google.im': { type: 'search', name: 'Google' }, + 'google.co.in': { type: 'search', name: 'Google' }, + 'google.io': { type: 'search', name: 'Google' }, + 'google.is': { type: 'search', name: 'Google' }, + 'google.it': { type: 'search', name: 'Google' }, + 'google.je': { type: 'search', name: 'Google' }, + 'google.com.jm': { type: 'search', name: 'Google' }, + 'google.jo': { type: 'search', name: 'Google' }, + 'google.co.jp': { type: 'search', name: 'Google' }, + 'google.co.ke': { type: 'search', name: 'Google' }, + 'google.ki': { type: 'search', name: 'Google' }, + 'google.kg': { type: 'search', name: 'Google' }, + 'google.co.kr': { type: 'search', name: 'Google' }, + 'google.com.kw': { type: 'search', name: 'Google' }, + 'google.kz': { type: 'search', name: 'Google' }, + 'google.la': { type: 'search', name: 'Google' }, + 'google.com.lb': { type: 'search', name: 'Google' }, + 'google.com.lc': { type: 'search', name: 'Google' }, + 'google.li': { type: 'search', name: 'Google' }, + 'google.lk': { type: 'search', name: 'Google' }, + 'google.co.ls': { type: 'search', name: 'Google' }, + 'google.lt': { type: 'search', name: 'Google' }, + 'google.lu': { type: 'search', name: 'Google' }, + 'google.lv': { type: 'search', name: 'Google' }, + 'google.com.ly': { type: 'search', name: 'Google' }, + 'google.co.ma': { type: 'search', name: 'Google' }, + 'google.md': { type: 'search', name: 'Google' }, + 'google.me': { type: 'search', name: 'Google' }, + 'google.mg': { type: 'search', name: 'Google' }, + 'google.mk': { type: 'search', name: 'Google' }, + 'google.ml': { type: 'search', name: 'Google' }, + 'google.mn': { type: 'search', name: 'Google' }, + 'google.ms': { type: 'search', name: 'Google' }, + 'google.com.mt': { type: 'search', name: 'Google' }, + 'google.mu': { type: 'search', name: 'Google' }, + 'google.mv': { type: 'search', name: 'Google' }, + 'google.mw': { type: 'search', name: 'Google' }, + 'google.com.mx': { type: 'search', name: 'Google' }, + 'google.com.my': { type: 'search', name: 'Google' }, + 'google.co.mz': { type: 'search', name: 'Google' }, + 'google.com.na': { type: 'search', name: 'Google' }, + 'google.ne': { type: 'search', name: 'Google' }, + 'google.com.nf': { type: 'search', name: 'Google' }, + 'google.com.ng': { type: 'search', name: 'Google' }, + 'google.com.ni': { type: 'search', name: 'Google' }, + 'google.nl': { type: 'search', name: 'Google' }, + 'google.no': { type: 'search', name: 'Google' }, + 'google.com.np': { type: 'search', name: 'Google' }, + 'google.nr': { type: 'search', name: 'Google' }, + 'google.nu': { type: 'search', name: 'Google' }, + 'google.co.nz': { type: 'search', name: 'Google' }, + 'google.com.om': { type: 'search', name: 'Google' }, + 'google.com.pa': { type: 'search', name: 'Google' }, + 'google.com.pe': { type: 'search', name: 'Google' }, + 'google.com.ph': { type: 'search', name: 'Google' }, + 'google.com.pk': { type: 'search', name: 'Google' }, + 'google.pl': { type: 'search', name: 'Google' }, + 'google.pn': { type: 'search', name: 'Google' }, + 'google.com.pr': { type: 'search', name: 'Google' }, + 'google.ps': { type: 'search', name: 'Google' }, + 'google.pt': { type: 'search', name: 'Google' }, + 'google.com.py': { type: 'search', name: 'Google' }, + 'google.com.qa': { type: 'search', name: 'Google' }, + 'google.ro': { type: 'search', name: 'Google' }, + 'google.rs': { type: 'search', name: 'Google' }, + 'google.ru': { type: 'search', name: 'Google' }, + 'google.rw': { type: 'search', name: 'Google' }, + 'google.com.sa': { type: 'search', name: 'Google' }, + 'google.com.sb': { type: 'search', name: 'Google' }, + 'google.sc': { type: 'search', name: 'Google' }, + 'google.se': { type: 'search', name: 'Google' }, + 'google.com.sg': { type: 'search', name: 'Google' }, + 'google.sh': { type: 'search', name: 'Google' }, + 'google.si': { type: 'search', name: 'Google' }, + 'google.sk': { type: 'search', name: 'Google' }, + 'google.com.sl': { type: 'search', name: 'Google' }, + 'google.sn': { type: 'search', name: 'Google' }, + 'google.sm': { type: 'search', name: 'Google' }, + 'google.so': { type: 'search', name: 'Google' }, + 'google.st': { type: 'search', name: 'Google' }, + 'google.com.sv': { type: 'search', name: 'Google' }, + 'google.td': { type: 'search', name: 'Google' }, + 'google.tg': { type: 'search', name: 'Google' }, + 'google.co.th': { type: 'search', name: 'Google' }, + 'google.com.tj': { type: 'search', name: 'Google' }, + 'google.tk': { type: 'search', name: 'Google' }, + 'google.tl': { type: 'search', name: 'Google' }, + 'google.tm': { type: 'search', name: 'Google' }, + 'google.to': { type: 'search', name: 'Google' }, + 'google.com.tn': { type: 'search', name: 'Google' }, + 'google.com.tr': { type: 'search', name: 'Google' }, + 'google.tt': { type: 'search', name: 'Google' }, + 'google.com.tw': { type: 'search', name: 'Google' }, + 'google.co.tz': { type: 'search', name: 'Google' }, + 'google.com.ua': { type: 'search', name: 'Google' }, + 'google.co.ug': { type: 'search', name: 'Google' }, + 'google.ae': { type: 'search', name: 'Google' }, + 'google.co.uk': { type: 'search', name: 'Google' }, + 'google.us': { type: 'search', name: 'Google' }, + 'google.com.uy': { type: 'search', name: 'Google' }, + 'google.co.uz': { type: 'search', name: 'Google' }, + 'google.com.vc': { type: 'search', name: 'Google' }, + 'google.co.ve': { type: 'search', name: 'Google' }, + 'google.vg': { type: 'search', name: 'Google' }, + 'google.co.vi': { type: 'search', name: 'Google' }, + 'google.com.vn': { type: 'search', name: 'Google' }, + 'google.vu': { type: 'search', name: 'Google' }, + 'google.ws': { type: 'search', name: 'Google' }, + 'google.co.za': { type: 'search', name: 'Google' }, + 'google.co.zm': { type: 'search', name: 'Google' }, + 'google.co.zw': { type: 'search', name: 'Google' }, + 'google.tn': { type: 'search', name: 'Google' }, + 'search.avg.com': { type: 'search', name: 'Google' }, + 'isearch.avg.com': { type: 'search', name: 'Google' }, + 'www.cnn.com': { type: 'search', name: 'Google' }, + 'darkoogle.com': { type: 'search', name: 'Google' }, + 'search.darkoogle.com': { type: 'search', name: 'Google' }, + 'search.foxtab.com': { type: 'search', name: 'Google' }, + 'www.gooofullsearch.com': { type: 'search', name: 'Google' }, + 'search.hiyo.com': { type: 'search', name: 'Google' }, + 'search.incredimail.com': { type: 'search', name: 'Google' }, + 'search1.incredimail.com': { type: 'search', name: 'Google' }, + 'search2.incredimail.com': { type: 'search', name: 'Google' }, + 'search3.incredimail.com': { type: 'search', name: 'Google' }, + 'search4.incredimail.com': { type: 'search', name: 'Google' }, + 'search.incredibar.com': { type: 'search', name: 'Google' }, + 'search.sweetim.com': { type: 'search', name: 'Google' }, + 'www.fastweb.it': { type: 'search', name: 'Google' }, + 'search.juno.com': { type: 'search', name: 'Google' }, + 'find.tdc.dk': { type: 'search', name: 'Google' }, + 'searchresults.verizon.com': { type: 'search', name: 'Google' }, + 'search.walla.co.il': { type: 'search', name: 'Google' }, + 'search.alot.com': { type: 'search', name: 'Google' }, + 'www.googleearth.de': { type: 'search', name: 'Google' }, + 'www.googleearth.fr': { type: 'search', name: 'Google' }, + 'webcache.googleusercontent.com': { type: 'search', name: 'Google' }, + 'encrypted.google.com': { type: 'search', name: 'Google' }, + 'googlesyndicatedsearch.com': { type: 'search', name: 'Google' }, + 'com.google.android.googlequicksearchbox': { type: 'search', name: 'Google' }, + 'www.blogpulse.com': { type: 'search', name: 'Blogpulse' }, + 'www.hooseek.com': { type: 'search', name: 'Hooseek.com' }, + 'www.dalesearch.com': { type: 'search', name: 'Dalesearch' }, + 'rechercher.aliceadsl.fr': { type: 'search', name: 'Alice Adsl' }, + 'suche.t-online.de': { type: 'search', name: 'T-Online' }, + 'brisbane.t-online.de': { type: 'search', name: 'T-Online' }, + 'navigationshilfe.t-online.de': { type: 'search', name: 'T-Online' }, + 'www.sougou.com': { type: 'search', name: 'Sogou' }, + 'www.soso.com': { type: 'search', name: 'Sogou' }, + 'req.-hit-parade.com': { type: 'search', name: 'Hit-Parade' }, + 'class.hit-parade.com': { type: 'search', name: 'Hit-Parade' }, + 'www.hit-parade.com': { type: 'search', name: 'Hit-Parade' }, + 'www.searchcanvas.com': { type: 'search', name: 'SearchCanvas' }, + 'junglekey.com': { type: 'search', name: 'Jungle Key' }, + 'junglekey.fr': { type: 'search', name: 'Jungle Key' }, + 'www.google.interia.pl': { type: 'search', name: 'Interia' }, + 'search.genieo.com': { type: 'search', name: 'Genieo' }, + 'search.tiscali.it': { type: 'search', name: 'Tiscali' }, + 'search-dyn.tiscali.it': { type: 'search', name: 'Tiscali' }, + 'hledani.tiscali.cz': { type: 'search', name: 'Tiscali' }, + 'www.gomeo.com': { type: 'search', name: 'Gomeo' }, + 'webmail.bigpond.com': { type: 'email', name: 'Bigpond' }, + 'webmail2.bigpond.com': { type: 'email', name: 'Bigpond' }, + 'email.telstra.com': { type: 'email', name: 'Bigpond' }, + 'basic.messaging.bigpond.com': { type: 'email', name: 'Bigpond' }, + 'mail.naver.com': { type: 'email', name: 'Naver Mail' }, + 'mail.zoho.com': { type: 'email', name: 'Zoho' }, + 'webmail.virginbroadband.com.au': { type: 'email', name: 'Virgin' }, + 'mail.yahoo.net': { type: 'email', name: 'Yahoo! Mail' }, + 'mail.yahoo.com': { type: 'email', name: 'Yahoo! Mail' }, + 'mail.yahoo.co.uk': { type: 'email', name: 'Yahoo! Mail' }, + 'mail.yahoo.co.jp': { type: 'email', name: 'Yahoo! Mail' }, + 'com.yahoo.mobile.client.android.mail': { + type: 'email', + name: 'Yahoo! Mail', + }, + 'webmail.iinet.net.au': { type: 'email', name: 'iiNet' }, + 'mail.iinet.net.au': { type: 'email', name: 'iiNet' }, + 'mail.e1.ru': { type: 'email', name: 'E1.ru' }, + 'webmail.vodafone.co.nz': { type: 'email', name: 'Vodafone' }, + 'mail.126.com': { type: 'email', name: '126 Mail' }, + 'com.mailchimp.mailchimp': { type: 'email', name: 'Mailchimp' }, + 'inbox.com': { type: 'email', name: 'Inbox.com' }, + 'webmail.iprimus.com.au': { type: 'email', name: 'iPrimus' }, + 'mail.qq.com': { type: 'email', name: 'QQ Mail' }, + 'exmail.qq.com': { type: 'email', name: 'QQ Mail' }, + 'mail.qip.ru': { type: 'email', name: 'QIP' }, + 'sibmail.com': { type: 'email', name: 'Sibmail' }, + 'webmail.freenet.de': { type: 'email', name: 'Freenet' }, + 'email.seznam.cz': { type: 'email', name: 'Seznam Mail' }, + 'webmail.westnet.com.au': { type: 'email', name: 'Westnet' }, + 'mail.live.com': { type: 'email', name: 'Outlook.com' }, + 'outlook.live.com': { type: 'email', name: 'Outlook.com' }, + 'com.microsoft.office.outlook': { type: 'email', name: 'Outlook.com' }, + 'webmail.dodo.com.au': { type: 'email', name: 'Dodo' }, + 'webmail.2degreesbroadband.co.nz': { type: 'email', name: '2degrees' }, + 'mail2.daum.net': { type: 'email', name: 'Daum Mail' }, + 'mail.daum.net': { type: 'email', name: 'Daum Mail' }, + 'post.ru': { type: 'email', name: 'Beeline' }, + 'e.mail.ru': { type: 'email', name: 'Mail.ru' }, + 'touch.mail.ru': { type: 'email', name: 'Mail.ru' }, + 'webmail.adam.com.au': { type: 'email', name: 'Adam Internet' }, + 'orange.fr/webmail': { type: 'email', name: 'Orange Webmail' }, + 'com.earthlink.myearthlink': { type: 'email', name: 'earthlink' }, + 'mail.aol.com': { type: 'email', name: 'AOL Mail' }, + 'com.aol.mobile.aolapp': { type: 'email', name: 'AOL Mail' }, + 'webmail.netspace.net.au': { type: 'email', name: 'Netspace' }, + 'webmail.optuszoo.com.au': { type: 'email', name: 'Optus Zoo' }, + 'webmail.optusnet.com.au': { type: 'email', name: 'Optus Zoo' }, + 'webmail.commander.net.au': { type: 'email', name: 'Commander' }, + 'mastermail.ru': { type: 'email', name: 'Mastermail' }, + 'm.mastermail.ru': { type: 'email', name: 'Mastermail' }, + 'mail.yandex.ru': { type: 'email', name: 'Yandex' }, + 'mail.yandex.com': { type: 'email', name: 'Yandex' }, + 'mail.yandex.kz': { type: 'email', name: 'Yandex' }, + 'mail.yandex.ua': { type: 'email', name: 'Yandex' }, + 'mail.yandex.by': { type: 'email', name: 'Yandex' }, + 'mail.163.com': { type: 'email', name: '163 Mail' }, + 'mail.ukr.net': { type: 'email', name: 'Ukr.net' }, + 'mail.rambler.ru': { type: 'email', name: 'Rambler' }, + 'mail.mynet.com': { type: 'email', name: 'Mynet Mail' }, + 'mail.google.com': { type: 'email', name: 'Gmail' }, + 'com.google.android.gm': { type: 'email', name: 'Gmail' }, + 'inbox.google.com': { type: 'email', name: 'Gmail' }, + 'adspirit.de': { type: 'paid', name: 'AdSpirit' }, + 'rtbcity.com': { type: 'paid', name: 'AdSpirit' }, + 'plusperformance.com': { type: 'paid', name: 'AdSpirit' }, + 'flashtalking.com': { type: 'paid', name: 'Flashtalking' }, + 'servedby.flashtalking.com': { type: 'paid', name: 'Flashtalking' }, + 'wunderloop.net': { type: 'paid', name: 'AudienceScience' }, + 'paid.outbrain.com': { type: 'paid', name: 'Outbrain' }, + 'yieldmo.com': { type: 'paid', name: 'Yieldmo' }, + 'mozo.com.au': { type: 'paid', name: 'Mozo' }, + 'a.mozo.com.au': { type: 'paid', name: 'Mozo' }, + 'acuityplatform.com': { type: 'paid', name: 'Acuity Ads' }, + 'lfstmedia.com': { type: 'paid', name: 'LifeStreet' }, + 'microad.jp': { type: 'paid', name: 'MicroAd' }, + 'trc.taboola.com': { type: 'paid', name: 'Taboola' }, + 'api.taboola.com': { type: 'paid', name: 'Taboola' }, + 'taboola.com': { type: 'paid', name: 'Taboola' }, + 'ad.doubleclick.net': { type: 'paid', name: 'Doubleclick' }, + 'ad-apac.doubleclick.net': { type: 'paid', name: 'Doubleclick' }, + 's0.2mdn.net': { type: 'paid', name: 'Doubleclick' }, + 's1.2mdn.net': { type: 'paid', name: 'Doubleclick' }, + 'dp.g.doubleclick.net': { type: 'paid', name: 'Doubleclick' }, + 'pubads.g.doubleclick.net': { type: 'paid', name: 'Doubleclick' }, + 'adform.net': { type: 'paid', name: 'Adform' }, + 'bs.serving-sys.com': { type: 'paid', name: 'Sizmek' }, + 'cas.jp.as.criteo.com': { type: 'paid', name: 'Criteo' }, + 'cas.criteo.com': { type: 'paid', name: 'Criteo' }, + 'adingo.jp': { type: 'paid', name: 'Fluct' }, + 'lowermybills.com': { type: 'paid', name: 'LowerMyBills' }, + 'www.whitepages.com.au': { type: 'paid', name: 'White Pages' }, + 'mobile.whitepages.com.au': { type: 'paid', name: 'White Pages' }, + 'adadvisor.net': { type: 'paid', name: 'Neustar AdAdvisor' }, + 'nexage.com': { type: 'paid', name: 'ONE by AOL' }, + 'mixpo.com': { type: 'paid', name: 'Mixpo' }, + 'optimized-by.rubiconproject.com': { type: 'paid', name: 'Rubicon Project' }, + 'sshowads.pubmatic.com': { type: 'paid', name: 'PubMatic' }, + 'jivox.com': { type: 'paid', name: 'Jivox' }, + 'bidswitch.net': { type: 'paid', name: 'BidSwitch' }, + 'sonobi.com': { type: 'paid', name: 'Sonobi' }, + 'steelhousemedia.com': { type: 'paid', name: 'SteelHouse' }, + 'adroll.com': { type: 'paid', name: 'AdRoll' }, + 'adnet.de': { type: 'paid', name: 'AdNET' }, + 'cdnx.tribalfusion.com': { type: 'paid', name: 'Tribal Fusion' }, + 'market.yandex.ru': { type: 'paid', name: 'Yandex.Market' }, + 'm.market.yandex.ru': { type: 'paid', name: 'Yandex.Market' }, + 'stickyadstv.com': { type: 'paid', name: 'StickyADS.tv' }, + 'sfx.stickyadstv.com': { type: 'paid', name: 'StickyADS.tv' }, + 'zedo.com': { type: 'paid', name: 'ZEDO' }, + 'z1.zedo.com': { type: 'paid', name: 'ZEDO' }, + 'farm.plista.com': { type: 'paid', name: 'Plista' }, + 'ib.adnxs.com': { type: 'paid', name: 'AppNexus' }, + 'adnxs.com': { type: 'paid', name: 'AppNexus' }, + '247realmedia.com': { type: 'paid', name: 'AppNexus' }, + 'lijit.com': { type: 'paid', name: 'Sovrn' }, + 'www.googleadservices.com': { type: 'paid', name: 'Google' }, + 'partner.googleadservices.com': { type: 'paid', name: 'Google' }, + 'googleads.g.doubleclick.net': { type: 'paid', name: 'Google' }, + 'tpc.googlesyndication.com': { type: 'paid', name: 'Google' }, + 'googleadservices.com': { type: 'paid', name: 'Google' }, + 'imasdk.googleapis.com': { type: 'paid', name: 'Google' }, + 'eyeota.net': { type: 'paid', name: 'Eyeota' }, + 'price.ru': { type: 'paid', name: 'Price.ru' }, + 'v.price.ru': { type: 'paid', name: 'Price.ru' }, + 'us-ads.openx.net': { type: 'paid', name: 'OpenX' }, + 'openx.net': { type: 'paid', name: 'OpenX' }, + 'servedbyopenx.com': { type: 'paid', name: 'OpenX' }, + 'openxenterprise.com': { type: 'paid', name: 'OpenX' }, + 'casalemedia.com': { type: 'paid', name: 'Casale Media' }, + 'adition.com': { type: 'paid', name: 'Adition' }, + 'an.yandex.ru': { type: 'paid', name: 'Yandex.Direct' }, + 'yabs.yandex.ru': { type: 'paid', name: 'Yandex.Direct' }, + 'yabs.yandex.ua': { type: 'paid', name: 'Yandex.Direct' }, + 'yabs.yandex.com': { type: 'paid', name: 'Yandex.Direct' }, + 'yabs.yandex.by': { type: 'paid', name: 'Yandex.Direct' }, + 'adfox.ru': { type: 'paid', name: 'ADFOX' }, + 'www.adfox.ru': { type: 'paid', name: 'ADFOX' }, + 'ads.adfox.ru': { type: 'paid', name: 'ADFOX' }, + 'www.ads.adfox.ru': { type: 'paid', name: 'ADFOX' }, + 'torg.mail.ru': { type: 'paid', name: 'Torg.Mail.ru' }, + 'sociomantic.com': { type: 'paid', name: 'Sociomantic Labs' }, + 'hi5.com': { type: 'social', name: 'hi5' }, + 'friendster.com': { type: 'social', name: 'Friendster' }, + 'vkrugudruzei.ru': { type: 'social', name: 'vKruguDruzei.ru' }, + 'xanga.com': { type: 'social', name: 'Xanga' }, + 'myspace.com': { type: 'social', name: 'Myspace' }, + 'buzznet.com': { type: 'social', name: 'Buzznet' }, + 'mylife.ru': { type: 'social', name: 'MyLife' }, + 'flickr.com': { type: 'social', name: 'Flickr' }, + 'forums.whirlpool.net.au': { type: 'social', name: 'Whirlpool' }, + 'sonico.com': { type: 'social', name: 'Sonico.com' }, + 'odnoklassniki.ru': { type: 'social', name: 'Odnoklassniki' }, + 'ok.ru': { type: 'social', name: 'Odnoklassniki' }, + 'tildes.net': { type: 'social', name: 'Tildes' }, + 'com.talklittle.android.tildes': { type: 'social', name: 'Tildes' }, + 'classmates.com': { type: 'social', name: 'Classmates' }, + 'friendsreunited.com': { type: 'social', name: 'Friends Reunited' }, + 'news.ycombinator.com': { type: 'social', name: 'Hacker News' }, + 'io.github.hidroh.materialistic': { type: 'social', name: 'Hacker News' }, + 'quora.com': { type: 'social', name: 'Quora' }, + 'livejournal.ru': { type: 'social', name: 'LiveJournal' }, + 'netlog.com': { type: 'social', name: 'Netlog' }, + 'orkut.com': { type: 'social', name: 'Orkut' }, + 'myheritage.com': { type: 'social', name: 'MyHeritage' }, + 'multiply.com': { type: 'social', name: 'Multiply' }, + 'threads.net': { type: 'social', name: 'Threads' }, + 'l.threads.net': { type: 'social', name: 'Threads' }, + 'com.instagram.barcelona': { type: 'social', name: 'Threads' }, + 'myyearbook.com': { type: 'social', name: 'myYearbook' }, + 'renren.com': { type: 'social', name: 'Renren' }, + 'app.slack.com': { type: 'social', name: 'Slack' }, + 'com.slack': { type: 'social', name: 'Slack' }, + 'weeworld.com': { type: 'social', name: 'WeeWorld' }, + 'vimeo.com': { type: 'social', name: 'Vimeo' }, + 'Sozluk.com': { type: 'social', name: 'Eksi Sozluk' }, + 'sourtimes.org': { type: 'social', name: 'Eksi Sozluk' }, + 'mixi.jp': { type: 'social', name: 'Mixi' }, + 'geni.com': { type: 'social', name: 'Geni' }, + 'uludagsozluk.com': { type: 'social', name: 'Uludag Sozluk' }, + 'ulusozluk.com': { type: 'social', name: 'Uludag Sozluk' }, + 'sourceforge.net': { type: 'social', name: 'SourceForge' }, + 'plaxo.com': { type: 'social', name: 'Plaxo' }, + 'taringa.net': { type: 'social', name: 'Taringa!' }, + 'login.tagged.com': { type: 'social', name: 'Tagged' }, + 'xing.com': { type: 'social', name: 'XING' }, + 'instagram.com': { type: 'social', name: 'Instagram' }, + 'l.instagram.com': { type: 'social', name: 'Instagram' }, + 'com.instagram.android': { type: 'social', name: 'Instagram' }, + 'm.vk.com': { type: 'social', name: 'Vkontakte' }, + 'vk.com': { type: 'social', name: 'Vkontakte' }, + 'away.vk.com': { type: 'social', name: 'Vkontakte' }, + 'vkontakte.ru': { type: 'social', name: 'Vkontakte' }, + 'weibo.com': { type: 'social', name: 'Weibo' }, + 't.cn': { type: 'social', name: 'Weibo' }, + 'web.telegram.org': { type: 'social', name: 'Telegram' }, + 'org.telegram.messenger': { type: 'social', name: 'Telegram' }, + 'org.telegram.messenger.web': { type: 'social', name: 'Telegram' }, + 'org.aka.messenger': { type: 'social', name: 'Telegram' }, + 'org.telegram.biftogram': { type: 'social', name: 'Telegram' }, + 'org.telegram.plus': { type: 'social', name: 'Telegram' }, + 'twitter.com': { type: 'social', name: 'Twitter' }, + 't.co': { type: 'social', name: 'Twitter' }, + 'com.twitter.android': { type: 'social', name: 'Twitter' }, + 'com.snapchat.android': { type: 'social', name: 'Snapchat' }, + 'snapchat.com': { type: 'social', name: 'Snapchat' }, + 'donanimhaber.com': { type: 'social', name: 'Donanimhaber' }, + 'wayn.com': { type: 'social', name: 'WAYN' }, + 'web.skype.com': { type: 'social', name: 'Skype' }, + 'my.mail.ru': { type: 'social', name: 'Mail.ru' }, + 'badoo.com': { type: 'social', name: 'Badoo' }, + 'instela.com': { type: 'social', name: 'Instela' }, + 'habbo.com': { type: 'social', name: 'Habbo' }, + 'pinterest.ca': { type: 'social', name: 'Pinterest' }, + 'pinterest.cl': { type: 'social', name: 'Pinterest' }, + 'pinterest.co.kr': { type: 'social', name: 'Pinterest' }, + 'pinterest.com': { type: 'social', name: 'Pinterest' }, + 'pinterest.com.au': { type: 'social', name: 'Pinterest' }, + 'pinterest.co.uk': { type: 'social', name: 'Pinterest' }, + 'pinterest.de': { type: 'social', name: 'Pinterest' }, + 'pinterest.dk': { type: 'social', name: 'Pinterest' }, + 'pinterest.es': { type: 'social', name: 'Pinterest' }, + 'pinterest.fr': { type: 'social', name: 'Pinterest' }, + 'pinterest.jp': { type: 'social', name: 'Pinterest' }, + 'pinterest.nz': { type: 'social', name: 'Pinterest' }, + 'pinterest.pt': { type: 'social', name: 'Pinterest' }, + 'pinterest.se': { type: 'social', name: 'Pinterest' }, + 'pinterest.at': { type: 'social', name: 'Pinterest' }, + 'pinterest.ch': { type: 'social', name: 'Pinterest' }, + 'pinterest.com.mx': { type: 'social', name: 'Pinterest' }, + 'pinterest.ie': { type: 'social', name: 'Pinterest' }, + 'pinterest.it': { type: 'social', name: 'Pinterest' }, + 'pinterest.ph': { type: 'social', name: 'Pinterest' }, + 'pinterest.ru': { type: 'social', name: 'Pinterest' }, + 'com.pinterest': { type: 'social', name: 'Pinterest' }, + 'com.linkedin.android': { type: 'social', name: 'LinkedIn' }, + 'linkedin.com': { type: 'social', name: 'LinkedIn' }, + 'lnkd.in': { type: 'social', name: 'LinkedIn' }, + 'foursquare.com': { type: 'social', name: 'Foursquare' }, + 'douban.com': { type: 'social', name: 'Douban' }, + 'login.live.com': { type: 'social', name: 'Windows Live Spaces' }, + 'blackplanet.com': { type: 'social', name: 'BlackPlanet' }, + 'global.cyworld.com': { type: 'social', name: 'Cyworld' }, + 'getpocket.com': { type: 'social', name: 'Pocket' }, + 'skyrock.com': { type: 'social', name: 'Skyrock' }, + 'facebook.com': { type: 'social', name: 'Facebook' }, + 'fb.me': { type: 'social', name: 'Facebook' }, + 'm.facebook.com': { type: 'social', name: 'Facebook' }, + 'l.facebook.com': { type: 'social', name: 'Facebook' }, + 'lm.facebook.com': { type: 'social', name: 'Facebook' }, + 'com.facebook.katana': { type: 'social', name: 'Facebook' }, + 'web.whatsapp.com': { type: 'social', name: 'WhatsApp' }, + 'com.whatsapp': { type: 'social', name: 'WhatsApp' }, + 'redirect.disqus.com': { type: 'social', name: 'Disqus' }, + 'disq.us': { type: 'social', name: 'Disqus' }, + 'disqus.com': { type: 'social', name: 'Disqus' }, + 'studivz.net': { type: 'social', name: 'StudiVZ' }, + 'fotolog.com': { type: 'social', name: 'Fotolog' }, + 'itusozluk.com': { type: 'social', name: 'ITU Sozluk' }, + 'url.google.com': { type: 'social', name: 'Google+' }, + 'plus.google.com': { type: 'social', name: 'Google+' }, + 'nk.pl': { type: 'social', name: 'Nasza-klasa.pl' }, + 'qzone.qq.com': { type: 'social', name: 'Qzone' }, + 'flixster.com': { type: 'social', name: 'Flixster' }, + 'bebo.com': { type: 'social', name: 'Bebo' }, + 'tuenti.com': { type: 'social', name: 'Tuenti' }, + 'youtube.com': { type: 'social', name: 'Youtube' }, + 'youtu.be': { type: 'social', name: 'Youtube' }, + 'reddit.com': { type: 'social', name: 'Reddit' }, + 'io.syncapps.lemmy_sync': { type: 'social', name: 'Reddit' }, + 'com.laurencedawson.reddit_sync': { type: 'social', name: 'Reddit' }, + 'com.laurencedawson.reddit_sync.pro': { type: 'social', name: 'Reddit' }, + 'viadeo.com': { type: 'social', name: 'Viadeo' }, + 'github.com': { type: 'social', name: 'GitHub' }, + 'stackoverflow.com': { type: 'social', name: 'StackOverflow' }, + 'gaiaonline.com': { type: 'social', name: 'Gaia Online' }, + 'stumbleupon.com': { type: 'social', name: 'StumbleUpon' }, + 'inci.sozlukspot.com': { type: 'social', name: 'Inci Sozluk' }, + 'incisozluk.com': { type: 'social', name: 'Inci Sozluk' }, + 'incisozluk.cc': { type: 'social', name: 'Inci Sozluk' }, + 'identi.ca': { type: 'social', name: 'Identi.ca' }, + 'lastfm.ru': { type: 'social', name: 'Last.fm' }, + 'tumblr.com': { type: 'social', name: 'Tumblr' }, + 't.umblr.com': { type: 'social', name: 'Tumblr' }, + 'tiktok.com': { type: 'social', name: 'TikTok' }, + 'hocam.com': { type: 'social', name: 'Hocam.com' }, + 'delicious.com': { type: 'social', name: 'Delicious' }, + 'hyves.nl': { type: 'social', name: 'Hyves' }, + 'paper.li': { type: 'social', name: 'Paper.li' }, + 'moikrug.ru': { type: 'social', name: 'MoiKrug.ru' }, +} as const; +export default referrers; diff --git a/apps/api/src/referrers/referrers.readme.md b/apps/api/src/referrers/referrers.readme.md new file mode 100644 index 00000000..098d1c2a --- /dev/null +++ b/apps/api/src/referrers/referrers.readme.md @@ -0,0 +1,5 @@ +# Snowplow Referer Parser + +The file index.ts in this dir is generated from snowplows referer database [Snowplow Referer Parser](https://github.com/snowplow-referer-parser/referer-parser). + +The orginal [referers.yml](https://github.com/snowplow-referer-parser/referer-parser/blob/master/resources/referers.yml) is based on Piwik's SearchEngines.php and Socials.php, copyright 2012 Matthieu Aubry and available under the GNU General Public License v3. diff --git a/apps/api/src/routes/event.router.ts b/apps/api/src/routes/event.router.ts new file mode 100644 index 00000000..fffc39be --- /dev/null +++ b/apps/api/src/routes/event.router.ts @@ -0,0 +1,59 @@ +import { isBot } from "@/bots"; +import * as controller from "@/controllers/event.controller"; +import { validateSdkRequest } from "@/utils/auth"; +import type { FastifyPluginCallback, FastifyRequest } from "fastify"; + +import { createBotEvent } from "@openpanel/db"; +import type { PostEventPayload } from "@openpanel/sdk"; + +const eventRouter: FastifyPluginCallback = (fastify, opts, done) => { + fastify.addHook( + "preHandler", + async ( + req: FastifyRequest<{ + Body: PostEventPayload; + }>, + reply, + ) => { + try { + const projectId = await validateSdkRequest(req.headers); + req.projectId = projectId; + + const bot = req.headers["user-agent"] + ? isBot(req.headers["user-agent"]) + : null; + + if (bot) { + const path = (req.body?.properties?.__path || + req.body?.properties?.path) as string | undefined; + req.log.warn({ ...req.headers, bot }, "Bot detected (event)"); + await createBotEvent({ + ...bot, + projectId, + path: path ?? "", + createdAt: new Date(req.body?.timestamp), + }); + reply.status(202).send("OK"); + } + } catch (e) { + req.log.error(e, "Failed to create bot event"); + reply.status(401).send(); + return; + } + }, + ); + + fastify.route({ + method: "POST", + url: "/", + handler: controller.postEvent, + }); + fastify.route({ + method: "GET", + url: "/", + handler: controller.postEvent, + }); + done(); +}; + +export default eventRouter; diff --git a/apps/api/src/routes/live.router.ts b/apps/api/src/routes/live.router.ts new file mode 100644 index 00000000..b8318688 --- /dev/null +++ b/apps/api/src/routes/live.router.ts @@ -0,0 +1,27 @@ +import * as controller from '@/controllers/live.controller'; +import fastifyWS from '@fastify/websocket'; +import type { FastifyPluginCallback } from 'fastify'; + +const liveRouter: FastifyPluginCallback = (fastify, opts, done) => { + fastify.route({ + method: 'GET', + url: '/events/test/:projectId', + handler: controller.test, + }); + + fastify.register(fastifyWS); + + fastify.register((fastify, _, done) => { + fastify.get( + '/visitors/:projectId', + { websocket: true }, + controller.wsVisitors + ); + fastify.get('/events/:projectId', { websocket: true }, controller.wsEvents); + done(); + }); + + done(); +}; + +export default liveRouter; diff --git a/apps/api/src/routes/misc.router.ts b/apps/api/src/routes/misc.router.ts new file mode 100644 index 00000000..35af774c --- /dev/null +++ b/apps/api/src/routes/misc.router.ts @@ -0,0 +1,20 @@ +import * as controller from '@/controllers/misc.controller'; +import type { FastifyPluginCallback } from 'fastify'; + +const miscRouter: FastifyPluginCallback = (fastify, opts, done) => { + fastify.route({ + method: 'GET', + url: '/favicon', + handler: controller.getFavicon, + }); + + fastify.route({ + method: 'GET', + url: '/favicon/clear', + handler: controller.clearFavicons, + }); + + done(); +}; + +export default miscRouter; diff --git a/apps/api/src/routes/profile.router.ts b/apps/api/src/routes/profile.router.ts new file mode 100644 index 00000000..baa0de31 --- /dev/null +++ b/apps/api/src/routes/profile.router.ts @@ -0,0 +1,46 @@ +import { isBot } from '@/bots'; +import * as controller from '@/controllers/profile.controller'; +import { validateSdkRequest } from '@/utils/auth'; +import type { FastifyPluginCallback } from 'fastify'; + +const eventRouter: FastifyPluginCallback = (fastify, opts, done) => { + fastify.addHook('preHandler', async (req, reply) => { + try { + const projectId = await validateSdkRequest(req.headers); + req.projectId = projectId; + + const bot = req.headers['user-agent'] + ? isBot(req.headers['user-agent']) + : null; + + if (bot) { + reply.log.warn({ ...req.headers, bot }, 'Bot detected (profile)'); + reply.status(202).send('OK'); + } + } catch (e) { + reply.status(401).send(); + return; + } + }); + + fastify.route({ + method: 'POST', + url: '/', + handler: controller.updateProfile, + }); + + fastify.route({ + method: 'POST', + url: '/increment', + handler: controller.incrementProfileProperty, + }); + + fastify.route({ + method: 'POST', + url: '/decrement', + handler: controller.decrementProfileProperty, + }); + done(); +}; + +export default eventRouter; diff --git a/apps/api/src/utils/auth.ts b/apps/api/src/utils/auth.ts new file mode 100644 index 00000000..825396d4 --- /dev/null +++ b/apps/api/src/utils/auth.ts @@ -0,0 +1,43 @@ +import type { RawRequestDefaultExpression } from 'fastify'; + +import { verifyPassword } from '@openpanel/common'; +import { db } from '@openpanel/db'; + +export async function validateSdkRequest( + headers: RawRequestDefaultExpression['headers'] +): Promise { + const clientId = headers['openpanel-client-id'] as string; + const clientSecret = headers['openpanel-client-secret'] as string; + const origin = headers.origin; + if (!clientId) { + throw new Error('Misisng client id'); + } + + const client = await db.client.findUnique({ + where: { + id: clientId, + }, + }); + + if (!client) { + throw new Error('Invalid client id'); + } + + if (client.secret) { + if (!(await verifyPassword(clientSecret || '', client.secret))) { + throw new Error('Invalid client secret'); + } + } else if (client.cors !== '*') { + const domainAllowed = client.cors.split(',').find((domain) => { + if (domain === origin) { + return true; + } + }); + + if (!domainAllowed) { + throw new Error('Invalid cors settings'); + } + } + + return client.project_id; +} diff --git a/apps/api/src/utils/logger.ts b/apps/api/src/utils/logger.ts new file mode 100644 index 00000000..eb3bf857 --- /dev/null +++ b/apps/api/src/utils/logger.ts @@ -0,0 +1,29 @@ +import type { TransportTargetOptions } from 'pino'; +import pino from 'pino'; + +const targets: TransportTargetOptions[] = + process.env.NODE_ENV === 'production' + ? [ + { + target: '@logtail/pino', + options: { sourceToken: process.env.BETTERSTACK_TOKEN }, + }, + ] + : [ + { + target: 'pino-pretty', + }, + ]; + +const transport = pino.transport({ + targets, +}); + +export const logger = pino(transport); + +export function logInfo(msg: string, obj?: unknown) { + logger.info(obj, msg); +} + +export const noop = (message: string) => (error: unknown) => + logger.error(error, message); diff --git a/apps/api/src/utils/parseIp.ts b/apps/api/src/utils/parseIp.ts new file mode 100644 index 00000000..b0acd4eb --- /dev/null +++ b/apps/api/src/utils/parseIp.ts @@ -0,0 +1,61 @@ +import type { FastifyRequest } from 'fastify'; + +import { logger } from './logger'; + +interface RemoteIpLookupResponse { + country: string | undefined; + city: string | undefined; + stateprov: string | undefined; + continent: string | undefined; +} + +interface GeoLocation { + country: string | undefined; + city: string | undefined; + region: string | undefined; + continent: string | undefined; +} + +const geo: GeoLocation = { + country: undefined, + city: undefined, + region: undefined, + continent: undefined, +}; + +const ignore = ['127.0.0.1', '::1']; + +export function getClientIp(req: FastifyRequest) { + if (req.headers['cf-connecting-ip']) { + return String(req.headers['cf-connecting-ip']); + } + + if (req.headers['x-forwarded-for']) { + return String(req.headers['x-forwarded-for']); + } + + return null; +} + +export async function parseIp(ip?: string): Promise { + if (!ip || ignore.includes(ip)) { + return geo; + } + + try { + const geo = await fetch(`${process.env.GEO_IP_HOST}/${ip}`, { + signal: AbortSignal.timeout(2000), + }); + const res = (await geo.json()) as RemoteIpLookupResponse; + + return { + country: res.country, + city: res.city, + region: res.stateprov, + continent: res.continent, + }; + } catch (e) { + logger.error('Failed to fetch geo location for ip', e); + return geo; + } +} diff --git a/apps/api/src/utils/parseReferrer.ts b/apps/api/src/utils/parseReferrer.ts new file mode 100644 index 00000000..0ff61a1b --- /dev/null +++ b/apps/api/src/utils/parseReferrer.ts @@ -0,0 +1,50 @@ +import { stripTrailingSlash } from "@openpanel/common"; + +import referrers from "../referrers"; + +function getHostname(url: string | undefined) { + if (!url) { + return ""; + } + + try { + return new URL(url).hostname; + } catch (e) { + return ""; + } +} + +export function parseReferrer(url: string | undefined) { + const hostname = getHostname(url); + const match = referrers[hostname] ?? referrers[hostname.replace("www.", "")]; + + return { + name: match?.name ?? "", + type: match?.type ?? "unknown", + url: stripTrailingSlash(url ?? ""), + }; +} + +export function getReferrerWithQuery( + query: Record | undefined, +) { + if (!query) { + return null; + } + + const source = query.utm_source ?? query.ref ?? query.utm_referrer ?? ""; + + const match = Object.values(referrers).find( + (referrer) => referrer.name.toLowerCase() === source?.toLowerCase(), + ); + + if (!match) { + return null; + } + + return { + name: match.name, + type: match.type, + url: "", + }; +} diff --git a/apps/api/src/utils/parseUserAgent.ts b/apps/api/src/utils/parseUserAgent.ts new file mode 100644 index 00000000..4a8842a9 --- /dev/null +++ b/apps/api/src/utils/parseUserAgent.ts @@ -0,0 +1,33 @@ +import { UAParser } from 'ua-parser-js'; + +export function isUserAgentSet(ua: string) { + return ua !== 'node' && ua !== 'undici' && !!ua; +} + +export function parseUserAgent(ua: string) { + const res = new UAParser(ua).getResult(); + return { + os: res.os.name, + osVersion: res.os.version, + browser: res.browser.name, + browserVersion: res.browser.version, + device: res.device.type ?? getDevice(ua), + brand: res.device.vendor, + model: res.device.model, + }; +} + +export function getDevice(ua: string) { + const t1 = + /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test( + ua + ); + const t2 = + /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test( + ua.slice(0, 4) + ); + if (t1 || t2) { + return 'mobile'; + } + return 'desktop'; +} diff --git a/apps/api/src/utils/url.ts b/apps/api/src/utils/url.ts new file mode 100644 index 00000000..c6d3723d --- /dev/null +++ b/apps/api/src/utils/url.ts @@ -0,0 +1,48 @@ +export function parseSearchParams( + params: URLSearchParams +): Record | undefined { + const result: Record = {}; + for (const [key, value] of params.entries()) { + result[key] = value; + } + return Object.keys(result).length ? result : undefined; +} + +export function parsePath(path?: string): { + query?: Record; + path: string; + hash?: string; +} { + if (!path) { + return { + path: '', + }; + } + + try { + const url = new URL(path); + return { + query: parseSearchParams(url.searchParams), + path: url.pathname, + hash: url.hash || undefined, + }; + } catch (error) { + return { + path, + }; + } +} + +export function isSameDomain( + url1: string | undefined, + url2: string | undefined +) { + if (!url1 || !url2) { + return false; + } + try { + return new URL(url1).hostname === new URL(url2).hostname; + } catch (e) { + return false; + } +} diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 00000000..a291eef2 --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "@openpanel/tsconfig/base.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "@/*": ["./src/*"] + }, + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json" + }, + "include": ["."], + "exclude": ["node_modules"] +} diff --git a/apps/api/tsup.config.ts b/apps/api/tsup.config.ts new file mode 100644 index 00000000..12e0eb1b --- /dev/null +++ b/apps/api/tsup.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from 'tsup'; +import type { Options } from 'tsup'; + +const options: Options = { + clean: true, + entry: ['src/index.ts'], + noExternal: [/^@openpanel\/.*$/u, /^@\/.*$/u], + sourcemap: true, + splitting: false, +}; + +if (process.env.WATCH) { + options.watch = ['src/**/*', '../../packages/**/*']; + options.onSuccess = 'node dist/index.js'; + options.minify = false; +} + +export default defineConfig(options); diff --git a/apps/web/.gitignore b/apps/dashboard/.gitignore similarity index 100% rename from apps/web/.gitignore rename to apps/dashboard/.gitignore diff --git a/apps/dashboard/Dockerfile b/apps/dashboard/Dockerfile new file mode 100644 index 00000000..0f19d891 --- /dev/null +++ b/apps/dashboard/Dockerfile @@ -0,0 +1,113 @@ +FROM --platform=linux/amd64 node:20-slim AS base + +ARG NEXT_PUBLIC_DASHBOARD_URL +ENV NEXT_PUBLIC_DASHBOARD_URL=$NEXT_PUBLIC_DASHBOARD_URL + +ARG NEXT_PUBLIC_API_URL +ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL + +ARG DATABASE_URL +ENV DATABASE_URL=$DATABASE_URL + +ARG CLICKHOUSE_DB +ENV CLICKHOUSE_DB=$CLICKHOUSE_DB + +ARG CLICKHOUSE_PASSWORD +ENV CLICKHOUSE_PASSWORD=$CLICKHOUSE_PASSWORD + +ARG CLICKHOUSE_URL +ENV CLICKHOUSE_URL=$CLICKHOUSE_URL + +ARG CLICKHOUSE_USER +ENV CLICKHOUSE_USER=$CLICKHOUSE_USER + +ARG REDIS_URL +ENV REDIS_URL=$REDIS_URL + +ARG NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY +ENV NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=$NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY + +ARG CLERK_SECRET_KEY +ENV CLERK_SECRET_KEY=$CLERK_SECRET_KEY + +ENV PNPM_HOME="/pnpm" + +ENV PATH="$PNPM_HOME:$PATH" + +RUN corepack enable + +ARG NODE_VERSION=20 + +RUN apt update \ + && apt install -y curl \ + && curl -L https://raw.githubusercontent.com/tj/n/master/bin/n -o n \ + && bash n $NODE_VERSION \ + && rm n \ + && npm install -g n + +WORKDIR /app + +COPY package.json package.json +COPY pnpm-lock.yaml pnpm-lock.yaml +COPY pnpm-workspace.yaml pnpm-workspace.yaml +COPY apps/dashboard/package.json apps/dashboard/package.json +COPY packages/db/package.json packages/db/package.json +COPY packages/redis/package.json packages/redis/package.json +COPY packages/queue/package.json packages/queue/package.json +COPY packages/common/package.json packages/common/package.json +COPY packages/constants/package.json packages/constants/package.json +COPY packages/validation/package.json packages/validation/package.json +COPY packages/sdk/package.json packages/sdk/package.json + +# BUILD +FROM base AS build + +WORKDIR /app/apps/dashboard +RUN pnpm install --frozen-lockfile --ignore-scripts + +WORKDIR /app +COPY apps apps +COPY packages packages +COPY tooling tooling +RUN pnpm db:codegen + +WORKDIR /app/apps/dashboard +RUN pnpm run build + +# PROD +FROM base AS prod + +WORKDIR /app/apps/dashboard +RUN pnpm install --frozen-lockfile --prod --ignore-scripts + +# FINAL +FROM base AS runner + +COPY --from=build /app/package.json /app/package.json +COPY --from=prod /app/node_modules /app/node_modules +# Apps +COPY --from=build /app/apps/dashboard /app/apps/dashboard +# Apps node_modules +COPY --from=prod /app/apps/dashboard/node_modules /app/apps/dashboard/node_modules +# Packages +COPY --from=build /app/packages/db /app/packages/db +COPY --from=build /app/packages/redis /app/packages/redis +COPY --from=build /app/packages/common /app/packages/common +COPY --from=build /app/packages/queue /app/packages/queue +COPY --from=build /app/packages/constants /app/packages/constants +COPY --from=build /app/packages/validation /app/packages/validation +COPY --from=build /app/packages/sdk /app/packages/sdk +# Packages node_modules +COPY --from=prod /app/packages/db/node_modules /app/packages/db/node_modules +COPY --from=prod /app/packages/redis/node_modules /app/packages/redis/node_modules +COPY --from=prod /app/packages/common/node_modules /app/packages/common/node_modules +COPY --from=prod /app/packages/validation/node_modules /app/packages/validation/node_modules +COPY --from=prod /app/packages/queue/node_modules /app/packages/queue/node_modules + +RUN pnpm db:codegen + +WORKDIR /app/apps/dashboard + +EXPOSE 3000 + +CMD ["pnpm", "start"] \ No newline at end of file diff --git a/apps/web/README.md b/apps/dashboard/README.md similarity index 100% rename from apps/web/README.md rename to apps/dashboard/README.md diff --git a/apps/dashboard/TOOODOO.md b/apps/dashboard/TOOODOO.md new file mode 100644 index 00000000..d61d9b44 --- /dev/null +++ b/apps/dashboard/TOOODOO.md @@ -0,0 +1,6 @@ +- new org +- create project +- all trpc mutations seems to break in prod +- top event convertions + - create events_meta (name, color, icon) + - edit event convertion diff --git a/apps/web/components.json b/apps/dashboard/components.json similarity index 100% rename from apps/web/components.json rename to apps/dashboard/components.json diff --git a/apps/web/next.config.mjs b/apps/dashboard/next.config.mjs similarity index 74% rename from apps/web/next.config.mjs rename to apps/dashboard/next.config.mjs index 959ac96c..6c2cd5a9 100644 --- a/apps/web/next.config.mjs +++ b/apps/dashboard/next.config.mjs @@ -7,9 +7,13 @@ await import('./src/env.mjs'); /** @type {import("next").NextConfig} */ const config = { reactStrictMode: true, - transpilePackages: [], + transpilePackages: ['@openpanel/queue'], eslint: { ignoreDuringBuilds: true }, typescript: { ignoreBuildErrors: true }, + experimental: { + // Avoid "Critical dependency: the request of a dependency is an expression" + serverComponentsExternalPackages: ['bullmq'], + }, /** * If you are using `appDir` then you must comment the below `i18n` config out. * diff --git a/apps/dashboard/package.json b/apps/dashboard/package.json new file mode 100644 index 00000000..2799069e --- /dev/null +++ b/apps/dashboard/package.json @@ -0,0 +1,130 @@ +{ + "name": "@openpanel/dashboard", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "rm -rf .next && pnpm with-env next dev", + "testing": "pnpm dev", + "build": "next build", + "start": "next start", + "lint": "eslint .", + "format": "prettier --write \"**/*.{tsx,mjs,ts,md,json}\"", + "typecheck": "tsc --noEmit", + "with-env": "dotenv -e ../../.env -c --" + }, + "dependencies": { + "@clerk/nextjs": "^4.29.7", + "@clickhouse/client": "^0.2.9", + "@hookform/resolvers": "^3.3.4", + "@openpanel/common": "workspace:^", + "@openpanel/constants": "workspace:^", + "@openpanel/db": "workspace:^", + "@openpanel/queue": "workspace:^", + "@openpanel/validation": "workspace:^", + "@radix-ui/react-accordion": "^1.1.2", + "@radix-ui/react-alert-dialog": "^1.0.5", + "@radix-ui/react-aspect-ratio": "^1.0.3", + "@radix-ui/react-avatar": "^1.0.4", + "@radix-ui/react-checkbox": "^1.0.4", + "@radix-ui/react-dialog": "^1.0.5", + "@radix-ui/react-dropdown-menu": "^2.0.6", + "@radix-ui/react-label": "^2.0.2", + "@radix-ui/react-popover": "^1.0.7", + "@radix-ui/react-progress": "^1.0.3", + "@radix-ui/react-scroll-area": "^1.0.5", + "@radix-ui/react-slot": "^1.0.2", + "@radix-ui/react-toast": "^1.1.5", + "@radix-ui/react-toggle": "^1.0.3", + "@radix-ui/react-toggle-group": "^1.0.4", + "@radix-ui/react-tooltip": "^1.0.7", + "@reduxjs/toolkit": "^1.9.7", + "@t3-oss/env-nextjs": "^0.7.3", + "@tanstack/react-query": "^4.36.1", + "@tanstack/react-table": "^8.11.8", + "@trpc/client": "^10.45.1", + "@trpc/next": "^10.45.1", + "@trpc/react-query": "^10.45.1", + "@trpc/server": "^10.45.1", + "@types/d3": "^7.4.3", + "bcrypt": "^5.1.1", + "class-variance-authority": "^0.7.0", + "clsx": "^2.1.0", + "cmdk": "^0.2.1", + "d3": "^7.8.5", + "date-fns": "^3.3.1", + "embla-carousel-react": "8.0.0-rc22", + "flag-icons": "^7.1.0", + "hamburger-react": "^2.5.0", + "lodash.debounce": "^4.0.8", + "lodash.throttle": "^4.1.1", + "lottie-react": "^2.4.0", + "lucide-react": "^0.331.0", + "mathjs": "^12.3.2", + "mitt": "^3.0.1", + "next": "~14.0.4", + "next-auth": "^4.24.5", + "next-themes": "^0.2.1", + "nuqs": "^1.16.1", + "prisma-error-enum": "^0.1.3", + "ramda": "^0.29.1", + "random-animal-name": "^0.1.1", + "react": "18.2.0", + "react-animate-height": "^3.2.3", + "react-animated-numbers": "^0.18.0", + "react-day-picker": "^8.10.0", + "react-dom": "18.2.0", + "react-hook-form": "^7.50.1", + "react-in-viewport": "1.0.0-alpha.30", + "react-redux": "^8.1.3", + "react-responsive": "^9.0.2", + "react-svg-worldmap": "2.0.0-alpha.16", + "react-syntax-highlighter": "^15.5.0", + "react-use-websocket": "^4.7.0", + "react-virtualized-auto-sizer": "^1.0.22", + "recharts": "^2.12.0", + "request-ip": "^3.3.0", + "short-unique-id": "^5.0.3", + "slugify": "^1.6.6", + "sonner": "^1.4.0", + "superjson": "^1.13.3", + "tailwind-merge": "^1.14.0", + "tailwindcss-animate": "^1.0.7", + "usehooks-ts": "^2.14.0", + "zod": "^3.22.4" + }, + "devDependencies": { + "@openpanel/eslint-config": "workspace:*", + "@openpanel/prettier-config": "workspace:*", + "@openpanel/tsconfig": "workspace:*", + "@types/bcrypt": "^5.0.2", + "@types/lodash.debounce": "^4.0.9", + "@types/lodash.throttle": "^4.1.9", + "@types/node": "^18.19.15", + "@types/ramda": "^0.29.10", + "@types/react": "^18.2.20", + "@types/react-dom": "^18.2.7", + "@types/react-syntax-highlighter": "^15.5.11", + "@types/request-ip": "^0.0.41", + "@typescript-eslint/eslint-plugin": "^6.21.0", + "@typescript-eslint/parser": "^6.21.0", + "autoprefixer": "^10.4.17", + "eslint": "^8.56.0", + "postcss": "^8.4.35", + "prettier": "^3.2.5", + "prettier-plugin-tailwindcss": "^0.5.11", + "tailwindcss": "^3.4.1", + "typescript": "^5.3.3" + }, + "ct3aMetadata": { + "initVersion": "7.21.0" + }, + "eslintConfig": { + "root": true, + "extends": [ + "@openpanel/eslint-config/base", + "@openpanel/eslint-config/react", + "@openpanel/eslint-config/nextjs" + ] + }, + "prettier": "@openpanel/prettier-config" +} diff --git a/apps/web/postcss.config.cjs b/apps/dashboard/postcss.config.cjs similarity index 100% rename from apps/web/postcss.config.cjs rename to apps/dashboard/postcss.config.cjs diff --git a/apps/web/public/favicon.ico b/apps/dashboard/public/favicon.ico similarity index 100% rename from apps/web/public/favicon.ico rename to apps/dashboard/public/favicon.ico diff --git a/apps/dashboard/public/logo-2.svg b/apps/dashboard/public/logo-2.svg new file mode 100644 index 00000000..264890a2 --- /dev/null +++ b/apps/dashboard/public/logo-2.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/apps/dashboard/public/logo-with-text.svg b/apps/dashboard/public/logo-with-text.svg new file mode 100644 index 00000000..53198a73 --- /dev/null +++ b/apps/dashboard/public/logo-with-text.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/apps/dashboard/public/logo.svg b/apps/dashboard/public/logo.svg new file mode 100644 index 00000000..e45d0d95 --- /dev/null +++ b/apps/dashboard/public/logo.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/create-client.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/create-client.tsx new file mode 100644 index 00000000..71757a87 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/create-client.tsx @@ -0,0 +1,252 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { CheckboxInput } from '@/components/ui/checkbox'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { useAppParams } from '@/hooks/useAppParams'; +import { clipboard } from '@/utils/clipboard'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { Copy, SaveIcon } from 'lucide-react'; +import Link from 'next/link'; +import { useRouter } from 'next/navigation'; +import type { SubmitHandler } from 'react-hook-form'; +import { Controller, useForm, useWatch } from 'react-hook-form'; +import { toast } from 'sonner'; +import { z } from 'zod'; + +import { api, handleError } from '../../../_trpc/client'; + +const validation = z.object({ + name: z.string().min(1), + domain: z.string().optional(), + withSecret: z.boolean().optional(), +}); + +type IForm = z.infer; + +export function CreateClient() { + const [open, setOpen] = useState(false); + const { organizationId, projectId } = useAppParams(); + const clients = api.client.list.useQuery({ + organizationId, + }); + const clientsCount = clients.data?.length; + + useEffect(() => { + if (clientsCount === 0) { + setOpen(true); + } + }, [clientsCount]); + + const router = useRouter(); + const form = useForm({ + resolver: zodResolver(validation), + defaultValues: { + withSecret: false, + name: '', + domain: '', + }, + }); + const mutation = api.client.create2.useMutation({ + onError: handleError, + onSuccess() { + toast.success('Client created'); + router.refresh(); + }, + }); + const onSubmit: SubmitHandler = (values) => { + mutation.mutate({ + name: values.name, + domain: values.withSecret ? undefined : values.domain, + organizationId, + projectId, + }); + }; + + const watch = useWatch({ + control: form.control, + name: 'withSecret', + }); + + return ( + + {mutation.isSuccess ? ( + <> + setOpen(false)} + > + + Success + + {mutation.data.clientSecret + ? 'Use your client id and secret with our SDK to send events to us. ' + : 'Use your client id with our SDK to send events to us. '} + See our{' '} + + documentation + + + +
+ + {mutation.data.clientSecret ? ( + + ) : ( +
+ +
+ {mutation.data.cors} +
+
+ You can update cors settings{' '} + + here + +
+
+ )} +
+ + + +
+ + ) : ( + <> + setOpen(false)} + > + + Let's connect + + Create a client so you can start send events to us 🚀 + + +
+
+
+ + +
+ ( + { + field.onChange(!checked); + }} + > + This is a website + + )} + /> +
+ + +
+
+ + + + +
+
+ + )} +
+ ); +} + +//
+//
+// Select your framework and we'll generate a client for you. +//
+//
+// +// +// +// +// +// +//
+//
diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/[dashboardId]/list-reports.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/[dashboardId]/list-reports.tsx new file mode 100644 index 00000000..13be6c69 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/[dashboardId]/list-reports.tsx @@ -0,0 +1,139 @@ +'use client'; + +import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header'; +import { useOverviewOptions } from '@/components/overview/useOverviewOptions'; +import { LazyChart } from '@/components/report/chart/LazyChart'; +import { Button } from '@/components/ui/button'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; +import { useAppParams } from '@/hooks/useAppParams'; +import { cn } from '@/utils/cn'; +import { + getDefaultIntervalByDates, + getDefaultIntervalByRange, +} from '@openpanel/constants'; +import type { getReportsByDashboardId } from '@openpanel/db'; +import { ChevronRight, MoreHorizontal, PlusIcon, Trash } from 'lucide-react'; +import Link from 'next/link'; +import { useRouter } from 'next/navigation'; + +import { OverviewReportRange } from '../../overview-sticky-header'; + +interface ListReportsProps { + reports: Awaited>; +} + +export function ListReports({ reports }: ListReportsProps) { + const router = useRouter(); + const params = useAppParams<{ dashboardId: string }>(); + const { range, startDate, endDate } = useOverviewOptions(); + + return ( + <> + + + + +
+ {reports.map((report) => { + const chartRange = report.range; // timeRanges[report.range]; + return ( +
+ +
+
{report.name}
+ {chartRange !== null && ( +
+ + {chartRange} + + {startDate && endDate ? ( + Custom dates + ) : ( + range !== null && {range} + )} +
+ )} +
+
+ + + + + + + { + // event.stopPropagation(); + // deletion.mutate({ + // reportId: report.id, + // }); + }} + > + + Delete + + + + + +
+ +
+ +
+
+ ); + })} +
+ + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/[dashboardId]/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/[dashboardId]/page.tsx new file mode 100644 index 00000000..5bf0b73a --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/[dashboardId]/page.tsx @@ -0,0 +1,34 @@ +import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout'; +import { getExists } from '@/server/pageExists'; +import { getDashboardById, getReportsByDashboardId } from '@openpanel/db'; +import { notFound } from 'next/navigation'; + +import { ListReports } from './list-reports'; + +interface PageProps { + params: { + organizationId: string; + projectId: string; + dashboardId: string; + }; +} + +export default async function Page({ + params: { organizationId, projectId, dashboardId }, +}: PageProps) { + const [dashboard, reports] = await Promise.all([ + getDashboardById(dashboardId, projectId), + getReportsByDashboardId(dashboardId), + getExists(organizationId), + ]); + + if (!dashboard) { + return notFound(); + } + + return ( + + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/header-dashboards.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/header-dashboards.tsx new file mode 100644 index 00000000..62e50b99 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/header-dashboards.tsx @@ -0,0 +1,26 @@ +'use client'; + +import { Button } from '@/components/ui/button'; +import { pushModal } from '@/modals'; +import { PlusIcon } from 'lucide-react'; + +import { StickyBelowHeader } from '../layout-sticky-below-header'; + +export function HeaderDashboards() { + return ( + +
+
+ +
+ + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/list-dashboards.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/list-dashboards.tsx new file mode 100644 index 00000000..c035e02e --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/list-dashboards.tsx @@ -0,0 +1,104 @@ +'use client'; + +import { api, handleErrorToastOptions } from '@/app/_trpc/client'; +import { Card, CardActions, CardActionsItem } from '@/components/Card'; +import { FullPageEmptyState } from '@/components/FullPageEmptyState'; +import { Button } from '@/components/ui/button'; +import { ToastAction } from '@/components/ui/toast'; +import { useAppParams } from '@/hooks/useAppParams'; +import { pushModal } from '@/modals'; +import type { IServiceDashboards } from '@openpanel/db'; +import { LayoutPanelTopIcon, Pencil, PlusIcon, Trash } from 'lucide-react'; +import Link from 'next/link'; +import { useRouter } from 'next/navigation'; +import { toast } from 'sonner'; + +interface ListDashboardsProps { + dashboards: IServiceDashboards; +} + +export function ListDashboards({ dashboards }: ListDashboardsProps) { + const router = useRouter(); + const params = useAppParams(); + const { organizationId, projectId } = params; + const deletion = api.dashboard.delete.useMutation({ + onError: (error, variables) => { + return handleErrorToastOptions({ + action: { + label: 'Force delete', + onClick: () => { + deletion.mutate({ + forceDelete: true, + id: variables.id, + }); + }, + }, + })(error); + }, + onSuccess() { + router.refresh(); + toast('Success', { + description: 'Dashboard deleted.', + }); + }, + }); + + if (dashboards.length === 0) { + return ( + +

You have not created any dashboards for this project yet

+ +
+ ); + } + + return ( + <> +
+ {dashboards.map((item) => ( + +
+ + {item.name} + +
+ + + + + + + + + +
+ ))} +
+ + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/page.tsx new file mode 100644 index 00000000..e3025033 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/dashboards/page.tsx @@ -0,0 +1,29 @@ +import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout'; +import { getExists } from '@/server/pageExists'; +import { getDashboardsByProjectId } from '@openpanel/db'; + +import { HeaderDashboards } from './header-dashboards'; +import { ListDashboards } from './list-dashboards'; + +interface PageProps { + params: { + projectId: string; + organizationId: string; + }; +} + +export default async function Page({ + params: { projectId, organizationId }, +}: PageProps) { + const [dashboards] = await Promise.all([ + getDashboardsByProjectId(projectId), + await getExists(organizationId, projectId), + ]); + + return ( + + {dashboards.length > 0 && } + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-chart.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-chart.tsx new file mode 100644 index 00000000..445b21ee --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-chart.tsx @@ -0,0 +1,41 @@ +import { ChartSwitchShortcut } from '@/components/report/chart'; +import type { IChartEvent } from '@openpanel/validation'; + +interface Props { + projectId: string; + events?: string[]; + filters?: any[]; +} + +export function EventChart({ projectId, filters, events }: Props) { + const fallback: IChartEvent[] = [ + { + id: 'A', + name: '*', + displayName: 'All events', + segment: 'event', + filters: filters ?? [], + }, + ]; + + return ( +
+ 0 + ? events.map((name) => ({ + id: name, + name, + displayName: name, + segment: 'event', + filters: filters ?? [], + })) + : fallback + } + /> +
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-details.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-details.tsx new file mode 100644 index 00000000..b06b4892 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-details.tsx @@ -0,0 +1,217 @@ +'use client'; + +import type { Dispatch, SetStateAction } from 'react'; +import { ChartSwitchShortcut } from '@/components/report/chart'; +import { KeyValue } from '@/components/ui/key-value'; +import { + Sheet, + SheetContent, + SheetHeader, + SheetTitle, +} from '@/components/ui/sheet'; +import { + useEventQueryFilters, + useEventQueryNamesFilter, +} from '@/hooks/useEventQueryFilters'; +import type { IServiceCreateEventPayload } from '@openpanel/db'; +import { round } from 'mathjs'; + +interface Props { + event: IServiceCreateEventPayload; + open: boolean; + setOpen: Dispatch>; +} +export function EventDetails({ event, open, setOpen }: Props) { + const { name } = event; + const [, setFilter] = useEventQueryFilters({ shallow: false }); + const [, setEvents] = useEventQueryNamesFilter({ shallow: false }); + + const common = [ + { + name: 'Duration', + value: event.duration ? round(event.duration / 1000, 1) : undefined, + }, + { + name: 'Referrer', + value: event.referrer, + onClick() { + setFilter('referrer', event.referrer ?? ''); + }, + }, + { + name: 'Referrer name', + value: event.referrerName, + onClick() { + setFilter('referrer_name', event.referrerName ?? ''); + }, + }, + { + name: 'Referrer type', + value: event.referrerType, + onClick() { + setFilter('referrer_type', event.referrerType ?? ''); + }, + }, + { + name: 'Brand', + value: event.brand, + onClick() { + setFilter('brand', event.brand ?? ''); + }, + }, + { + name: 'Model', + value: event.model, + onClick() { + setFilter('model', event.model ?? ''); + }, + }, + { + name: 'Browser', + value: event.browser, + onClick() { + setFilter('browser', event.browser ?? ''); + }, + }, + { + name: 'Browser version', + value: event.browserVersion, + onClick() { + setFilter('browser_version', event.browserVersion ?? ''); + }, + }, + { + name: 'OS', + value: event.os, + onClick() { + setFilter('os', event.os ?? ''); + }, + }, + { + name: 'OS version', + value: event.osVersion, + onClick() { + setFilter('os_version', event.osVersion ?? ''); + }, + }, + { + name: 'City', + value: event.city, + onClick() { + setFilter('city', event.city ?? ''); + }, + }, + { + name: 'Region', + value: event.region, + onClick() { + setFilter('region', event.region ?? ''); + }, + }, + { + name: 'Country', + value: event.country, + onClick() { + setFilter('country', event.country ?? ''); + }, + }, + { + name: 'Continent', + value: event.continent, + onClick() { + setFilter('continent', event.continent ?? ''); + }, + }, + { + name: 'Device', + value: event.device, + onClick() { + setFilter('device', event.device ?? ''); + }, + }, + ].filter((item) => typeof item.value === 'string' && item.value); + + const properties = Object.entries(event.properties) + .map(([name, value]) => ({ + name, + value: value as string | number | undefined, + })) + .filter((item) => typeof item.value === 'string' && item.value); + + return ( + + +
+
+ + {name.replace('_', ' ')} + + + {properties.length > 0 && ( +
+
Params
+
+ {properties.map((item) => ( + { + setFilter( + `properties.${item.name}`, + item.value ? String(item.value) : '', + 'is' + ); + }} + /> + ))} +
+
+ )} +
+
Common
+
+ {common.map((item) => ( + + ))} +
+
+ +
+
+
Similar events
+ +
+ +
+
+
+
+
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-edit.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-edit.tsx new file mode 100644 index 00000000..28836790 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-edit.tsx @@ -0,0 +1,176 @@ +import type { Dispatch, SetStateAction } from 'react'; +import { useEffect, useState } from 'react'; +import { api } from '@/app/_trpc/client'; +import { Button } from '@/components/ui/button'; +import { Checkbox } from '@/components/ui/checkbox'; +import { Label } from '@/components/ui/label'; +import { + Sheet, + SheetContent, + SheetFooter, + SheetHeader, + SheetTitle, +} from '@/components/ui/sheet'; +import { cn } from '@/utils/cn'; +import type { IServiceCreateEventPayload } from '@openpanel/db'; +import { useRouter } from 'next/navigation'; +import { toast } from 'sonner'; + +import { + EventIconColors, + EventIconMapper, + EventIconRecords, +} from './event-icon'; + +interface Props { + event: IServiceCreateEventPayload; + open: boolean; + setOpen: Dispatch>; +} + +export function EventEdit({ event, open, setOpen }: Props) { + const router = useRouter(); + + const { name, meta, projectId } = event; + + const [selectedIcon, setIcon] = useState( + meta?.icon ?? + EventIconRecords[name]?.icon ?? + EventIconRecords.default?.icon ?? + '' + ); + const [selectedColor, setColor] = useState( + meta?.color ?? + EventIconRecords[name]?.color ?? + EventIconRecords.default?.color ?? + '' + ); + const [conversion, setConversion] = useState(!!meta?.conversion); + + useEffect(() => { + if (meta?.icon) { + setIcon(meta.icon); + } + }, [meta?.icon]); + useEffect(() => { + if (meta?.color) { + setColor(meta.color); + } + }, [meta?.color]); + useEffect(() => { + setConversion(meta?.conversion ?? false); + }, [meta?.conversion]); + + const SelectedIcon = EventIconMapper[selectedIcon]!; + + const mutation = api.event.updateEventMeta.useMutation({ + onSuccess() { + // @ts-expect-error + document.querySelector('#close-sheet')?.click(); + toast('Event updated'); + router.refresh(); + }, + }); + const getBg = (color: string) => `bg-${color}-200`; + const getText = (color: string) => `text-${color}-700`; + + return ( + + + + Edit "{name}" + +
+
+ + +
+
+ +
+ {Object.entries(EventIconMapper).map(([name, Icon]) => ( + + ))} +
+
+
+ +
+ {EventIconColors.map((color) => ( + + ))} +
+
+
+ + + + +
+
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-icon.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-icon.tsx new file mode 100644 index 00000000..186f348c --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-icon.tsx @@ -0,0 +1,160 @@ +import { useEffect, useState } from 'react'; +import { api } from '@/app/_trpc/client'; +import { Button } from '@/components/ui/button'; +import { Checkbox } from '@/components/ui/checkbox'; +import { Label } from '@/components/ui/label'; +import { + Sheet, + SheetContent, + SheetFooter, + SheetHeader, + SheetTitle, + SheetTrigger, +} from '@/components/ui/sheet'; +import { cn } from '@/utils/cn'; +import type { EventMeta } from '@openpanel/db'; +import type { VariantProps } from 'class-variance-authority'; +import { cva } from 'class-variance-authority'; +import type { LucideIcon } from 'lucide-react'; +import * as Icons from 'lucide-react'; +import { useRouter } from 'next/navigation'; +import { toast } from 'sonner'; + +const variants = cva('flex items-center justify-center shrink-0 rounded-full', { + variants: { + size: { + sm: 'w-6 h-6', + default: 'w-10 h-10', + }, + }, + defaultVariants: { + size: 'default', + }, +}); + +type EventIconProps = VariantProps & { + name: string; + meta?: EventMeta; + projectId: string; + className?: string; +}; + +export const EventIconRecords: Record< + string, + { + icon: string; + color: string; + } +> = { + default: { + icon: 'BotIcon', + color: 'slate', + }, + screen_view: { + icon: 'MonitorPlayIcon', + color: 'blue', + }, + session_start: { + icon: 'ActivityIcon', + color: 'teal', + }, + link_out: { + icon: 'ExternalLinkIcon', + color: 'indigo', + }, +}; + +export const EventIconMapper: Record = { + DownloadIcon: Icons.DownloadIcon, + BotIcon: Icons.BotIcon, + BoxIcon: Icons.BoxIcon, + AccessibilityIcon: Icons.AccessibilityIcon, + ActivityIcon: Icons.ActivityIcon, + AirplayIcon: Icons.AirplayIcon, + AlarmCheckIcon: Icons.AlarmCheckIcon, + AlertTriangleIcon: Icons.AlertTriangleIcon, + BellIcon: Icons.BellIcon, + BoltIcon: Icons.BoltIcon, + CandyIcon: Icons.CandyIcon, + ConeIcon: Icons.ConeIcon, + MonitorPlayIcon: Icons.MonitorPlayIcon, + PizzaIcon: Icons.PizzaIcon, + SearchIcon: Icons.SearchIcon, + HomeIcon: Icons.HomeIcon, + MailIcon: Icons.MailIcon, + AngryIcon: Icons.AngryIcon, + AnnoyedIcon: Icons.AnnoyedIcon, + ArchiveIcon: Icons.ArchiveIcon, + AwardIcon: Icons.AwardIcon, + BadgeCheckIcon: Icons.BadgeCheckIcon, + BeerIcon: Icons.BeerIcon, + BluetoothIcon: Icons.BluetoothIcon, + BookIcon: Icons.BookIcon, + BookmarkIcon: Icons.BookmarkIcon, + BookCheckIcon: Icons.BookCheckIcon, + BookMinusIcon: Icons.BookMinusIcon, + BookPlusIcon: Icons.BookPlusIcon, + CalendarIcon: Icons.CalendarIcon, + ClockIcon: Icons.ClockIcon, + CogIcon: Icons.CogIcon, + LoaderIcon: Icons.LoaderIcon, + CrownIcon: Icons.CrownIcon, + FileIcon: Icons.FileIcon, + KeyRoundIcon: Icons.KeyRoundIcon, + GemIcon: Icons.GemIcon, + GlobeIcon: Icons.GlobeIcon, + LightbulbIcon: Icons.LightbulbIcon, + LightbulbOffIcon: Icons.LightbulbOffIcon, + LockIcon: Icons.LockIcon, + MessageCircleIcon: Icons.MessageCircleIcon, + RadioIcon: Icons.RadioIcon, + RepeatIcon: Icons.RepeatIcon, + ShareIcon: Icons.ShareIcon, + ExternalLinkIcon: Icons.ExternalLinkIcon, +}; + +export const EventIconColors = [ + 'rose', + 'pink', + 'fuchsia', + 'purple', + 'violet', + 'indigo', + 'blue', + 'sky', + 'cyan', + 'teal', + 'emerald', + 'green', + 'lime', + 'yellow', + 'amber', + 'orange', + 'red', + 'stone', + 'neutral', + 'zinc', + 'grey', + 'slate', +]; + +export function EventIcon({ className, name, size, meta }: EventIconProps) { + const Icon = + EventIconMapper[ + meta?.icon ?? + EventIconRecords[name]?.icon ?? + EventIconRecords.default?.icon ?? + '' + ]!; + const color = + meta?.color ?? + EventIconRecords[name]?.color ?? + EventIconRecords.default?.color ?? + ''; + + return ( +
+ +
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-list-item.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-list-item.tsx new file mode 100644 index 00000000..272fa67e --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-list-item.tsx @@ -0,0 +1,132 @@ +'use client'; + +import { useState } from 'react'; +import { ProfileAvatar } from '@/components/profiles/ProfileAvatar'; +import { SerieIcon } from '@/components/report/chart/SerieIcon'; +import { KeyValueSubtle } from '@/components/ui/key-value'; +import { useAppParams } from '@/hooks/useAppParams'; +import { useEventQueryFilters } from '@/hooks/useEventQueryFilters'; +import { useNumber } from '@/hooks/useNumerFormatter'; +import { cn } from '@/utils/cn'; +import { getProfileName } from '@/utils/getters'; +import type { IServiceCreateEventPayload } from '@openpanel/db'; + +import { EventDetails } from './event-details'; +import { EventEdit } from './event-edit'; +import { EventIcon } from './event-icon'; + +type EventListItemProps = IServiceCreateEventPayload; + +export function EventListItem(props: EventListItemProps) { + const { + profile, + createdAt, + name, + path, + duration, + brand, + browser, + city, + country, + device, + os, + projectId, + meta, + } = props; + const params = useAppParams(); + const [, setFilter] = useEventQueryFilters({ shallow: false }); + const [isDetailsOpen, setIsDetailsOpen] = useState(false); + const [isEditOpen, setIsEditOpen] = useState(false); + const number = useNumber(); + + return ( + <> + + +
+
+
+ + +
+
+ {createdAt.toLocaleTimeString()} +
+
+
+ {path && ( + + )} + {profile && ( + + {profile.avatar && } + {getProfileName(profile)} + + } + href={`/${params.organizationId}/${params.projectId}/profiles/${profile.id}`} + /> + )} + setFilter('city', city)} + value={ + <> + {country && } + {city} + + } + /> + setFilter('device', device)} + value={ + <> + {device && } + {brand || os} + + } + /> + {browser !== 'WebKit' && browser !== '' && ( + setFilter('browser', browser)} + value={ + <> + {browser && } + {browser} + + } + /> + )} +
+
+ + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-list.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-list.tsx new file mode 100644 index 00000000..2fff9d84 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-list.tsx @@ -0,0 +1,89 @@ +'use client'; + +import { Fragment, Suspense } from 'react'; +import { FullPageEmptyState } from '@/components/FullPageEmptyState'; +import { Pagination } from '@/components/Pagination'; +import { ChartSwitch, ChartSwitchShortcut } from '@/components/report/chart'; +import { Button } from '@/components/ui/button'; +import { useAppParams } from '@/hooks/useAppParams'; +import { useCursor } from '@/hooks/useCursor'; +import { useEventQueryFilters } from '@/hooks/useEventQueryFilters'; +import type { IServiceCreateEventPayload } from '@openpanel/db'; +import { isSameDay } from 'date-fns'; +import { GanttChartIcon } from 'lucide-react'; + +import { EventListItem } from './event-list-item'; +import EventListener from './event-listener'; + +function showDateHeader(a: Date, b?: Date) { + if (!b) return true; + return !isSameDay(a, b); +} + +interface EventListProps { + data: IServiceCreateEventPayload[]; + count: number; +} +export function EventList({ data, count }: EventListProps) { + const { cursor, setCursor } = useCursor(); + const [filters] = useEventQueryFilters(); + return ( + <> + {data.length === 0 ? ( + + {cursor !== 0 ? ( + <> +

Looks like you have reached the end of the list

+ + + ) : ( + <> + {filters.length ? ( +

Could not find any events with your filter

+ ) : ( +

We have not recieved any events yet

+ )} + + )} +
+ ) : ( + <> +
+ + +
+
+ {data.map((item, index, list) => ( + + {showDateHeader(item.createdAt, list[index - 1]?.createdAt) && ( +
+ {item.createdAt.toLocaleDateString()} +
+ )} + +
+ ))} +
+ + + )} + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-listener.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-listener.tsx new file mode 100644 index 00000000..6ea7627d --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/event-listener.tsx @@ -0,0 +1,91 @@ +'use client'; + +import { useEffect, useRef, useState } from 'react'; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from '@/components/ui/tooltip'; +import { useAppParams } from '@/hooks/useAppParams'; +import { cn } from '@/utils/cn'; +import type { IServiceCreateEventPayload } from '@openpanel/db'; +import { useQueryClient } from '@tanstack/react-query'; +import dynamic from 'next/dynamic'; +import { useRouter } from 'next/navigation'; +import useWebSocket from 'react-use-websocket'; +import { toast } from 'sonner'; + +const AnimatedNumbers = dynamic(() => import('react-animated-numbers'), { + ssr: false, + loading: () =>
0
, +}); + +export default function EventListener() { + const router = useRouter(); + const { projectId } = useAppParams(); + const ws = String(process.env.NEXT_PUBLIC_API_URL) + .replace(/^https/, 'wss') + .replace(/^http/, 'ws'); + const [counter, setCounter] = useState(0); + const [socketUrl] = useState(`${ws}/live/events/${projectId}`); + + useWebSocket(socketUrl, { + shouldReconnect: () => true, + onMessage(payload) { + const event = JSON.parse(payload.data) as IServiceCreateEventPayload; + if (event?.name) { + setCounter((prev) => prev + 1); + toast(`New event ${event.name} from ${event.country}!`); + } + }, + }); + + return ( + + + + + + {counter === 0 ? 'Listening to new events' : 'Click to refresh'} + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/page.tsx new file mode 100644 index 00000000..69f19d6f --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/events/page.tsx @@ -0,0 +1,82 @@ +import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout'; +import { OverviewFiltersButtons } from '@/components/overview/filters/overview-filters-buttons'; +import { OverviewFiltersDrawer } from '@/components/overview/filters/overview-filters-drawer'; +import { + eventQueryFiltersParser, + eventQueryNamesFilter, +} from '@/hooks/useEventQueryFilters'; +import { getExists } from '@/server/pageExists'; +import { getEventList, getEventsCount } from '@openpanel/db'; +import { parseAsInteger } from 'nuqs'; + +import { StickyBelowHeader } from '../layout-sticky-below-header'; +import { EventChart } from './event-chart'; +import { EventList } from './event-list'; + +interface PageProps { + params: { + projectId: string; + organizationId: string; + }; + searchParams: { + events?: string; + cursor?: string; + f?: string; + }; +} + +const nuqsOptions = { + shallow: false, +}; + +export default async function Page({ + params: { projectId, organizationId }, + searchParams, +}: PageProps) { + const filters = + eventQueryFiltersParser.parseServerSide(searchParams.f ?? '') ?? undefined; + const eventsFilter = eventQueryNamesFilter.parseServerSide( + searchParams.events ?? '' + ); + const [events, count] = await Promise.all([ + getEventList({ + cursor: + parseAsInteger.parseServerSide(searchParams.cursor ?? '') ?? undefined, + projectId, + take: 50, + events: eventsFilter, + filters, + }), + getEventsCount({ + projectId, + events: eventsFilter, + filters, + }), + getExists(organizationId, projectId), + ]); + + return ( + + + + + +
+ + +
+
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-menu.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-menu.tsx new file mode 100644 index 00000000..f0028c59 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-menu.tsx @@ -0,0 +1,160 @@ +'use client'; + +import { useEffect } from 'react'; +import { useAppParams } from '@/hooks/useAppParams'; +import { cn } from '@/utils/cn'; +import { useUser } from '@clerk/nextjs'; +import type { IServiceDashboards } from '@openpanel/db'; +import { + BuildingIcon, + CogIcon, + DotIcon, + GanttChartIcon, + KeySquareIcon, + LayoutPanelTopIcon, + UserIcon, + UsersIcon, + WallpaperIcon, + WarehouseIcon, +} from 'lucide-react'; +import type { LucideProps } from 'lucide-react'; +import Link from 'next/link'; +import { usePathname } from 'next/navigation'; + +function LinkWithIcon({ + href, + icon: Icon, + label, + active: overrideActive, + className, +}: { + href: string; + icon: React.ElementType; + label: React.ReactNode; + active?: boolean; + className?: string; +}) { + const pathname = usePathname(); + const active = overrideActive || href === pathname; + return ( + + +
{label}
+ + ); +} + +interface LayoutMenuProps { + dashboards: IServiceDashboards; +} +export default function LayoutMenu({ dashboards }: LayoutMenuProps) { + const { user } = useUser(); + + const pathname = usePathname(); + const params = useAppParams(); + const hasProjectId = + params.projectId && + params.projectId !== 'null' && + params.projectId !== 'undefined'; + const projectId = hasProjectId + ? params.projectId + : (user?.unsafeMetadata.projectId as string); + + useEffect(() => { + if (hasProjectId) { + user?.update({ + unsafeMetadata: { + projectId: params.projectId, + }, + }); + } + }, [params.projectId, hasProjectId]); + + return ( + <> + + + + + + {pathname?.includes('/settings/') && ( +
+ + + + + +
+ )} + {dashboards.length > 0 && ( +
+
Your dashboards
+
+ {dashboards.map((item) => ( + + {item.name} + + {item.project.name} + +
+ } + href={`/${item.organization_slug}/${item.project_id}/dashboards/${item.id}`} + /> + ))} +
+
+ )} + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-organization-selector.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-organization-selector.tsx new file mode 100644 index 00000000..8ce1c010 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-organization-selector.tsx @@ -0,0 +1,46 @@ +'use client'; + +import { Combobox } from '@/components/ui/combobox'; +import { useAppParams } from '@/hooks/useAppParams'; +import type { IServiceOrganization } from '@openpanel/db'; +import { Building } from 'lucide-react'; +import { useRouter } from 'next/navigation'; + +interface LayoutOrganizationSelectorProps { + organizations: IServiceOrganization[]; +} + +export default function LayoutOrganizationSelector({ + organizations, +}: LayoutOrganizationSelectorProps) { + const params = useAppParams(); + const router = useRouter(); + + const organization = organizations.find( + (item) => item.slug === params.organizationId + ); + + if (!organization) { + return null; + } + + return ( + item.slug) + .map((item) => ({ + label: item.name, + value: item.slug!, + })) ?? [] + } + onChange={(value) => { + router.push(`/${value}`); + }} + /> + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-project-selector.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-project-selector.tsx new file mode 100644 index 00000000..5b180cf1 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-project-selector.tsx @@ -0,0 +1,44 @@ +'use client'; + +import { Combobox } from '@/components/ui/combobox'; +import { useAppParams } from '@/hooks/useAppParams'; +import type { getProjectsByOrganizationSlug } from '@openpanel/db'; +import { usePathname, useRouter } from 'next/navigation'; + +interface LayoutProjectSelectorProps { + projects: Awaited>; +} +export default function LayoutProjectSelector({ + projects, +}: LayoutProjectSelectorProps) { + const router = useRouter(); + const { organizationId, projectId } = useAppParams(); + const pathname = usePathname() || ''; + + return ( +
+ { + if (organizationId && projectId) { + const split = pathname.replace(projectId, value).split('/'); + // slicing here will remove everything after /{orgId}/{projectId}/dashboards [slice here] /xxx/xxx/xxx + router.push(split.slice(0, 4).join('/')); + } else { + router.push(`/${organizationId}/${value}`); + } + }} + value={projectId} + items={ + projects.map((item) => ({ + label: item.name, + value: item.id, + })) ?? [] + } + /> +
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-sidebar.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-sidebar.tsx new file mode 100644 index 00000000..71970307 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/layout-sidebar.tsx @@ -0,0 +1,82 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { Logo } from '@/components/Logo'; +import { buttonVariants } from '@/components/ui/button'; +import { cn } from '@/utils/cn'; +import type { IServiceDashboards, IServiceOrganization } from '@openpanel/db'; +import { Rotate as Hamburger } from 'hamburger-react'; +import { PlusIcon } from 'lucide-react'; +import Link from 'next/link'; +import { usePathname } from 'next/navigation'; + +import LayoutMenu from './layout-menu'; +import LayoutOrganizationSelector from './layout-organization-selector'; + +interface LayoutSidebarProps { + organizations: IServiceOrganization[]; + dashboards: IServiceDashboards; + organizationId: string; + projectId: string; +} +export function LayoutSidebar({ + organizations, + dashboards, + organizationId, + projectId, +}: LayoutSidebarProps) { + const [active, setActive] = useState(false); + const pathname = usePathname(); + + useEffect(() => { + setActive(false); + }, [pathname]); + + return ( + <> + + + ) : ( + <> + {filters.length ? ( +

Could not find any profiles with your filter

+ ) : ( +

No profiles have been created yet

+ )} + + )} + + ) : ( + <> + +
+ {data.map((item) => ( + + ))} +
+ + + )} + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/reports/[reportId]/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/reports/[reportId]/page.tsx new file mode 100644 index 00000000..5eb5ef32 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/reports/[reportId]/page.tsx @@ -0,0 +1,42 @@ +import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout'; +import { getExists } from '@/server/pageExists'; +import { getOrganizationBySlug, getReportById } from '@openpanel/db'; +import { Pencil } from 'lucide-react'; +import { notFound } from 'next/navigation'; + +import ReportEditor from '../report-editor'; + +interface PageProps { + params: { + projectId: string; + reportId: string; + organizationId: string; + }; +} + +export default async function Page({ + params: { reportId, organizationId, projectId }, +}: PageProps) { + const [report] = await Promise.all([ + getReportById(reportId), + getExists(organizationId, projectId), + ]); + + if (!report) { + return notFound(); + } + + return ( + + {report.name} + + + } + > + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/reports/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/reports/page.tsx new file mode 100644 index 00000000..1558745f --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/reports/page.tsx @@ -0,0 +1,34 @@ +import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout'; +import { getExists } from '@/server/pageExists'; +import { getOrganizationBySlug } from '@openpanel/db'; +import { Pencil } from 'lucide-react'; +import { notFound } from 'next/navigation'; + +import ReportEditor from './report-editor'; + +interface PageProps { + params: { + organizationId: string; + projectId: string; + }; +} + +export default async function Page({ + params: { organizationId, projectId }, +}: PageProps) { + await getExists(organizationId, projectId); + + return ( + + Unnamed report + + + } + > + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/reports/report-editor.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/reports/report-editor.tsx new file mode 100644 index 00000000..ad308f52 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/reports/report-editor.tsx @@ -0,0 +1,109 @@ +'use client'; + +import { useEffect } from 'react'; +import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header'; +import { ChartSwitch } from '@/components/report/chart'; +import { ReportChartType } from '@/components/report/ReportChartType'; +import { ReportInterval } from '@/components/report/ReportInterval'; +import { ReportLineType } from '@/components/report/ReportLineType'; +import { ReportRange } from '@/components/report/ReportRange'; +import { ReportSaveButton } from '@/components/report/ReportSaveButton'; +import { + changeDateRanges, + changeDates, + changeEndDate, + changeStartDate, + ready, + reset, + setReport, +} from '@/components/report/reportSlice'; +import { ReportSidebar } from '@/components/report/sidebar/ReportSidebar'; +import { Button } from '@/components/ui/button'; +import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet'; +import { useAppParams } from '@/hooks/useAppParams'; +import { useDispatch, useSelector } from '@/redux'; +import type { IServiceReport } from '@openpanel/db'; +import { endOfDay, startOfDay } from 'date-fns'; +import { GanttChartSquareIcon } from 'lucide-react'; + +interface ReportEditorProps { + report: IServiceReport | null; +} + +export default function ReportEditor({ + report: initialReport, +}: ReportEditorProps) { + const { projectId } = useAppParams(); + const dispatch = useDispatch(); + const report = useSelector((state) => state.report); + + // Set report if reportId exists + useEffect(() => { + if (initialReport) { + dispatch(setReport(initialReport)); + } else { + dispatch(ready()); + } + + return () => { + dispatch(reset()); + }; + }, [initialReport, dispatch]); + + return ( + + + +
+ +
+
+
+ + { + dispatch(changeDateRanges(value)); + }} + dates={{ + startDate: report.startDate, + endDate: report.endDate, + }} + onDatesChange={(val) => { + if (!val) return; + + if (val.from && val.to) { + dispatch( + changeDates({ + startDate: startOfDay(val.from).toISOString(), + endDate: endOfDay(val.to).toISOString(), + }) + ); + } else if (val.from) { + dispatch(changeStartDate(startOfDay(val.from).toISOString())); + } else if (val.to) { + dispatch(changeEndDate(endOfDay(val.to).toISOString())); + } + }} + /> + + +
+
+ +
+
+
+ {report.ready && ( + + )} +
+ + + +
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/clients/list-clients.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/clients/list-clients.tsx new file mode 100644 index 00000000..3dea79e4 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/clients/list-clients.tsx @@ -0,0 +1,37 @@ +'use client'; + +import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header'; +import { columns } from '@/components/clients/table'; +import { DataTable } from '@/components/DataTable'; +import { Button } from '@/components/ui/button'; +import { useAppParams } from '@/hooks/useAppParams'; +import { pushModal } from '@/modals'; +import type { getClientsByOrganizationId } from '@openpanel/db'; +import { PlusIcon } from 'lucide-react'; + +interface ListClientsProps { + clients: Awaited>; +} +export default function ListClients({ clients }: ListClientsProps) { + const organizationId = useAppParams().organizationId; + + return ( + <> + +
+
+ +
+ +
+ +
+ + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/clients/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/clients/page.tsx new file mode 100644 index 00000000..7f66f77e --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/clients/page.tsx @@ -0,0 +1,22 @@ +import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout'; +import { getExists } from '@/server/pageExists'; +import { getClientsByOrganizationId } from '@openpanel/db'; + +import ListClients from './list-clients'; + +interface PageProps { + params: { + organizationId: string; + }; +} + +export default async function Page({ params: { organizationId } }: PageProps) { + await getExists(organizationId); + const clients = await getClientsByOrganizationId(organizationId); + + return ( + + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/edit-organization.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/edit-organization.tsx new file mode 100644 index 00000000..21090a8e --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/edit-organization.tsx @@ -0,0 +1,65 @@ +'use client'; + +import { api, handleError } from '@/app/_trpc/client'; +import { InputWithLabel } from '@/components/forms/InputWithLabel'; +import { Button } from '@/components/ui/button'; +import { Widget, WidgetBody, WidgetHead } from '@/components/Widget'; +import type { getOrganizationBySlug } from '@openpanel/db'; +import { useRouter } from 'next/navigation'; +import { useForm } from 'react-hook-form'; +import { toast } from 'sonner'; +import { z } from 'zod'; + +const validator = z.object({ + id: z.string().min(2), + name: z.string().min(2), +}); + +type IForm = z.infer; +interface EditOrganizationProps { + organization: Awaited>; +} +export default function EditOrganization({ + organization, +}: EditOrganizationProps) { + const router = useRouter(); + + const { register, handleSubmit, formState, reset } = useForm({ + defaultValues: organization ?? undefined, + }); + + const mutation = api.organization.update.useMutation({ + onSuccess(res) { + toast('Organization updated', { + description: 'Your organization has been updated.', + }); + reset(res); + router.refresh(); + }, + onError: handleError, + }); + + return ( +
{ + mutation.mutate(values); + })} + > + + + Org. details + + + + + + +
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/invite-user.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/invite-user.tsx new file mode 100644 index 00000000..4c058e0e --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/invite-user.tsx @@ -0,0 +1,59 @@ +import { api } from '@/app/_trpc/client'; +import { InputWithLabel } from '@/components/forms/InputWithLabel'; +import { Button } from '@/components/ui/button'; +import { useAppParams } from '@/hooks/useAppParams'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { zInviteUser } from '@openpanel/validation'; +import { SendIcon } from 'lucide-react'; +import { useRouter } from 'next/navigation'; +import { useForm } from 'react-hook-form'; +import { toast } from 'sonner'; +import type { z } from 'zod'; + +type IForm = z.infer; + +export function InviteUser() { + const router = useRouter(); + const { organizationId: organizationSlug } = useAppParams(); + + const { register, handleSubmit, formState, reset } = useForm({ + resolver: zodResolver(zInviteUser), + defaultValues: { + organizationSlug, + email: '', + role: 'org:member', + }, + }); + + const mutation = api.organization.inviteUser.useMutation({ + onSuccess() { + toast('User invited!', { + description: 'The user has been invited to the organization.', + }); + reset(); + router.refresh(); + }, + }); + + return ( +
mutation.mutate(values))} + className="flex items-end gap-4" + > + + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/invited-users.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/invited-users.tsx new file mode 100644 index 00000000..38835d4e --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/invited-users.tsx @@ -0,0 +1,64 @@ +'use client'; + +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from '@/components/ui/table'; +import { Widget, WidgetBody, WidgetHead } from '@/components/Widget'; +import type { IServiceInvites } from '@openpanel/db'; + +import { InviteUser } from './invite-user'; + +interface InvitedUsersProps { + invites: IServiceInvites; +} +export default function InvitedUsers({ invites }: InvitedUsersProps) { + return ( + + + Invites + + + + +
Invited users
+ + + + Email + Role + Status + Created + + + + {invites.map((item) => { + return ( + + {item.email} + {item.role} + {item.status} + + {new Date(item.createdAt).toLocaleString()} + + + ); + })} + + {invites.length === 0 && ( + + + No invites + + + )} + +
+
+
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/page.tsx new file mode 100644 index 00000000..cbc8edbe --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/organization/page.tsx @@ -0,0 +1,32 @@ +import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout'; +import { clerkClient } from '@clerk/nextjs'; +import { getInvites, getOrganizationBySlug } from '@openpanel/db'; +import { notFound } from 'next/navigation'; + +import EditOrganization from './edit-organization'; +import InvitedUsers from './invited-users'; + +interface PageProps { + params: { + organizationId: string; + }; +} + +export default async function Page({ params: { organizationId } }: PageProps) { + const organization = await getOrganizationBySlug(organizationId); + + if (!organization) { + return notFound(); + } + + const invites = await getInvites(organization.id); + + return ( + +
+ + +
+
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/page.tsx new file mode 100644 index 00000000..22b9c8b1 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/page.tsx @@ -0,0 +1 @@ +export { default } from './organization/page'; diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/profile/edit-profile.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/profile/edit-profile.tsx new file mode 100644 index 00000000..6adeea31 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/profile/edit-profile.tsx @@ -0,0 +1,84 @@ +'use client'; + +import { api, handleError } from '@/app/_trpc/client'; +import { InputWithLabel } from '@/components/forms/InputWithLabel'; +import { Button } from '@/components/ui/button'; +import { Widget, WidgetBody, WidgetHead } from '@/components/Widget'; +import { zodResolver } from '@hookform/resolvers/zod'; +import type { getUserById } from '@openpanel/db'; +import { useRouter } from 'next/navigation'; +import { useForm } from 'react-hook-form'; +import { toast } from 'sonner'; +import { z } from 'zod'; + +const validator = z.object({ + firstName: z.string().min(2), + lastName: z.string().min(2), + email: z.string().email(), +}); + +type IForm = z.infer; +interface EditProfileProps { + profile: Awaited>; +} +export default function EditProfile({ profile }: EditProfileProps) { + const router = useRouter(); + + const { register, handleSubmit, reset, formState } = useForm({ + resolver: zodResolver(validator), + defaultValues: { + firstName: profile.firstName ?? '', + lastName: profile.lastName ?? '', + email: profile.email ?? '', + }, + }); + + const mutation = api.user.update.useMutation({ + onSuccess(res) { + toast('Profile updated', { + description: 'Your profile has been updated.', + }); + reset(res); + router.refresh(); + }, + onError: handleError, + }); + + return ( +
{ + mutation.mutate(values); + })} + > + + + Your profile + + + + + + + + +
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/profile/logout.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/profile/logout.tsx new file mode 100644 index 00000000..e4e14826 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/profile/logout.tsx @@ -0,0 +1,20 @@ +'use client'; + +import { Widget, WidgetBody, WidgetHead } from '@/components/Widget'; +import { SignOutButton } from '@clerk/nextjs'; + +export function Logout() { + return ( + + + Sad part + + +

+ Sometime's you need to go. See you next time +

+ +
+
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/profile/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/profile/page.tsx new file mode 100644 index 00000000..1fb4d25d --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/profile/page.tsx @@ -0,0 +1,27 @@ +import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout'; +import { getExists } from '@/server/pageExists'; +import { auth } from '@clerk/nextjs'; +import { getUserById } from '@openpanel/db'; + +import EditProfile from './edit-profile'; +import { Logout } from './logout'; + +interface PageProps { + params: { + organizationId: string; + }; +} +export default async function Page({ params: { organizationId } }: PageProps) { + const { userId } = auth(); + await getExists(organizationId); + const profile = await getUserById(userId!); + + return ( + +
+ + +
+
+ ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/projects/list-projects.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/projects/list-projects.tsx new file mode 100644 index 00000000..deb3a173 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/projects/list-projects.tsx @@ -0,0 +1,40 @@ +'use client'; + +import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header'; +import { DataTable } from '@/components/DataTable'; +import { columns } from '@/components/projects/table'; +import { Button } from '@/components/ui/button'; +import { useAppParams } from '@/hooks/useAppParams'; +import { pushModal } from '@/modals'; +import type { getProjectsByOrganizationSlug } from '@openpanel/db'; +import { PlusIcon } from 'lucide-react'; + +interface ListProjectsProps { + projects: Awaited>; +} +export default function ListProjects({ projects }: ListProjectsProps) { + const organizationId = useAppParams().organizationId; + return ( + <> + +
+
+ +
+ +
+ +
+ + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/projects/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/projects/page.tsx new file mode 100644 index 00000000..b6976bb4 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/projects/page.tsx @@ -0,0 +1,22 @@ +import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout'; +import { getExists } from '@/server/pageExists'; +import { getProjectsByOrganizationSlug } from '@openpanel/db'; + +import ListProjects from './list-projects'; + +interface PageProps { + params: { + organizationId: string; + }; +} + +export default async function Page({ params: { organizationId } }: PageProps) { + await getExists(organizationId); + const projects = await getProjectsByOrganizationSlug(organizationId); + + return ( + + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/references/list-references.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/references/list-references.tsx new file mode 100644 index 00000000..d4270a29 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/references/list-references.tsx @@ -0,0 +1,32 @@ +'use client'; + +import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header'; +import { DataTable } from '@/components/DataTable'; +import { columns } from '@/components/references/table'; +import { Button } from '@/components/ui/button'; +import { pushModal } from '@/modals'; +import type { IServiceReference } from '@openpanel/db'; +import { PlusIcon } from 'lucide-react'; + +interface ListProjectsProps { + data: IServiceReference[]; +} + +export default function ListReferences({ data }: ListProjectsProps) { + return ( + <> + +
+
+ +
+ +
+ +
+ + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/references/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/references/page.tsx new file mode 100644 index 00000000..ca5e8c01 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/settings/references/page.tsx @@ -0,0 +1,31 @@ +import PageLayout from '@/app/(app)/[organizationId]/[projectId]/page-layout'; +import { getExists } from '@/server/pageExists'; +import { getReferences } from '@openpanel/db'; + +import ListReferences from './list-references'; + +interface PageProps { + params: { + organizationId: string; + projectId: string; + }; +} + +export default async function Page({ + params: { organizationId, projectId }, +}: PageProps) { + await getExists(organizationId, projectId); + const references = await getReferences({ + where: { + project_id: projectId, + }, + take: 50, + skip: 0, + }); + + return ( + + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/test/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/test/page.tsx new file mode 100644 index 00000000..d03b06c1 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/[projectId]/test/page.tsx @@ -0,0 +1,21 @@ +import { Funnel } from '@/components/report/funnel'; + +import PageLayout from '../page-layout'; + +export const metadata = { + title: 'Funnel - Openpanel.dev', +}; + +interface PageProps { + params: { + organizationId: string; + }; +} + +export default function Page({ params: { organizationId } }: PageProps) { + return ( + + + + ); +} diff --git a/apps/dashboard/src/app/(app)/[organizationId]/create-project.tsx b/apps/dashboard/src/app/(app)/[organizationId]/create-project.tsx new file mode 100644 index 00000000..59c132a8 --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/create-project.tsx @@ -0,0 +1,113 @@ +'use client'; + +import { LogoSquare } from '@/components/Logo'; +import { Button } from '@/components/ui/button'; +import { Checkbox } from '@/components/ui/checkbox'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { useAppParams } from '@/hooks/useAppParams'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { SaveIcon } from 'lucide-react'; +import { useRouter } from 'next/navigation'; +import type { SubmitHandler } from 'react-hook-form'; +import { useForm } from 'react-hook-form'; +import { toast } from 'sonner'; +import { z } from 'zod'; + +import { api, handleError } from '../../_trpc/client'; + +const validation = z.object({ + name: z.string().min(1), +}); + +type IForm = z.infer; + +export function CreateProject() { + const params = useAppParams(); + const router = useRouter(); + const form = useForm({ + resolver: zodResolver(validation), + }); + const mutation = api.project.create.useMutation({ + onError: handleError, + onSuccess() { + toast.success('Project created'); + router.refresh(); + }, + }); + const onSubmit: SubmitHandler = (values) => { + mutation.mutate({ + name: values.name, + organizationId: params.organizationId, + }); + }; + + return ( + <> +
+ +

Create your first project

+
+ A project is just a container for your events. You can create as many + as you want. +
+
+
+ + +
+
+ +
+
+
+ + ); +} + +//
+//
+// Select your framework and we'll generate a client for you. +//
+//
+// +// +// +// +// +// +//
+//
diff --git a/apps/dashboard/src/app/(app)/[organizationId]/page.tsx b/apps/dashboard/src/app/(app)/[organizationId]/page.tsx new file mode 100644 index 00000000..1b1b08ba --- /dev/null +++ b/apps/dashboard/src/app/(app)/[organizationId]/page.tsx @@ -0,0 +1,64 @@ +import { LogoSquare } from '@/components/Logo'; +import { ProjectCard } from '@/components/projects/project-card'; +import { + getOrganizationBySlug, + getProjectsByOrganizationSlug, +} from '@openpanel/db'; +import { notFound, redirect } from 'next/navigation'; + +import { CreateProject } from './create-project'; + +interface PageProps { + params: { + organizationId: string; + }; +} + +export default async function Page({ params: { organizationId } }: PageProps) { + const [organization, projects] = await Promise.all([ + getOrganizationBySlug(organizationId), + getProjectsByOrganizationSlug(organizationId), + ]); + + if (!organization) { + return notFound(); + } + + if (process.env.BLOCK) { + return ( +
+
+ +

Not quite there yet

+
+ We're still working on Openpanel, but we're not quite there yet. + We'll let you know when we're ready to go! +
+
+
+ ); + } + + if (projects.length === 0) { + return ( +
+
+ +
+
+ ); + } + + if (projects.length === 1 && projects[0]) { + return redirect(`/${organizationId}/${projects[0].id}`); + } + + return ( +
+

Select project

+ {projects.map((item) => ( + + ))} +
+ ); +} diff --git a/apps/dashboard/src/app/(app)/create-organization.tsx b/apps/dashboard/src/app/(app)/create-organization.tsx new file mode 100644 index 00000000..75503829 --- /dev/null +++ b/apps/dashboard/src/app/(app)/create-organization.tsx @@ -0,0 +1,86 @@ +'use client'; + +import { LogoSquare } from '@/components/Logo'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { SaveIcon } from 'lucide-react'; +import { useRouter } from 'next/navigation'; +import type { SubmitHandler } from 'react-hook-form'; +import { useForm } from 'react-hook-form'; +import { z } from 'zod'; + +import { api, handleError } from '../_trpc/client'; + +const validation = z.object({ + organization: z.string().min(4), + project: z.string().optional(), +}); + +type IForm = z.infer; + +export function CreateOrganization() { + const router = useRouter(); + const form = useForm({ + resolver: zodResolver(validation), + }); + const mutation = api.onboarding.organziation.useMutation({ + onError: handleError, + onSuccess({ organization, project }) { + let url = `/${organization.slug}`; + if (project) { + url += `/${project.id}`; + } + router.replace(url); + }, + }); + const onSubmit: SubmitHandler = (values) => { + mutation.mutate(values); + }; + return ( + <> +
+ +

Welcome to Openpanel

+
+ Create your organization below (can be personal or a company) and + optionally your first project 🤠 +
+
+
+ + +
+
+ + +
+
+ +
+
+
+ + ); +} diff --git a/apps/dashboard/src/app/(app)/page.tsx b/apps/dashboard/src/app/(app)/page.tsx new file mode 100644 index 00000000..86a03e2b --- /dev/null +++ b/apps/dashboard/src/app/(app)/page.tsx @@ -0,0 +1,38 @@ +// import { CreateOrganization } from '@clerk/nextjs'; + +import { LogoSquare } from '@/components/Logo'; +import { getCurrentOrganizations } from '@openpanel/db'; +import { redirect } from 'next/navigation'; + +import { CreateOrganization } from './create-organization'; + +export default async function Page() { + const organizations = await getCurrentOrganizations(); + + if (process.env.BLOCK) { + return ( +
+
+ +

Not quite there yet

+
+ We're still working on Openpanel, but we're not quite there yet. + We'll let you know when we're ready to go! +
+
+
+ ); + } + + if (organizations.length > 0) { + return redirect(`/${organizations[0]?.slug}`); + } + + return ( +
+
+ +
+
+ ); +} diff --git a/apps/dashboard/src/app/(public)/share/overview/[id]/page.tsx b/apps/dashboard/src/app/(public)/share/overview/[id]/page.tsx new file mode 100644 index 00000000..c875dc85 --- /dev/null +++ b/apps/dashboard/src/app/(public)/share/overview/[id]/page.tsx @@ -0,0 +1,73 @@ +import { StickyBelowHeader } from '@/app/(app)/[organizationId]/[projectId]/layout-sticky-below-header'; +import { OverviewReportRange } from '@/app/(app)/[organizationId]/[projectId]/overview-sticky-header'; +import { Logo } from '@/components/Logo'; +import { OverviewFiltersButtons } from '@/components/overview/filters/overview-filters-buttons'; +import { OverviewFiltersDrawer } from '@/components/overview/filters/overview-filters-drawer'; +import ServerLiveCounter from '@/components/overview/live-counter'; +import { OverviewLiveHistogram } from '@/components/overview/overview-live-histogram'; +import OverviewMetrics from '@/components/overview/overview-metrics'; +import OverviewTopDevices from '@/components/overview/overview-top-devices'; +import OverviewTopEvents from '@/components/overview/overview-top-events'; +import OverviewTopGeo from '@/components/overview/overview-top-geo'; +import OverviewTopPages from '@/components/overview/overview-top-pages'; +import OverviewTopSources from '@/components/overview/overview-top-sources'; +import { getOrganizationBySlug, getShareOverviewById } from '@openpanel/db'; +import { notFound } from 'next/navigation'; + +interface PageProps { + params: { + id: string; + }; +} + +export default async function Page({ params: { id } }: PageProps) { + const share = await getShareOverviewById(id); + if (!share) { + return notFound(); + } + const projectId = share.project_id; + const organization = await getOrganizationBySlug(share.organization_slug); + + return ( +
+
+
+
+ {organization?.name} +

+ {share.project?.name} +

+
+ + + +
+
+ +
+
+ + {/* */} +
+
+ +
+
+ +
+
+
+ +
+ + + + + + +
+
+
+
+ ); +} diff --git a/apps/dashboard/src/app/_trpc/client.tsx b/apps/dashboard/src/app/_trpc/client.tsx new file mode 100644 index 00000000..83d94d8c --- /dev/null +++ b/apps/dashboard/src/app/_trpc/client.tsx @@ -0,0 +1,39 @@ +import type { AppRouter } from '@/server/api/root'; +import type { TRPCClientErrorBase } from '@trpc/react-query'; +import { createTRPCReact } from '@trpc/react-query'; +import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server'; +import type { ExternalToast } from 'sonner'; +import { toast } from 'sonner'; + +export const api = createTRPCReact({}); + +/** + * Inference helper for inputs. + * + * @example type HelloInput = RouterInputs['example']['hello'] + */ +export type RouterInputs = inferRouterInputs; + +/** + * Inference helper for outputs. + * + * @example type HelloOutput = RouterOutputs['example']['hello'] + */ +export type RouterOutputs = inferRouterOutputs; +export type IChartData = RouterOutputs['chart']['chart']; +export type IChartSerieDataItem = IChartData['series'][number]['data'][number]; + +export function handleError(error: TRPCClientErrorBase) { + toast('Error', { + description: error.message, + }); +} + +export function handleErrorToastOptions(options: ExternalToast) { + return function (error: TRPCClientErrorBase) { + toast('Error', { + description: error.message, + ...options, + }); + }; +} diff --git a/apps/dashboard/src/app/api/trpc/[trpc]/route.ts b/apps/dashboard/src/app/api/trpc/[trpc]/route.ts new file mode 100644 index 00000000..ca979c6e --- /dev/null +++ b/apps/dashboard/src/app/api/trpc/[trpc]/route.ts @@ -0,0 +1,25 @@ +import { appRouter } from '@/server/api/root'; +import { getAuth } from '@clerk/nextjs/server'; +import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; + +const handler = (req: Request) => + fetchRequestHandler({ + endpoint: '/api/trpc', + req, + router: appRouter, + async createContext({ req }) { + const session = getAuth(req as any); + return { + session, + }; + }, + onError(opts) { + const { error, type, path, input, ctx, req } = opts; + console.error('---- TRPC ERROR'); + console.error('Error:', error); + console.error('Context:', ctx); + console.error(); + }, + }); + +export { handler as GET, handler as POST }; diff --git a/apps/dashboard/src/app/auth.tsx b/apps/dashboard/src/app/auth.tsx new file mode 100644 index 00000000..d73c4909 --- /dev/null +++ b/apps/dashboard/src/app/auth.tsx @@ -0,0 +1,87 @@ +'use client'; + +import { useState } from 'react'; +import { InputWithLabel } from '@/components/forms/InputWithLabel'; +import { Logo } from '@/components/Logo'; +import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; +import { Button } from '@/components/ui/button'; +import { Widget, WidgetBody } from '@/components/Widget'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { KeySquareIcon } from 'lucide-react'; +import { signIn } from 'next-auth/react'; +import Link from 'next/link'; +import { usePathname, useRouter } from 'next/navigation'; +import { useForm } from 'react-hook-form'; +import { z } from 'zod'; + +const validator = z.object({ + email: z.string().email(), + password: z.string().min(6), +}); + +type IForm = z.infer; +export default function Auth() { + const form = useForm({ + resolver: zodResolver(validator), + }); + const router = useRouter(); + const pathname = usePathname(); + const [state, setState] = useState(null); + return ( +
+ + +
+ +
+
{ + const res = await signIn('credentials', { + email: values.email, + password: values.password, + redirect: false, + }).catch(() => { + setState('Something went wrong. Please try again later'); + }); + + if (res?.ok) { + router.refresh(); + } + + if (res?.status === 401) { + setState('Wrong email or password. Please try again'); + } + })} + className="flex flex-col gap-4" + > + + + {state !== null && ( + + + Failed + {state} + + )} + + + No account?{' '} + Sign up here! + + +
+
+

Terms & conditions

+
+ ); +} diff --git a/apps/dashboard/src/app/layout.tsx b/apps/dashboard/src/app/layout.tsx new file mode 100644 index 00000000..65f850ad --- /dev/null +++ b/apps/dashboard/src/app/layout.tsx @@ -0,0 +1,33 @@ +import { cn } from '@/utils/cn'; + +import Providers from './providers'; + +import '@/styles/globals.css'; +import '/node_modules/flag-icons/css/flag-icons.min.css'; + +export const metadata = { + title: 'Overview - Openpanel.dev', +}; + +export const viewport = { + width: 'device-width', + initialScale: 1, + maximumScale: 1, + userScalable: 1, +}; + +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( + + + {children} + + + ); +} diff --git a/apps/dashboard/src/app/manifest.ts b/apps/dashboard/src/app/manifest.ts new file mode 100644 index 00000000..4fb65d4c --- /dev/null +++ b/apps/dashboard/src/app/manifest.ts @@ -0,0 +1,20 @@ +import type { MetadataRoute } from 'next'; + +export default function manifest(): MetadataRoute.Manifest { + return { + name: 'Openpanel.dev', + short_name: 'Openpanel.dev', + description: '', + start_url: '/', + display: 'standalone', + background_color: '#fff', + theme_color: '#fff', + icons: [ + { + src: 'https://openpanel.dev/favicon.ico', + sizes: 'any', + type: 'image/x-icon', + }, + ], + }; +} diff --git a/apps/dashboard/src/app/providers.tsx b/apps/dashboard/src/app/providers.tsx new file mode 100644 index 00000000..562215ef --- /dev/null +++ b/apps/dashboard/src/app/providers.tsx @@ -0,0 +1,71 @@ +'use client'; + +import React, { useRef, useState } from 'react'; +import { api } from '@/app/_trpc/client'; +import { TooltipProvider } from '@/components/ui/tooltip'; +import { ModalProvider } from '@/modals'; +import type { AppStore } from '@/redux'; +import makeStore from '@/redux'; +import { ClerkProvider, useAuth } from '@clerk/nextjs'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { httpLink } from '@trpc/client'; +import { Provider as ReduxProvider } from 'react-redux'; +import { Toaster } from 'sonner'; +import superjson from 'superjson'; + +function AllProviders({ children }: { children: React.ReactNode }) { + const { getToken } = useAuth(); + const [queryClient] = useState( + () => + new QueryClient({ + defaultOptions: { + queries: { + networkMode: 'always', + refetchOnMount: true, + refetchOnWindowFocus: false, + }, + }, + }) + ); + const [trpcClient] = useState(() => + api.createClient({ + transformer: superjson, + links: [ + httpLink({ + url: `${process.env.NEXT_PUBLIC_DASHBOARD_URL}/api/trpc`, + async headers() { + return { Authorization: `Bearer ${await getToken()}` }; + }, + }), + ], + }) + ); + + const storeRef = useRef(); + if (!storeRef.current) { + // Create the store instance the first time this renders + storeRef.current = makeStore(); + } + + return ( + + + + + {children} + + + + + + + ); +} + +export default function Providers({ children }: { children: React.ReactNode }) { + return ( + + {children} + + ); +} diff --git a/apps/web/src/components/AutoSizer.tsx b/apps/dashboard/src/components/AutoSizer.tsx similarity index 100% rename from apps/web/src/components/AutoSizer.tsx rename to apps/dashboard/src/components/AutoSizer.tsx diff --git a/apps/web/src/components/ButtonContainer.tsx b/apps/dashboard/src/components/ButtonContainer.tsx similarity index 100% rename from apps/web/src/components/ButtonContainer.tsx rename to apps/dashboard/src/components/ButtonContainer.tsx diff --git a/apps/web/src/components/Card.tsx b/apps/dashboard/src/components/Card.tsx similarity index 90% rename from apps/web/src/components/Card.tsx rename to apps/dashboard/src/components/Card.tsx index f4ce4090..ad3763a5 100644 --- a/apps/web/src/components/Card.tsx +++ b/apps/dashboard/src/components/Card.tsx @@ -1,3 +1,5 @@ +'use client'; + import { DropdownMenu, DropdownMenuContent, @@ -17,8 +19,8 @@ export function Card({ children, hover, className }: CardProps) { return (
diff --git a/apps/web/src/components/ColorSquare.tsx b/apps/dashboard/src/components/ColorSquare.tsx similarity index 77% rename from apps/web/src/components/ColorSquare.tsx rename to apps/dashboard/src/components/ColorSquare.tsx index e0015dab..52f79340 100644 --- a/apps/web/src/components/ColorSquare.tsx +++ b/apps/dashboard/src/components/ColorSquare.tsx @@ -1,9 +1,15 @@ import type { HtmlProps } from '@/types'; import { cn } from '@/utils/cn'; +import { useChartContext } from './report/chart/ChartProvider'; + type ColorSquareProps = HtmlProps; export function ColorSquare({ children, className }: ColorSquareProps) { + const { hideID } = useChartContext(); + if (hideID) { + return null; + } return (
+
+
+ +
+ +

{title}

+ + {children} +
+
+ ); +} diff --git a/apps/dashboard/src/components/Logo.tsx b/apps/dashboard/src/components/Logo.tsx new file mode 100644 index 00000000..590ee1e3 --- /dev/null +++ b/apps/dashboard/src/components/Logo.tsx @@ -0,0 +1,26 @@ +import { cn } from '@/utils/cn'; + +interface LogoProps { + className?: string; +} + +export function LogoSquare({ className }: LogoProps) { + return ( + Openpanel logo + ); +} + +export function Logo({ className }: LogoProps) { + return ( +
+ + openpanel.dev +
+ ); +} diff --git a/apps/web/src/components/PageTitle.tsx b/apps/dashboard/src/components/PageTitle.tsx similarity index 100% rename from apps/web/src/components/PageTitle.tsx rename to apps/dashboard/src/components/PageTitle.tsx diff --git a/apps/dashboard/src/components/Pagination.tsx b/apps/dashboard/src/components/Pagination.tsx new file mode 100644 index 00000000..e5ecab97 --- /dev/null +++ b/apps/dashboard/src/components/Pagination.tsx @@ -0,0 +1,57 @@ +import type { Dispatch, SetStateAction } from 'react'; +import { useState } from 'react'; + +import { Button } from './ui/button'; + +export function usePagination(take: number) { + const [page, setPage] = useState(0); + return { + take, + skip: page * take, + setPage, + page, + paginate: (data: T[]): T[] => + data.slice(page * take, (page + 1) * take), + }; +} + +export function Pagination({ + take, + count, + cursor, + setCursor, +}: { + take?: number; + count?: number; + cursor: number; + setCursor: Dispatch>; +}) { + const isNextDisabled = + count !== undefined && take !== undefined && cursor * take + take >= count; + + return ( +
+
Page: {cursor + 1}
+ {typeof count === 'number' && ( +
Total rows: {count}
+ )} + + + +
+ ); +} diff --git a/apps/web/src/components/Syntax.tsx b/apps/dashboard/src/components/Syntax.tsx similarity index 97% rename from apps/web/src/components/Syntax.tsx rename to apps/dashboard/src/components/Syntax.tsx index 347df66b..d12814a1 100644 --- a/apps/web/src/components/Syntax.tsx +++ b/apps/dashboard/src/components/Syntax.tsx @@ -1,3 +1,5 @@ +'use client'; + import { Light as SyntaxHighlighter } from 'react-syntax-highlighter'; import ts from 'react-syntax-highlighter/dist/cjs/languages/hljs/typescript'; import docco from 'react-syntax-highlighter/dist/cjs/styles/hljs/docco'; diff --git a/apps/dashboard/src/components/Widget.tsx b/apps/dashboard/src/components/Widget.tsx new file mode 100644 index 00000000..41ecc8dd --- /dev/null +++ b/apps/dashboard/src/components/Widget.tsx @@ -0,0 +1,34 @@ +import { cn } from '@/utils/cn'; + +export interface WidgetHeadProps { + children: React.ReactNode; + className?: string; +} +export function WidgetHead({ children, className }: WidgetHeadProps) { + return ( +
+ {children} +
+ ); +} + +export interface WidgetBodyProps { + children: React.ReactNode; + className?: string; +} +export function WidgetBody({ children, className }: WidgetBodyProps) { + return
{children}
; +} + +export interface WidgetProps { + children: React.ReactNode; + className?: string; +} +export function Widget({ children, className }: WidgetProps) { + return
{children}
; +} diff --git a/apps/web/src/components/WithSidebar.tsx b/apps/dashboard/src/components/WithSidebar.tsx similarity index 100% rename from apps/web/src/components/WithSidebar.tsx rename to apps/dashboard/src/components/WithSidebar.tsx diff --git a/apps/dashboard/src/components/chart-ssr.tsx b/apps/dashboard/src/components/chart-ssr.tsx new file mode 100644 index 00000000..c84833e2 --- /dev/null +++ b/apps/dashboard/src/components/chart-ssr.tsx @@ -0,0 +1,68 @@ +import * as d3 from 'd3'; + +export function ChartSSR({ + data, + dots = false, +}: { + dots?: boolean; + data: { value: number; date: Date }[]; +}) { + const xScale = d3 + .scaleTime() + .domain([data[0]!.date, data[data.length - 1]!.date]) + .range([0, 100]); + const yScale = d3 + .scaleLinear() + .domain([0, d3.max(data.map((d) => d.value)) ?? 0]) + .range([100, 0]); + + const line = d3 + .line<(typeof data)[number]>() + .curve(d3.curveMonotoneX) + .x((d) => xScale(d.date)) + .y((d) => yScale(d.value)); + + const d = line(data); + + if (!d) { + return null; + } + + return ( +
+ {/* Chart area */} + + + {/* Line */} + + + {/* Circles */} + {dots && + data.map((d) => ( + + ))} + + +
+ ); +} diff --git a/apps/web/src/components/clients/ClientActions.tsx b/apps/dashboard/src/components/clients/ClientActions.tsx similarity index 80% rename from apps/web/src/components/clients/ClientActions.tsx rename to apps/dashboard/src/components/clients/ClientActions.tsx index 3198ec01..20c1f38e 100644 --- a/apps/web/src/components/clients/ClientActions.tsx +++ b/apps/dashboard/src/components/clients/ClientActions.tsx @@ -1,9 +1,12 @@ -import { useRefetchActive } from '@/hooks/useRefetchActive'; +'use client'; + +import { api } from '@/app/_trpc/client'; import { pushModal, showConfirm } from '@/modals'; -import type { IClientWithProject } from '@/types'; -import { api } from '@/utils/api'; import { clipboard } from '@/utils/clipboard'; +import type { IServiceClientWithProject } from '@openpanel/db'; import { MoreHorizontal } from 'lucide-react'; +import { useRouter } from 'next/navigation'; +import { toast } from 'sonner'; import { Button } from '../ui/button'; import { @@ -14,17 +17,16 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from '../ui/dropdown-menu'; -import { toast } from '../ui/use-toast'; -export function ClientActions({ id }: IClientWithProject) { - const refetch = useRefetchActive(); +export function ClientActions(client: IServiceClientWithProject) { + const { id } = client; + const router = useRouter(); const deletion = api.client.remove.useMutation({ onSuccess() { - toast({ - title: 'Success', + toast('Success', { description: 'Client revoked, incoming requests will be rejected.', }); - refetch(); + router.refresh(); }, }); return ( @@ -42,7 +44,7 @@ export function ClientActions({ id }: IClientWithProject) { { - pushModal('EditClient', { id }); + pushModal('EditClient', client); }} > Edit diff --git a/apps/web/src/components/clients/table.tsx b/apps/dashboard/src/components/clients/table.tsx similarity index 88% rename from apps/web/src/components/clients/table.tsx rename to apps/dashboard/src/components/clients/table.tsx index b6b45453..86d2ffce 100644 --- a/apps/web/src/components/clients/table.tsx +++ b/apps/dashboard/src/components/clients/table.tsx @@ -1,10 +1,10 @@ -import type { IClientWithProject } from '@/types'; import { formatDate } from '@/utils/date'; +import type { IServiceClientWithProject } from '@openpanel/db'; import type { ColumnDef } from '@tanstack/react-table'; import { ClientActions } from './ClientActions'; -export const columns: ColumnDef[] = [ +export const columns: ColumnDef[] = [ { accessorKey: 'name', header: 'Name', diff --git a/apps/dashboard/src/components/events/ListProperties.tsx b/apps/dashboard/src/components/events/ListProperties.tsx new file mode 100644 index 00000000..93aa80eb --- /dev/null +++ b/apps/dashboard/src/components/events/ListProperties.tsx @@ -0,0 +1,35 @@ +import { toDots } from '@openpanel/common'; + +import { Table, TableBody, TableCell, TableRow } from '../ui/table'; + +interface ListPropertiesProps { + data: any; + className?: string; +} + +export function ListProperties({ + data, + className = 'mini', +}: ListPropertiesProps) { + const dots = toDots(data); + return ( + + + {Object.keys(dots).map((key) => { + return ( + + {key} + + {typeof dots[key] === 'boolean' + ? dots[key] + ? 'true' + : 'false' + : dots[key]} + + + ); + })} + +
+ ); +} diff --git a/apps/web/src/components/forms/InputError.tsx b/apps/dashboard/src/components/forms/InputError.tsx similarity index 100% rename from apps/web/src/components/forms/InputError.tsx rename to apps/dashboard/src/components/forms/InputError.tsx diff --git a/apps/web/src/components/forms/InputWithLabel.tsx b/apps/dashboard/src/components/forms/InputWithLabel.tsx similarity index 59% rename from apps/web/src/components/forms/InputWithLabel.tsx rename to apps/dashboard/src/components/forms/InputWithLabel.tsx index 47df69df..32fbbdb1 100644 --- a/apps/web/src/components/forms/InputWithLabel.tsx +++ b/apps/dashboard/src/components/forms/InputWithLabel.tsx @@ -6,15 +6,23 @@ import { Label } from '../ui/label'; type InputWithLabelProps = InputProps & { label: string; + error?: string | undefined; }; export const InputWithLabel = forwardRef( ({ label, className, ...props }, ref) => { return (
- +
+ + {props.error && ( + + {props.error} + + )} +
); diff --git a/apps/dashboard/src/components/general/ExpandableListItem.tsx b/apps/dashboard/src/components/general/ExpandableListItem.tsx new file mode 100644 index 00000000..7b0b3ade --- /dev/null +++ b/apps/dashboard/src/components/general/ExpandableListItem.tsx @@ -0,0 +1,57 @@ +import React, { useState } from 'react'; +import { cn } from '@/utils/cn'; +import { ChevronUp } from 'lucide-react'; +import AnimateHeight from 'react-animate-height'; + +import { Button } from '../ui/button'; + +interface ExpandableListItemProps { + children: React.ReactNode; + content: React.ReactNode; + title: React.ReactNode; + image?: React.ReactNode; + initialOpen?: boolean; + className?: string; +} +export function ExpandableListItem({ + title, + content, + image, + initialOpen = false, + children, + className, +}: ExpandableListItemProps) { + const [open, setOpen] = useState(initialOpen ?? false); + return ( +
+
+
{image}
+
+
{title}
+ {!!content && ( +
+ {content} +
+ )} +
+ +
+ +
{children}
+
+
+ ); +} diff --git a/apps/dashboard/src/components/overview/filters/overview-filters-buttons.tsx b/apps/dashboard/src/components/overview/filters/overview-filters-buttons.tsx new file mode 100644 index 00000000..2a7a3460 --- /dev/null +++ b/apps/dashboard/src/components/overview/filters/overview-filters-buttons.tsx @@ -0,0 +1,57 @@ +'use client'; + +import { Button } from '@/components/ui/button'; +import { + useEventQueryFilters, + useEventQueryNamesFilter, +} from '@/hooks/useEventQueryFilters'; +import { cn } from '@/utils/cn'; +import { X } from 'lucide-react'; +import type { Options as NuqsOptions } from 'nuqs'; + +interface OverviewFiltersButtonsProps { + className?: string; + nuqsOptions?: NuqsOptions; +} + +export function OverviewFiltersButtons({ + className, + nuqsOptions, +}: OverviewFiltersButtonsProps) { + const [events, setEvents] = useEventQueryNamesFilter(nuqsOptions); + const [filters, setFilter] = useEventQueryFilters(nuqsOptions); + if (filters.length === 0 && events.length === 0) return null; + return ( +
+ {events.map((event) => ( + + ))} + {filters.map((filter) => { + if (!filter.value[0]) { + return null; + } + + return ( + + ); + })} +
+ ); +} diff --git a/apps/dashboard/src/components/overview/filters/overview-filters-drawer-content.tsx b/apps/dashboard/src/components/overview/filters/overview-filters-drawer-content.tsx new file mode 100644 index 00000000..9f2a8c80 --- /dev/null +++ b/apps/dashboard/src/components/overview/filters/overview-filters-drawer-content.tsx @@ -0,0 +1,185 @@ +import { Button } from '@/components/ui/button'; +import { Combobox } from '@/components/ui/combobox'; +import { ComboboxAdvanced } from '@/components/ui/combobox-advanced'; +import { SheetHeader, SheetTitle } from '@/components/ui/sheet'; +import { useEventNames } from '@/hooks/useEventNames'; +import { useEventProperties } from '@/hooks/useEventProperties'; +import { + useEventQueryFilters, + useEventQueryNamesFilter, +} from '@/hooks/useEventQueryFilters'; +import { useEventValues } from '@/hooks/useEventValues'; +import { useProfileProperties } from '@/hooks/useProfileProperties'; +import { useProfileValues } from '@/hooks/useProfileValues'; +import type { + IChartEventFilter, + IChartEventFilterOperator, + IChartEventFilterValue, +} from '@openpanel/validation'; +import { XIcon } from 'lucide-react'; +import type { Options as NuqsOptions } from 'nuqs'; + +export interface OverviewFiltersDrawerContentProps { + projectId: string; + nuqsOptions?: NuqsOptions; + enableEventsFilter?: boolean; + mode: 'profiles' | 'events'; +} + +export function OverviewFiltersDrawerContent({ + projectId, + nuqsOptions, + enableEventsFilter, + mode, +}: OverviewFiltersDrawerContentProps) { + const [filters, setFilter] = useEventQueryFilters(nuqsOptions); + const [event, setEvent] = useEventQueryNamesFilter(nuqsOptions); + const eventNames = useEventNames(projectId); + const eventProperties = useEventProperties(projectId); + const profileProperties = useProfileProperties(projectId); + const properties = mode === 'events' ? eventProperties : profileProperties; + + return ( +
+ + Overview filters + + +
+ {enableEventsFilter && ( + ({ + label: item.name, + value: item.name, + }))} + placeholder="Select event" + /> + )} + { + setFilter(value, ''); + }} + value="" + placeholder="Filter by property" + label="What do you want to filter by?" + items={properties.map((item) => ({ + label: item, + value: item, + }))} + searchable + /> +
+ +
+ {filters + .filter((filter) => filter.value[0] !== null) + .map((filter) => { + return mode === 'events' ? ( + + ) : ( + + ); + })} +
+
+ ); +} + +export function FilterOptionEvent({ + setFilter, + projectId, + ...filter +}: IChartEventFilter & { + projectId: string; + setFilter: ( + name: string, + value: IChartEventFilterValue, + operator: IChartEventFilterOperator + ) => void; +}) { + const values = useEventValues( + projectId, + filter.name === 'path' ? 'screen_view' : 'session_start', + filter.name + ); + + return ( +
+
{filter.name}
+ setFilter(filter.name, value, filter.operator)} + placeholder={'Select a value'} + items={values.map((value) => ({ + value, + label: value, + }))} + value={String(filter.value[0] ?? '')} + /> + +
+ ); +} + +export function FilterOptionProfile({ + setFilter, + projectId, + ...filter +}: IChartEventFilter & { + projectId: string; + setFilter: ( + name: string, + value: IChartEventFilterValue, + operator: IChartEventFilterOperator + ) => void; +}) { + const values = useProfileValues(projectId, filter.name); + + return ( +
+
{filter.name}
+ setFilter(filter.name, value, filter.operator)} + placeholder={'Select a value'} + items={values.map((value) => ({ + value, + label: value, + }))} + value={String(filter.value[0] ?? '')} + /> + +
+ ); +} diff --git a/apps/dashboard/src/components/overview/filters/overview-filters-drawer.tsx b/apps/dashboard/src/components/overview/filters/overview-filters-drawer.tsx new file mode 100644 index 00000000..5a3d8842 --- /dev/null +++ b/apps/dashboard/src/components/overview/filters/overview-filters-drawer.tsx @@ -0,0 +1,25 @@ +'use client'; + +import { Button } from '@/components/ui/button'; +import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet'; +import { FilterIcon } from 'lucide-react'; + +import type { OverviewFiltersDrawerContentProps } from './overview-filters-drawer-content'; +import { OverviewFiltersDrawerContent } from './overview-filters-drawer-content'; + +export function OverviewFiltersDrawer( + props: OverviewFiltersDrawerContentProps +) { + return ( + + + + + + + + + ); +} diff --git a/apps/dashboard/src/components/overview/live-counter/index.tsx b/apps/dashboard/src/components/overview/live-counter/index.tsx new file mode 100644 index 00000000..2eddb6af --- /dev/null +++ b/apps/dashboard/src/components/overview/live-counter/index.tsx @@ -0,0 +1,11 @@ +import { getLiveVisitors } from '@openpanel/db'; + +import type { LiveCounterProps } from './live-counter'; +import LiveCounter from './live-counter'; + +export default async function ServerLiveCounter( + props: Omit +) { + const count = await getLiveVisitors(props.projectId); + return ; +} diff --git a/apps/dashboard/src/components/overview/live-counter/live-counter.tsx b/apps/dashboard/src/components/overview/live-counter/live-counter.tsx new file mode 100644 index 00000000..2b5c1cf8 --- /dev/null +++ b/apps/dashboard/src/components/overview/live-counter/live-counter.tsx @@ -0,0 +1,97 @@ +'use client'; + +import { useRef, useState } from 'react'; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from '@/components/ui/tooltip'; +import { cn } from '@/utils/cn'; +import { useQueryClient } from '@tanstack/react-query'; +import dynamic from 'next/dynamic'; +import useWebSocket from 'react-use-websocket'; +import { toast } from 'sonner'; + +import { useOverviewOptions } from '../useOverviewOptions'; + +export interface LiveCounterProps { + data: number; + projectId: string; +} + +const AnimatedNumbers = dynamic(() => import('react-animated-numbers'), { + ssr: false, + loading: () =>
0
, +}); + +const FIFTEEN_SECONDS = 1000 * 15; + +export default function LiveCounter({ data = 0, projectId }: LiveCounterProps) { + const { setLiveHistogram } = useOverviewOptions(); + const ws = String(process.env.NEXT_PUBLIC_API_URL) + .replace(/^https/, 'wss') + .replace(/^http/, 'ws'); + const client = useQueryClient(); + const [counter, setCounter] = useState(data); + const [socketUrl] = useState(`${ws}/live/visitors/${projectId}`); + const lastRefresh = useRef(Date.now()); + + useWebSocket(socketUrl, { + shouldReconnect: () => true, + onMessage(event) { + const value = parseInt(event.data, 10); + if (!isNaN(value)) { + setCounter(value); + if (Date.now() - lastRefresh.current > FIFTEEN_SECONDS) { + lastRefresh.current = Date.now(); + toast('Refreshed data'); + client.refetchQueries({ + type: 'active', + }); + } + } + }, + }); + + return ( + + + + + +

{counter} unique visitors last 5 minutes

+

Click to see activity for the last 30 minutes

+
+
+ ); +} diff --git a/apps/dashboard/src/components/overview/overview-latest-events/index.tsx b/apps/dashboard/src/components/overview/overview-latest-events/index.tsx new file mode 100644 index 00000000..c3540a2e --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-latest-events/index.tsx @@ -0,0 +1,16 @@ +import { getConversionEventNames } from '@openpanel/db'; + +import type { OverviewLatestEventsProps } from './overview-latest-events'; +import OverviewLatestEvents from './overview-latest-events'; + +export default async function OverviewLatestEventsServer({ + projectId, +}: Omit) { + const eventNames = await getConversionEventNames(projectId); + return ( + item.name)} + /> + ); +} diff --git a/apps/dashboard/src/components/overview/overview-latest-events/overview-latest-events.tsx b/apps/dashboard/src/components/overview/overview-latest-events/overview-latest-events.tsx new file mode 100644 index 00000000..b3d9f5cb --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-latest-events/overview-latest-events.tsx @@ -0,0 +1,128 @@ +'use client'; + +import { ChartSwitch } from '@/components/report/chart'; +import { useEventQueryFilters } from '@/hooks/useEventQueryFilters'; +import { cn } from '@/utils/cn'; + +import { Widget, WidgetBody } from '../../Widget'; +import { WidgetButtons, WidgetHead } from '../overview-widget'; +import { useOverviewOptions } from '../useOverviewOptions'; +import { useOverviewWidget } from '../useOverviewWidget'; + +export interface OverviewLatestEventsProps { + projectId: string; + conversions: string[]; +} +export default function OverviewLatestEvents({ + projectId, + conversions, +}: OverviewLatestEventsProps) { + const { interval, range, previous, startDate, endDate } = + useOverviewOptions(); + const [filters] = useEventQueryFilters(); + const [widget, setWidget, widgets] = useOverviewWidget('ev', { + all: { + title: 'Top events', + btn: 'All', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters: [ + ...filters, + { + id: 'ex_session', + name: 'name', + operator: 'isNot', + value: ['session_start', 'session_end'], + }, + ], + id: 'A', + name: '*', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'name', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + conversions: { + title: 'Conversions', + btn: 'Conversions', + hide: conversions.length === 0, + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters: [ + ...filters, + { + id: 'conversion', + name: 'name', + operator: 'is', + value: conversions, + }, + ], + id: 'A', + name: '*', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'name', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + }); + + return ( + <> + + +
{widget.title}
+ + {widgets + .filter((item) => item.hide !== true) + .map((w) => ( + + ))} + +
+ + + +
+ + ); +} diff --git a/apps/dashboard/src/components/overview/overview-live-histogram.tsx b/apps/dashboard/src/components/overview/overview-live-histogram.tsx new file mode 100644 index 00000000..a436aac8 --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-live-histogram.tsx @@ -0,0 +1,157 @@ +'use client'; + +import { Fragment } from 'react'; +import { api } from '@/app/_trpc/client'; +import { cn } from '@/utils/cn'; +import type { IChartInput } from '@openpanel/validation'; +import { ChevronsUpDownIcon } from 'lucide-react'; +import AnimateHeight from 'react-animate-height'; + +import { redisSub } from '../../../../../packages/redis'; +import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip'; +import { useOverviewOptions } from './useOverviewOptions'; + +interface OverviewLiveHistogramProps { + projectId: string; +} + +export function OverviewLiveHistogram({ + projectId, +}: OverviewLiveHistogramProps) { + const { liveHistogram } = useOverviewOptions(); + const report: IChartInput = { + projectId, + events: [ + { + segment: 'user', + filters: [ + { + id: '1', + name: 'name', + operator: 'is', + value: ['screen_view', 'session_start'], + }, + ], + id: 'A', + name: '*', + displayName: 'Active users', + }, + ], + chartType: 'histogram', + interval: 'minute', + range: '30min', + name: '', + metric: 'sum', + breakdowns: [], + lineType: 'monotone', + previous: false, + }; + const countReport: IChartInput = { + name: '', + projectId, + events: [ + { + segment: 'user', + filters: [], + id: 'A', + name: 'session_start', + }, + ], + breakdowns: [], + chartType: 'metric', + lineType: 'monotone', + interval: 'minute', + range: '30min', + previous: false, + metric: 'sum', + }; + + const res = api.chart.chart.useQuery(report); + const countRes = api.chart.chart.useQuery(countReport); + + const metrics = res.data?.series[0]?.metrics; + const minutes = (res.data?.series[0]?.data || []).slice(-30); + const liveCount = countRes.data?.series[0]?.metrics?.sum ?? 0; + + if (res.isInitialLoading || countRes.isInitialLoading) { + // prettier-ignore + const staticArray = [ + 10, 25, 30, 45, 20, 5, 55, 18, 40, 12, + 50, 35, 8, 22, 38, 42, 15, 28, 52, 5, + 48, 14, 32, 58, 7, 19, 33, 56, 24, 5 + ]; + + return ( + + {staticArray.map((percent, i) => ( +
+ ))} + + ); + } + + if (!res.isSuccess && !countRes.isSuccess) { + return null; + } + + return ( + + {minutes.map((minute) => { + return ( + + +
+ + +
{minute.count} active users
+
@ {new Date(minute.date).toLocaleTimeString()}
+
+ + ); + })} + + ); +} + +interface WrapperProps { + open: boolean; + children: React.ReactNode; + count: number; +} + +function Wrapper({ open, children, count }: WrapperProps) { + return ( + +
+
+
Last 30 minutes
+
+ {count} +
+
+
+
+ NOW +
+ {/*
*/} + {children} +
+
+ + ); +} diff --git a/apps/dashboard/src/components/overview/overview-metrics.tsx b/apps/dashboard/src/components/overview/overview-metrics.tsx new file mode 100644 index 00000000..a1b7b5b5 --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-metrics.tsx @@ -0,0 +1,226 @@ +'use client'; + +import { WidgetHead } from '@/components/overview/overview-widget'; +import { useOverviewOptions } from '@/components/overview/useOverviewOptions'; +import { ChartSwitch } from '@/components/report/chart'; +import { Widget, WidgetBody } from '@/components/Widget'; +import { useEventQueryFilters } from '@/hooks/useEventQueryFilters'; +import { cn } from '@/utils/cn'; +import type { IChartInput } from '@openpanel/validation'; + +interface OverviewMetricsProps { + projectId: string; +} + +export default function OverviewMetrics({ projectId }: OverviewMetricsProps) { + const { previous, range, interval, metric, setMetric, startDate, endDate } = + useOverviewOptions(); + const [filters] = useEventQueryFilters(); + const isPageFilter = filters.find((filter) => filter.name === 'path'); + const reports = [ + { + id: 'Visitors', + projectId, + startDate, + endDate, + events: [ + { + segment: 'user', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + displayName: 'Visitors', + }, + ], + breakdowns: [], + chartType: 'metric', + lineType: 'monotone', + interval, + name: 'Visitors', + range, + previous, + metric: 'sum', + }, + { + id: 'Sessions', + projectId, + startDate, + endDate, + events: [ + { + segment: 'session', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + displayName: 'Sessions', + }, + ], + breakdowns: [], + chartType: 'metric', + lineType: 'monotone', + interval, + name: 'Sessions', + range, + previous, + metric: 'sum', + }, + { + id: 'Pageviews', + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: 'screen_view', + displayName: 'Pageviews', + }, + ], + breakdowns: [], + chartType: 'metric', + lineType: 'monotone', + interval, + name: 'Pageviews', + range, + previous, + metric: 'sum', + }, + { + id: 'Views per session', + projectId, + startDate, + endDate, + events: [ + { + segment: 'user_average', + filters, + id: 'A', + name: 'screen_view', + displayName: 'Views per session', + }, + ], + breakdowns: [], + chartType: 'metric', + lineType: 'monotone', + interval, + name: 'Views per session', + range, + previous, + metric: 'average', + }, + { + id: 'Bounce rate', + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters: [ + { + id: '1', + name: 'properties.__bounce', + operator: 'is', + value: ['true'], + }, + ...filters, + ], + id: 'A', + name: 'session_end', + displayName: 'Bounce rate', + }, + { + segment: 'event', + filters: filters, + id: 'B', + name: 'session_end', + displayName: 'Bounce rate', + }, + ], + breakdowns: [], + chartType: 'metric', + lineType: 'monotone', + interval, + name: 'Bounce rate', + range, + previous, + previousIndicatorInverted: true, + formula: 'A/B*100', + metric: 'average', + unit: '%', + }, + { + id: 'Visit duration', + projectId, + startDate, + endDate, + events: [ + { + segment: 'property_average', + filters: [ + { + name: 'duration', + operator: 'isNot', + value: ['0'], + id: 'A', + }, + ...filters, + ], + id: 'A', + property: 'duration', + name: isPageFilter ? 'screen_view' : 'session_end', + displayName: isPageFilter ? 'Time on page' : 'Visit duration', + }, + ], + breakdowns: [], + chartType: 'metric', + lineType: 'monotone', + interval, + name: 'Visit duration', + range, + previous, + formula: 'A/1000', + metric: 'average', + unit: 'min', + }, + ] satisfies (IChartInput & { id: string })[]; + + const selectedMetric = reports[metric]!; + + return ( + <> +
+ {reports.map((report, index) => ( + + ))} +
+ + +
{selectedMetric.events[0]?.displayName}
+
+ + + +
+ + ); +} diff --git a/apps/dashboard/src/components/overview/overview-share.tsx b/apps/dashboard/src/components/overview/overview-share.tsx new file mode 100644 index 00000000..5d07e022 --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-share.tsx @@ -0,0 +1,75 @@ +'use client'; + +import { api } from '@/app/_trpc/client'; +import { pushModal } from '@/modals'; +import type { ShareOverview } from '@openpanel/db'; +import { EyeIcon, Globe2Icon, LockIcon } from 'lucide-react'; +import Link from 'next/link'; +import { useRouter } from 'next/navigation'; + +import { Button } from '../ui/button'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuTrigger, +} from '../ui/dropdown-menu'; + +interface OverviewShareProps { + data: ShareOverview | null; +} + +export function OverviewShare({ data }: OverviewShareProps) { + const router = useRouter(); + const mutation = api.share.shareOverview.useMutation({ + onSuccess() { + router.refresh(); + }, + }); + + return ( + + + + + + + {(!data || data.public === false) && ( + pushModal('ShareOverviewModal')}> + + Make public + + )} + {data?.public && ( + + + + View + + + )} + {data?.public && ( + { + mutation.mutate({ + public: false, + projectId: data?.project_id, + organizationId: data?.organization_slug, + password: null, + }); + }} + > + + Make private + + )} + + + + ); +} diff --git a/apps/dashboard/src/components/overview/overview-top-devices.tsx b/apps/dashboard/src/components/overview/overview-top-devices.tsx new file mode 100644 index 00000000..04d2cbb1 --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-top-devices.tsx @@ -0,0 +1,221 @@ +'use client'; + +import { ChartSwitch } from '@/components/report/chart'; +import { useEventQueryFilters } from '@/hooks/useEventQueryFilters'; +import { cn } from '@/utils/cn'; + +import { Widget, WidgetBody } from '../Widget'; +import { WidgetButtons, WidgetHead } from './overview-widget'; +import { useOverviewOptions } from './useOverviewOptions'; +import { useOverviewWidget } from './useOverviewWidget'; + +interface OverviewTopDevicesProps { + projectId: string; +} +export default function OverviewTopDevices({ + projectId, +}: OverviewTopDevicesProps) { + const { interval, range, previous, startDate, endDate } = + useOverviewOptions(); + const [filters, setFilter] = useEventQueryFilters(); + const isPageFilter = filters.find((filter) => filter.name === 'path'); + const [widget, setWidget, widgets] = useOverviewWidget('tech', { + devices: { + title: 'Top devices', + btn: 'Devices', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'user', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'device', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + browser: { + title: 'Top browser', + btn: 'Browser', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'user', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'browser', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + browser_version: { + title: 'Top Browser Version', + btn: 'Browser Version', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'user', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'browser_version', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + os: { + title: 'Top OS', + btn: 'OS', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'user', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'os', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + os_version: { + title: 'Top OS version', + btn: 'OS Version', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'user', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'os_version', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + }); + + return ( + <> + + +
{widget.title}
+ + {widgets.map((w) => ( + + ))} + +
+ + { + switch (widget.key) { + case 'devices': + setFilter('device', item.name); + break; + case 'browser': + setFilter('browser', item.name); + break; + case 'browser_version': + setFilter('browser_version', item.name); + break; + case 'os': + setFilter('os', item.name); + break; + case 'os_version': + setFilter('os_version', item.name); + break; + } + }} + /> + +
+ + ); +} diff --git a/apps/dashboard/src/components/overview/overview-top-events/index.tsx b/apps/dashboard/src/components/overview/overview-top-events/index.tsx new file mode 100644 index 00000000..6c9601c1 --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-top-events/index.tsx @@ -0,0 +1,16 @@ +import { getConversionEventNames } from '@openpanel/db'; + +import type { OverviewTopEventsProps } from './overview-top-events'; +import OverviewTopEvents from './overview-top-events'; + +export default async function OverviewTopEventsServer({ + projectId, +}: Omit) { + const eventNames = await getConversionEventNames(projectId); + return ( + item.name)} + /> + ); +} diff --git a/apps/dashboard/src/components/overview/overview-top-events/overview-top-events.tsx b/apps/dashboard/src/components/overview/overview-top-events/overview-top-events.tsx new file mode 100644 index 00000000..7ec1cab3 --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-top-events/overview-top-events.tsx @@ -0,0 +1,128 @@ +'use client'; + +import { ChartSwitch } from '@/components/report/chart'; +import { useEventQueryFilters } from '@/hooks/useEventQueryFilters'; +import { cn } from '@/utils/cn'; + +import { Widget, WidgetBody } from '../../Widget'; +import { WidgetButtons, WidgetHead } from '../overview-widget'; +import { useOverviewOptions } from '../useOverviewOptions'; +import { useOverviewWidget } from '../useOverviewWidget'; + +export interface OverviewTopEventsProps { + projectId: string; + conversions: string[]; +} +export default function OverviewTopEvents({ + projectId, + conversions, +}: OverviewTopEventsProps) { + const { interval, range, previous, startDate, endDate } = + useOverviewOptions(); + const [filters] = useEventQueryFilters(); + const [widget, setWidget, widgets] = useOverviewWidget('ev', { + all: { + title: 'Top events', + btn: 'All', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters: [ + ...filters, + { + id: 'ex_session', + name: 'name', + operator: 'isNot', + value: ['session_start', 'session_end'], + }, + ], + id: 'A', + name: '*', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'name', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + conversions: { + title: 'Conversions', + btn: 'Conversions', + hide: conversions.length === 0, + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters: [ + ...filters, + { + id: 'conversion', + name: 'name', + operator: 'is', + value: conversions, + }, + ], + id: 'A', + name: '*', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'name', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + }); + + return ( + <> + + +
{widget.title}
+ + {widgets + .filter((item) => item.hide !== true) + .map((w) => ( + + ))} + +
+ + + +
+ + ); +} diff --git a/apps/dashboard/src/components/overview/overview-top-geo.tsx b/apps/dashboard/src/components/overview/overview-top-geo.tsx new file mode 100644 index 00000000..91aa2d2c --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-top-geo.tsx @@ -0,0 +1,191 @@ +'use client'; + +import { ChartSwitch } from '@/components/report/chart'; +import { useEventQueryFilters } from '@/hooks/useEventQueryFilters'; +import { cn } from '@/utils/cn'; + +import { Widget, WidgetBody } from '../Widget'; +import { WidgetButtons, WidgetHead } from './overview-widget'; +import { useOverviewOptions } from './useOverviewOptions'; +import { useOverviewWidget } from './useOverviewWidget'; + +interface OverviewTopGeoProps { + projectId: string; +} +export default function OverviewTopGeo({ projectId }: OverviewTopGeoProps) { + const { interval, range, previous, startDate, endDate } = + useOverviewOptions(); + const [filters, setFilter] = useEventQueryFilters(); + const isPageFilter = filters.find((filter) => filter.name === 'path'); + const [widget, setWidget, widgets] = useOverviewWidget('geo', { + countries: { + title: 'Top countries', + btn: 'Countries', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'country', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + regions: { + title: 'Top regions', + btn: 'Regions', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'region', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + cities: { + title: 'Top cities', + btn: 'Cities', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'city', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + }); + + return ( + <> + + +
{widget.title}
+ + {widgets.map((w) => ( + + ))} + +
+ + { + switch (widget.key) { + case 'countries': + setWidget('regions'); + setFilter('country', item.name); + break; + case 'regions': + setWidget('cities'); + setFilter('region', item.name); + break; + case 'cities': + setFilter('city', item.name); + break; + } + }} + /> + +
+ + +
Map
+
+ + + +
+ + ); +} diff --git a/apps/dashboard/src/components/overview/overview-top-pages.tsx b/apps/dashboard/src/components/overview/overview-top-pages.tsx new file mode 100644 index 00000000..140c3b76 --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-top-pages.tsx @@ -0,0 +1,142 @@ +'use client'; + +import { ChartSwitch } from '@/components/report/chart'; +import { useEventQueryFilters } from '@/hooks/useEventQueryFilters'; +import { cn } from '@/utils/cn'; + +import { Widget, WidgetBody } from '../Widget'; +import { WidgetButtons, WidgetHead } from './overview-widget'; +import { useOverviewOptions } from './useOverviewOptions'; +import { useOverviewWidget } from './useOverviewWidget'; + +interface OverviewTopPagesProps { + projectId: string; +} +export default function OverviewTopPages({ projectId }: OverviewTopPagesProps) { + const { interval, range, previous, startDate, endDate } = + useOverviewOptions(); + const [filters, setFilter] = useEventQueryFilters(); + const [widget, setWidget, widgets] = useOverviewWidget('pages', { + top: { + title: 'Top pages', + btn: 'Top pages', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: 'screen_view', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'path', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval, + name: 'Top sources', + range, + previous, + metric: 'sum', + }, + }, + entries: { + title: 'Entry Pages', + btn: 'Entries', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'path', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval, + name: 'Top sources', + range, + previous, + metric: 'sum', + }, + }, + exits: { + title: 'Exit Pages', + btn: 'Exits', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: 'session_end', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'path', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval, + name: 'Top sources', + range, + previous, + metric: 'sum', + }, + }, + }); + + return ( + <> + + +
{widget.title}
+ + {widgets.map((w) => ( + + ))} + +
+ + { + setFilter('path', item.name); + }} + /> + +
+ + ); +} diff --git a/apps/dashboard/src/components/overview/overview-top-sources.tsx b/apps/dashboard/src/components/overview/overview-top-sources.tsx new file mode 100644 index 00000000..5a8e3329 --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-top-sources.tsx @@ -0,0 +1,322 @@ +'use client'; + +import { ChartSwitch } from '@/components/report/chart'; +import { useEventQueryFilters } from '@/hooks/useEventQueryFilters'; +import { cn } from '@/utils/cn'; + +import { Widget, WidgetBody } from '../Widget'; +import { WidgetButtons, WidgetHead } from './overview-widget'; +import { useOverviewOptions } from './useOverviewOptions'; +import { useOverviewWidget } from './useOverviewWidget'; + +interface OverviewTopSourcesProps { + projectId: string; +} +export default function OverviewTopSources({ + projectId, +}: OverviewTopSourcesProps) { + const { interval, range, previous, startDate, endDate } = + useOverviewOptions(); + const [filters, setFilter] = useEventQueryFilters(); + const isPageFilter = filters.find((filter) => filter.name === 'path'); + const [widget, setWidget, widgets] = useOverviewWidget('sources', { + all: { + title: 'Top sources', + btn: 'All', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters: filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'referrer_name', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top groups', + range: range, + previous: previous, + metric: 'sum', + }, + }, + domain: { + title: 'Top urls', + btn: 'URLs', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters: filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'referrer', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + type: { + title: 'Top types', + btn: 'Types', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters: filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'referrer_type', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top types', + range: range, + previous: previous, + metric: 'sum', + }, + }, + utm_source: { + title: 'UTM Source', + btn: 'Source', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'properties.query.utm_source', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + utm_medium: { + title: 'UTM Medium', + btn: 'Medium', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'properties.query.utm_medium', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + utm_campaign: { + title: 'UTM Campaign', + btn: 'Campaign', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'properties.query.utm_campaign', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + utm_term: { + title: 'UTM Term', + btn: 'Term', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'properties.query.utm_term', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + utm_content: { + title: 'UTM Content', + btn: 'Content', + chart: { + projectId, + startDate, + endDate, + events: [ + { + segment: 'event', + filters, + id: 'A', + name: isPageFilter ? 'screen_view' : 'session_start', + }, + ], + breakdowns: [ + { + id: 'A', + name: 'properties.query.utm_content', + }, + ], + chartType: 'bar', + lineType: 'monotone', + interval: interval, + name: 'Top sources', + range: range, + previous: previous, + metric: 'sum', + }, + }, + }); + + return ( + <> + + +
{widget.title}
+ + {widgets.map((w) => ( + + ))} + +
+ + { + switch (widget.key) { + case 'all': + setFilter('referrer_name', item.name); + setWidget('domain'); + break; + case 'domain': + setFilter('referrer', item.name); + break; + case 'type': + setFilter('referrer_type', item.name); + setWidget('domain'); + break; + case 'utm_source': + setFilter('properties.query.utm_source', item.name); + break; + case 'utm_medium': + setFilter('properties.query.utm_medium', item.name); + break; + case 'utm_campaign': + setFilter('properties.query.utm_campaign', item.name); + break; + case 'utm_term': + setFilter('properties.query.utm_term', item.name); + break; + case 'utm_content': + setFilter('properties.query.utm_content', item.name); + break; + } + }} + /> + +
+ + ); +} diff --git a/apps/dashboard/src/components/overview/overview-widget.tsx b/apps/dashboard/src/components/overview/overview-widget.tsx new file mode 100644 index 00000000..9bead633 --- /dev/null +++ b/apps/dashboard/src/components/overview/overview-widget.tsx @@ -0,0 +1,122 @@ +'use client'; + +import { Children, useEffect, useRef, useState } from 'react'; +import { useThrottle } from '@/hooks/useThrottle'; +import { cn } from '@/utils/cn'; +import { ChevronsUpDownIcon } from 'lucide-react'; +import { last } from 'ramda'; + +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuTrigger, +} from '../ui/dropdown-menu'; +import type { WidgetHeadProps } from '../Widget'; +import { WidgetHead as WidgetHeadBase } from '../Widget'; + +export function WidgetHead({ className, ...props }: WidgetHeadProps) { + return ( + + ); +} + +export function WidgetButtons({ + className, + children, + ...props +}: WidgetHeadProps) { + const container = useRef(null); + const sizes = useRef([]); + const [slice, setSlice] = useState(3); // Show 3 buttons by default + const gap = 16; + + const handleResize = useThrottle(() => { + if (container.current) { + if (sizes.current.length === 0) { + // Get buttons + const buttons: HTMLButtonElement[] = Array.from( + container.current.querySelectorAll(`button`) + ); + // Get sizes and cache them + sizes.current = buttons.map( + (button) => Math.ceil(button.offsetWidth) + gap + ); + } + const containerWidth = container.current.offsetWidth; + const buttonsWidth = sizes.current.reduce((acc, size) => acc + size, 0); + const moreWidth = (last(sizes.current) ?? 0) + gap; + + if (buttonsWidth > containerWidth) { + const res = sizes.current.reduce( + (acc, size, index) => { + if (acc.size + size + moreWidth > containerWidth) { + return { index: acc.index, size: acc.size + size }; + } + return { index, size: acc.size + size }; + }, + { index: 0, size: 0 } + ); + + setSlice(res.index); + } else { + setSlice(sizes.current.length - 1); + } + } + }, 30); + + useEffect(() => { + handleResize(); + + window.addEventListener('resize', handleResize); + return () => window.removeEventListener('resize', handleResize); + }, [handleResize, children]); + + const hidden = '!opacity-0 absolute pointer-events-none'; + + return ( +
+ {Children.map(children, (child, index) => { + return ( + + ); + })} + + + + + + + {Children.map(children, (child, index) => { + if (index <= slice) { + return null; + } + return {child}; + })} + + + +
+ ); +} diff --git a/apps/dashboard/src/components/overview/useOverviewOptions.ts b/apps/dashboard/src/components/overview/useOverviewOptions.ts new file mode 100644 index 00000000..7a4000ad --- /dev/null +++ b/apps/dashboard/src/components/overview/useOverviewOptions.ts @@ -0,0 +1,71 @@ +import { + getDefaultIntervalByDates, + getDefaultIntervalByRange, + timeRanges, +} from '@openpanel/constants'; +import { mapKeys } from '@openpanel/validation'; +import { + parseAsBoolean, + parseAsInteger, + parseAsString, + parseAsStringEnum, + useQueryState, +} from 'nuqs'; + +const nuqsOptions = { history: 'push' } as const; + +export function useOverviewOptions() { + const [previous, setPrevious] = useQueryState( + 'compare', + parseAsBoolean.withDefault(true).withOptions(nuqsOptions) + ); + const [startDate, setStartDate] = useQueryState( + 'start', + parseAsString.withOptions(nuqsOptions) + ); + const [endDate, setEndDate] = useQueryState( + 'end', + parseAsString.withOptions(nuqsOptions) + ); + const [range, setRange] = useQueryState( + 'range', + parseAsStringEnum(mapKeys(timeRanges)) + .withDefault('7d') + .withOptions(nuqsOptions) + ); + + const interval = + getDefaultIntervalByDates(startDate, endDate) || + getDefaultIntervalByRange(range); + + const [metric, setMetric] = useQueryState( + 'metric', + parseAsInteger.withDefault(0).withOptions(nuqsOptions) + ); + + // Toggles + const [liveHistogram, setLiveHistogram] = useQueryState( + 'live', + parseAsBoolean.withDefault(true).withOptions(nuqsOptions) + ); + + return { + previous, + setPrevious, + range, + setRange, + metric, + setMetric, + startDate, + setStartDate, + endDate, + setEndDate, + + // Computed + interval, + + // Toggles + liveHistogram, + setLiveHistogram, + }; +} diff --git a/apps/dashboard/src/components/overview/useOverviewWidget.tsx b/apps/dashboard/src/components/overview/useOverviewWidget.tsx new file mode 100644 index 00000000..2eefa355 --- /dev/null +++ b/apps/dashboard/src/components/overview/useOverviewWidget.tsx @@ -0,0 +1,30 @@ +import { mapKeys } from '@openpanel/validation'; +import type { IChartInput } from '@openpanel/validation'; +import { parseAsStringEnum, useQueryState } from 'nuqs'; + +export function useOverviewWidget( + key: string, + widgets: Record< + T, + { title: string; btn: string; chart: IChartInput; hide?: boolean } + > +) { + const keys = Object.keys(widgets) as T[]; + const [widget, setWidget] = useQueryState( + key, + parseAsStringEnum(keys) + .withDefault(keys[0]!) + .withOptions({ history: 'push' }) + ); + return [ + { + ...widgets[widget], + key: widget, + }, + setWidget, + mapKeys(widgets).map((key) => ({ + ...widgets[key], + key, + })), + ] as const; +} diff --git a/apps/dashboard/src/components/profiles/ProfileAvatar.tsx b/apps/dashboard/src/components/profiles/ProfileAvatar.tsx new file mode 100644 index 00000000..e40417f5 --- /dev/null +++ b/apps/dashboard/src/components/profiles/ProfileAvatar.tsx @@ -0,0 +1,53 @@ +'use client'; + +import { cn } from '@/utils/cn'; +import type { IServiceProfile } from '@openpanel/db'; +import { AvatarImage } from '@radix-ui/react-avatar'; +import type { VariantProps } from 'class-variance-authority'; +import { cva } from 'class-variance-authority'; + +import { Avatar, AvatarFallback } from '../ui/avatar'; + +interface ProfileAvatarProps + extends VariantProps, + Partial> { + className?: string; +} + +const variants = cva('', { + variants: { + size: { + default: 'h-12 w-12 rounded-full [&>span]:rounded-full', + sm: 'h-6 w-6 rounded [&>span]:rounded', + xs: 'h-4 w-4 rounded [&>span]:rounded', + }, + }, + defaultVariants: { + size: 'default', + }, +}); + +export function ProfileAvatar({ + avatar, + first_name, + className, + size, +}: ProfileAvatarProps) { + return ( + + {avatar && } + + {first_name?.at(0) ?? '🫣'} + + + ); +} diff --git a/apps/web/src/components/projects/ProjectActions.tsx b/apps/dashboard/src/components/projects/ProjectActions.tsx similarity index 79% rename from apps/web/src/components/projects/ProjectActions.tsx rename to apps/dashboard/src/components/projects/ProjectActions.tsx index 99c78ced..6b58e124 100644 --- a/apps/web/src/components/projects/ProjectActions.tsx +++ b/apps/dashboard/src/components/projects/ProjectActions.tsx @@ -1,9 +1,12 @@ -import { useRefetchActive } from '@/hooks/useRefetchActive'; +'use client'; + +import { api } from '@/app/_trpc/client'; import { pushModal, showConfirm } from '@/modals'; -import type { IProject } from '@/types'; -import { api } from '@/utils/api'; import { clipboard } from '@/utils/clipboard'; +import type { IServiceProject } from '@openpanel/db'; import { MoreHorizontal } from 'lucide-react'; +import { useRouter } from 'next/navigation'; +import { toast } from 'sonner'; import { Button } from '../ui/button'; import { @@ -14,17 +17,16 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from '../ui/dropdown-menu'; -import { toast } from '../ui/use-toast'; -export function ProjectActions({ id }: IProject) { - const refetch = useRefetchActive(); +export function ProjectActions(project: Exclude) { + const { id } = project; + const router = useRouter(); const deletion = api.project.remove.useMutation({ onSuccess() { - toast({ - title: 'Success', + toast('Success', { description: 'Project deleted successfully.', }); - refetch(); + router.refresh(); }, }); @@ -43,7 +45,7 @@ export function ProjectActions({ id }: IProject) { { - pushModal('EditProject', { id }); + pushModal('EditProject', project); }} > Edit diff --git a/apps/dashboard/src/components/projects/project-card.tsx b/apps/dashboard/src/components/projects/project-card.tsx new file mode 100644 index 00000000..c01c0d41 --- /dev/null +++ b/apps/dashboard/src/components/projects/project-card.tsx @@ -0,0 +1,68 @@ +import { shortNumber } from '@/hooks/useNumerFormatter'; +import Link from 'next/link'; + +import type { IServiceProject } from '@openpanel/db'; +import { chQuery } from '@openpanel/db'; + +import { ChartSSR } from '../chart-ssr'; + +export async function ProjectCard({ + id, + name, + organizationSlug, +}: IServiceProject) { + const [chart, [data]] = await Promise.all([ + chQuery<{ value: number; date: string }>( + `SELECT countDistinct(profile_id) as value, toStartOfDay(created_at) as date FROM events WHERE project_id = '${id}' AND name = 'session_start' AND created_at >= now() - interval '1 month' GROUP BY date ORDER BY date ASC` + ), + chQuery<{ total: number; month: number; day: number }>( + ` + SELECT + ( + SELECT count(DISTINCT profile_id) as count FROM events WHERE project_id = '${id}' + ) as total, + ( + SELECT count(DISTINCT profile_id) as count FROM events WHERE project_id = '${id}' AND created_at >= now() - interval '1 month' + ) as month, + ( + SELECT count(DISTINCT profile_id) as count FROM events WHERE project_id = '${id}' AND created_at >= now() - interval '1 day' + ) as day + ` + ), + ]); + + return ( + +
{name}
+
+ ({ ...d, date: new Date(d.date) }))} /> +
+
+
Visitors
+
+
+
Total
+ + {shortNumber('en')(data?.total)} + +
+
+
Month
+ + {shortNumber('en')(data?.month)} + +
+
+
24h
+ + {shortNumber('en')(data?.day)} + +
+
+
+ + ); +} diff --git a/apps/web/src/components/projects/table.tsx b/apps/dashboard/src/components/projects/table.tsx similarity index 84% rename from apps/web/src/components/projects/table.tsx rename to apps/dashboard/src/components/projects/table.tsx index 6247992b..df97965f 100644 --- a/apps/web/src/components/projects/table.tsx +++ b/apps/dashboard/src/components/projects/table.tsx @@ -1,11 +1,11 @@ import { formatDate } from '@/utils/date'; -import type { Project as IProject } from '@prisma/client'; +import { IServiceProject } from '@openpanel/db'; +import type { Project as IProject } from '@openpanel/db'; import type { ColumnDef } from '@tanstack/react-table'; import { ProjectActions } from './ProjectActions'; export type Project = IProject; - export const columns: ColumnDef[] = [ { accessorKey: 'name', diff --git a/apps/dashboard/src/components/references/table.tsx b/apps/dashboard/src/components/references/table.tsx new file mode 100644 index 00000000..6fd734ea --- /dev/null +++ b/apps/dashboard/src/components/references/table.tsx @@ -0,0 +1,26 @@ +import { formatDate, formatDateTime } from '@/utils/date'; +import type { IServiceReference } from '@openpanel/db'; +import type { ColumnDef } from '@tanstack/react-table'; + +export const columns: ColumnDef[] = [ + { + accessorKey: 'title', + header: 'Title', + }, + { + accessorKey: 'date', + header: 'Date', + cell({ row }) { + const date = row.original.date; + return
{formatDateTime(date)}
; + }, + }, + { + accessorKey: 'createdAt', + header: 'Created at', + cell({ row }) { + const date = row.original.createdAt; + return
{formatDate(date)}
; + }, + }, +]; diff --git a/apps/dashboard/src/components/report/PreviousDiffIndicator.tsx b/apps/dashboard/src/components/report/PreviousDiffIndicator.tsx new file mode 100644 index 00000000..92993552 --- /dev/null +++ b/apps/dashboard/src/components/report/PreviousDiffIndicator.tsx @@ -0,0 +1,113 @@ +import { useNumber } from '@/hooks/useNumerFormatter'; +import { cn } from '@/utils/cn'; +import { TrendingDownIcon, TrendingUpIcon } from 'lucide-react'; + +import { Badge } from '../ui/badge'; +import { useChartContext } from './chart/ChartProvider'; + +export function getDiffIndicator( + inverted: boolean | undefined, + state: string | undefined | null, + positive: A, + negative: B, + neutral: C +): A | B | C { + if (state === 'neutral' || !state) { + return neutral; + } + + if (inverted === true) { + return state === 'positive' ? negative : positive; + } + return state === 'positive' ? positive : negative; +} + +// TODO: Fix this mess! + +interface PreviousDiffIndicatorProps { + diff?: number | null | undefined; + state?: string | null | undefined; + children?: React.ReactNode; + inverted?: boolean; +} + +export function PreviousDiffIndicator({ + diff, + state, + children, +}: PreviousDiffIndicatorProps) { + const { previous, previousIndicatorInverted } = useChartContext(); + const variant = getDiffIndicator( + previousIndicatorInverted, + state, + 'success', + 'destructive', + undefined + ); + const number = useNumber(); + + if (diff === null || diff === undefined || previous === false) { + return children ?? null; + } + + const renderIcon = () => { + if (state === 'positive') { + return ; + } + if (state === 'negative') { + return ; + } + return null; + }; + + return ( + <> + + {renderIcon()} + {number.format(diff)}% + + {children} + + ); +} + +export function PreviousDiffIndicatorText({ + diff, + state, + className, +}: PreviousDiffIndicatorProps & { className?: string }) { + const { previous, previousIndicatorInverted } = useChartContext(); + const number = useNumber(); + if (diff === null || diff === undefined || previous === false) { + return null; + } + + const renderIcon = () => { + if (state === 'positive') { + return ; + } + if (state === 'negative') { + return ; + } + return null; + }; + + return ( +
+ {renderIcon()} + {number.short(diff)}% +
+ ); +} diff --git a/apps/dashboard/src/components/report/ReportChartType.tsx b/apps/dashboard/src/components/report/ReportChartType.tsx new file mode 100644 index 00000000..58f1243d --- /dev/null +++ b/apps/dashboard/src/components/report/ReportChartType.tsx @@ -0,0 +1,31 @@ +import { useDispatch, useSelector } from '@/redux'; +import { chartTypes } from '@openpanel/constants'; +import { objectToZodEnums } from '@openpanel/validation'; +import { LineChartIcon } from 'lucide-react'; + +import { Combobox } from '../ui/combobox'; +import { changeChartType } from './reportSlice'; + +interface ReportChartTypeProps { + className?: string; +} +export function ReportChartType({ className }: ReportChartTypeProps) { + const dispatch = useDispatch(); + const type = useSelector((state) => state.report.chartType); + + return ( + { + dispatch(changeChartType(value)); + }} + value={type} + items={objectToZodEnums(chartTypes).map((key) => ({ + label: chartTypes[key], + value: key, + }))} + /> + ); +} diff --git a/apps/web/src/components/report/ReportInterval.tsx b/apps/dashboard/src/components/report/ReportInterval.tsx similarity index 63% rename from apps/web/src/components/report/ReportInterval.tsx rename to apps/dashboard/src/components/report/ReportInterval.tsx index 60eadff4..9cc6e141 100644 --- a/apps/web/src/components/report/ReportInterval.tsx +++ b/apps/dashboard/src/components/report/ReportInterval.tsx @@ -1,24 +1,38 @@ import { useDispatch, useSelector } from '@/redux'; -import type { IInterval } from '@/types'; -import { isMinuteIntervalEnabledByRange } from '@/utils/constants'; +import { + isHourIntervalEnabledByRange, + isMinuteIntervalEnabledByRange, +} from '@openpanel/constants'; +import type { IInterval } from '@openpanel/validation'; +import { ClockIcon } from 'lucide-react'; import { Combobox } from '../ui/combobox'; import { changeInterval } from './reportSlice'; -export function ReportInterval() { +interface ReportIntervalProps { + className?: string; +} +export function ReportInterval({ className }: ReportIntervalProps) { const dispatch = useDispatch(); const interval = useSelector((state) => state.report.interval); const range = useSelector((state) => state.report.range); const chartType = useSelector((state) => state.report.chartType); - if (chartType !== 'linear') { + if ( + chartType !== 'linear' && + chartType !== 'histogram' && + chartType !== 'area' && + chartType !== 'metric' + ) { return null; } return ( { - dispatch(changeInterval(value as IInterval)); + dispatch(changeInterval(value)); }} value={interval} items={[ @@ -30,6 +44,7 @@ export function ReportInterval() { { value: 'hour', label: 'Hour', + disabled: !isHourIntervalEnabledByRange(range), }, { value: 'day', diff --git a/apps/dashboard/src/components/report/ReportLineType.tsx b/apps/dashboard/src/components/report/ReportLineType.tsx new file mode 100644 index 00000000..cada47fa --- /dev/null +++ b/apps/dashboard/src/components/report/ReportLineType.tsx @@ -0,0 +1,36 @@ +import { useDispatch, useSelector } from '@/redux'; +import { lineTypes } from '@openpanel/constants'; +import { objectToZodEnums } from '@openpanel/validation'; +import { Tv2Icon } from 'lucide-react'; + +import { Combobox } from '../ui/combobox'; +import { changeLineType } from './reportSlice'; + +interface ReportLineTypeProps { + className?: string; +} +export function ReportLineType({ className }: ReportLineTypeProps) { + const dispatch = useDispatch(); + const chartType = useSelector((state) => state.report.chartType); + const type = useSelector((state) => state.report.lineType); + + if (chartType != 'linear' && chartType != 'area') { + return null; + } + + return ( + { + dispatch(changeLineType(value)); + }} + value={type} + items={objectToZodEnums(lineTypes).map((key) => ({ + label: lineTypes[key], + value: key, + }))} + /> + ); +} diff --git a/apps/dashboard/src/components/report/ReportRange.tsx b/apps/dashboard/src/components/report/ReportRange.tsx new file mode 100644 index 00000000..d71f81c7 --- /dev/null +++ b/apps/dashboard/src/components/report/ReportRange.tsx @@ -0,0 +1,101 @@ +import * as React from 'react'; +import { Button } from '@/components/ui/button'; +import { Calendar } from '@/components/ui/calendar'; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from '@/components/ui/popover'; +import { useBreakpoint } from '@/hooks/useBreakpoint'; +import { useDispatch, useSelector } from '@/redux'; +import { cn } from '@/utils/cn'; +import { timeRanges } from '@openpanel/constants'; +import type { IChartRange } from '@openpanel/validation'; +import { endOfDay, format, startOfDay } from 'date-fns'; +import { CalendarIcon, ChevronsUpDownIcon } from 'lucide-react'; +import type { SelectRangeEventHandler } from 'react-day-picker'; + +import type { ExtendedComboboxProps } from '../ui/combobox'; +import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group'; +import { changeDates, changeEndDate, changeStartDate } from './reportSlice'; + +export function ReportRange({ + range, + onRangeChange, + onDatesChange, + dates, + className, + ...props +}: { + range: IChartRange; + onRangeChange: (range: IChartRange) => void; + onDatesChange: SelectRangeEventHandler; + dates: { startDate: string | null; endDate: string | null }; +} & Omit, 'value' | 'onChange'>) { + const { isBelowSm } = useBreakpoint('sm'); + + return ( + <> + + + + + +
+ { + if (value) onRangeChange(value as IChartRange); + }} + type="single" + variant="outline" + className="flex-wrap max-sm:max-w-xs" + > + {Object.values(timeRanges).map((key) => ( + + {key} + + ))} + +
+ +
+
+ + ); +} diff --git a/apps/web/src/components/report/ReportSaveButton.tsx b/apps/dashboard/src/components/report/ReportSaveButton.tsx similarity index 68% rename from apps/web/src/components/report/ReportSaveButton.tsx rename to apps/dashboard/src/components/report/ReportSaveButton.tsx index 03cdc067..9fb874b9 100644 --- a/apps/web/src/components/report/ReportSaveButton.tsx +++ b/apps/dashboard/src/components/report/ReportSaveButton.tsx @@ -1,21 +1,25 @@ +'use client'; + +import { api, handleError } from '@/app/_trpc/client'; import { Button } from '@/components/ui/button'; -import { toast } from '@/components/ui/use-toast'; +import { useAppParams } from '@/hooks/useAppParams'; import { pushModal } from '@/modals'; import { useDispatch, useSelector } from '@/redux'; -import { api, handleError } from '@/utils/api'; import { SaveIcon } from 'lucide-react'; +import { toast } from 'sonner'; -import { useReportId } from './hooks/useReportId'; import { resetDirty } from './reportSlice'; -export function ReportSaveButton() { - const { reportId } = useReportId(); +interface ReportSaveButtonProps { + className?: string; +} +export function ReportSaveButton({ className }: ReportSaveButtonProps) { + const { reportId } = useAppParams<{ reportId: string | undefined }>(); const dispatch = useDispatch(); const update = api.report.update.useMutation({ onSuccess() { dispatch(resetDirty()); - toast({ - title: 'Success', + toast('Success', { description: 'Report updated.', }); }, @@ -26,11 +30,12 @@ export function ReportSaveButton() { if (reportId) { return ( +
+ ); +} diff --git a/apps/web/src/components/report/sidebar/ReportBreakdownMore.tsx b/apps/dashboard/src/components/report/sidebar/ReportBreakdownMore.tsx similarity index 100% rename from apps/web/src/components/report/sidebar/ReportBreakdownMore.tsx rename to apps/dashboard/src/components/report/sidebar/ReportBreakdownMore.tsx diff --git a/apps/web/src/components/report/sidebar/ReportBreakdowns.tsx b/apps/dashboard/src/components/report/sidebar/ReportBreakdowns.tsx similarity index 82% rename from apps/web/src/components/report/sidebar/ReportBreakdowns.tsx rename to apps/dashboard/src/components/report/sidebar/ReportBreakdowns.tsx index 9c3275f0..0f8b422a 100644 --- a/apps/web/src/components/report/sidebar/ReportBreakdowns.tsx +++ b/apps/dashboard/src/components/report/sidebar/ReportBreakdowns.tsx @@ -1,20 +1,23 @@ +'use client'; + +import { api } from '@/app/_trpc/client'; import { ColorSquare } from '@/components/ColorSquare'; import { Combobox } from '@/components/ui/combobox'; -import { useOrganizationParams } from '@/hooks/useOrganizationParams'; +import { useAppParams } from '@/hooks/useAppParams'; import { useDispatch, useSelector } from '@/redux'; -import type { IChartBreakdown } from '@/types'; -import { api } from '@/utils/api'; +import type { IChartBreakdown } from '@openpanel/validation'; +import { SplitIcon } from 'lucide-react'; import { addBreakdown, changeBreakdown, removeBreakdown } from '../reportSlice'; import { ReportBreakdownMore } from './ReportBreakdownMore'; import type { ReportEventMoreProps } from './ReportEventMore'; export function ReportBreakdowns() { - const params = useOrganizationParams(); + const { projectId } = useAppParams(); const selectedBreakdowns = useSelector((state) => state.report.breakdowns); const dispatch = useDispatch(); const propertiesQuery = api.chart.properties.useQuery({ - projectSlug: params.project, + projectId, }); const propertiesCombobox = (propertiesQuery.data ?? []).map((item) => ({ value: item, @@ -39,10 +42,13 @@ export function ReportBreakdowns() {
{selectedBreakdowns.map((item, index) => { return ( -
+
{index} { dispatch( @@ -63,6 +69,8 @@ export function ReportBreakdowns() { {selectedBreakdowns.length === 0 && ( { dispatch( diff --git a/apps/web/src/components/report/sidebar/ReportEventMore.tsx b/apps/dashboard/src/components/report/sidebar/ReportEventMore.tsx similarity index 87% rename from apps/web/src/components/report/sidebar/ReportEventMore.tsx rename to apps/dashboard/src/components/report/sidebar/ReportEventMore.tsx index 987a5f34..25168b87 100644 --- a/apps/web/src/components/report/sidebar/ReportEventMore.tsx +++ b/apps/dashboard/src/components/report/sidebar/ReportEventMore.tsx @@ -34,7 +34,7 @@ const labels = [ ]; export interface ReportEventMoreProps { - onClick: (action: 'createFilter' | 'remove') => void; + onClick: (action: 'remove') => void; } export function ReportEventMore({ onClick }: ReportEventMoreProps) { @@ -49,10 +49,6 @@ export function ReportEventMore({ onClick }: ReportEventMoreProps) { - onClick('createFilter')}> - - Add filter - state.report.previous); const selectedEvents = useSelector((state) => state.report.events); const dispatch = useDispatch(); - const params = useOrganizationParams(); - const eventsQuery = api.chart.events.useQuery({ - projectSlug: params.project, - }); - const eventsCombobox = (eventsQuery.data ?? []).map((item) => ({ - value: item.name, - label: item.name, - })); + const { projectId } = useAppParams(); + const eventNames = useEventNames(projectId); + const dispatchChangeEvent = useDebounceFn((event: IChartEvent) => { dispatch(changeEvent(event)); }); @@ -34,9 +38,6 @@ export function ReportEvents() { const handleMore = (event: IChartEvent) => { const callback: ReportEventMoreProps['onClick'] = (action) => { switch (action) { - case 'createFilter': { - return setIsCreating(true); - } case 'remove': { return dispatch(removeEvent(event)); } @@ -52,10 +53,13 @@ export function ReportEvents() {
{selectedEvents.map((event) => { return ( -
+
{event.id} { dispatch( @@ -66,7 +70,10 @@ export function ReportEvents() { }) ); }} - items={eventsCombobox} + items={eventNames.map((item) => ({ + label: item.name, + value: item.name, + }))} placeholder="Select event" /> - - + {/* */} + + + {(event.segment === 'property_average' || + event.segment === 'property_sum') && ( + + )}
{/* Filters */} - +
); })} { dispatch( addEvent({ @@ -162,10 +194,24 @@ export function ReportEvents() { }) ); }} - items={eventsCombobox} + items={eventNames.map((item) => ({ + label: item.name, + value: item.name, + }))} placeholder="Select event" />
+
); } diff --git a/apps/dashboard/src/components/report/sidebar/ReportForumula.tsx b/apps/dashboard/src/components/report/sidebar/ReportForumula.tsx new file mode 100644 index 00000000..1908bbe7 --- /dev/null +++ b/apps/dashboard/src/components/report/sidebar/ReportForumula.tsx @@ -0,0 +1,26 @@ +'use client'; + +import { Input } from '@/components/ui/input'; +import { useDispatch, useSelector } from '@/redux'; + +import { changeFormula } from '../reportSlice'; + +export function ReportForumula() { + const forumula = useSelector((state) => state.report.formula); + const dispatch = useDispatch(); + + return ( +
+

Forumula

+
+ { + dispatch(changeFormula(event.target.value)); + }} + /> +
+
+ ); +} diff --git a/apps/dashboard/src/components/report/sidebar/ReportSidebar.tsx b/apps/dashboard/src/components/report/sidebar/ReportSidebar.tsx new file mode 100644 index 00000000..2a4b8011 --- /dev/null +++ b/apps/dashboard/src/components/report/sidebar/ReportSidebar.tsx @@ -0,0 +1,27 @@ +import { Button } from '@/components/ui/button'; +import { SheetClose, SheetFooter } from '@/components/ui/sheet'; +import { useSelector } from '@/redux'; + +import { ReportBreakdowns } from './ReportBreakdowns'; +import { ReportEvents } from './ReportEvents'; +import { ReportForumula } from './ReportForumula'; + +export function ReportSidebar() { + const { chartType } = useSelector((state) => state.report); + const showForumula = chartType !== 'funnel'; + const showBreakdown = chartType !== 'funnel'; + return ( + <> +
+ + {showForumula && } + {showBreakdown && } +
+ + + + + + + ); +} diff --git a/apps/dashboard/src/components/report/sidebar/filters/FilterItem.tsx b/apps/dashboard/src/components/report/sidebar/filters/FilterItem.tsx new file mode 100644 index 00000000..a5294c4e --- /dev/null +++ b/apps/dashboard/src/components/report/sidebar/filters/FilterItem.tsx @@ -0,0 +1,132 @@ +import { api } from '@/app/_trpc/client'; +import { ColorSquare } from '@/components/ColorSquare'; +import { Dropdown } from '@/components/Dropdown'; +import { Button } from '@/components/ui/button'; +import { ComboboxAdvanced } from '@/components/ui/combobox-advanced'; +import { RenderDots } from '@/components/ui/RenderDots'; +import { useAppParams } from '@/hooks/useAppParams'; +import { useMappings } from '@/hooks/useMappings'; +import { useDispatch } from '@/redux'; +import { operators } from '@openpanel/constants'; +import type { + IChartEvent, + IChartEventFilterOperator, + IChartEventFilterValue, +} from '@openpanel/validation'; +import { mapKeys } from '@openpanel/validation'; +import { SlidersHorizontal, Trash } from 'lucide-react'; + +import { changeEvent } from '../../reportSlice'; + +interface FilterProps { + event: IChartEvent; + filter: IChartEvent['filters'][number]; +} + +export function FilterItem({ filter, event }: FilterProps) { + const { projectId } = useAppParams(); + const getLabel = useMappings(); + const dispatch = useDispatch(); + const potentialValues = api.chart.values.useQuery({ + event: event.name, + property: filter.name, + projectId, + }); + + const valuesCombobox = + potentialValues.data?.values?.map((item) => ({ + value: item, + label: getLabel(item), + })) ?? []; + + const removeFilter = () => { + dispatch( + changeEvent({ + ...event, + filters: event.filters.filter((item) => item.id !== filter.id), + }) + ); + }; + + const changeFilterValue = ( + value: IChartEventFilterValue | IChartEventFilterValue[] + ) => { + dispatch( + changeEvent({ + ...event, + filters: event.filters.map((item) => { + if (item.id === filter.id) { + return { + ...item, + value: Array.isArray(value) ? value : [value], + }; + } + + return item; + }), + }) + ); + }; + + const changeFilterOperator = (operator: IChartEventFilterOperator) => { + dispatch( + changeEvent({ + ...event, + filters: event.filters.map((item) => { + if (item.id === filter.id) { + return { + ...item, + operator, + }; + } + + return item; + }), + }) + ); + }; + + return ( +
+
+ + + +
+ {filter.name} +
+ +
+
+ ({ + value: key, + label: operators[key], + }))} + label="Operator" + > + + + { + changeFilterValue( + typeof setFn === 'function' ? setFn(filter.value) : setFn + ); + }} + placeholder="Select..." + /> +
+
+ ); +} diff --git a/apps/dashboard/src/components/report/sidebar/filters/FiltersCombobox.tsx b/apps/dashboard/src/components/report/sidebar/filters/FiltersCombobox.tsx new file mode 100644 index 00000000..d29c381a --- /dev/null +++ b/apps/dashboard/src/components/report/sidebar/filters/FiltersCombobox.tsx @@ -0,0 +1,61 @@ +import { api } from '@/app/_trpc/client'; +import { Combobox } from '@/components/ui/combobox'; +import { useAppParams } from '@/hooks/useAppParams'; +import { useDispatch } from '@/redux'; +import type { IChartEvent } from '@openpanel/validation'; +import { FilterIcon } from 'lucide-react'; + +import { changeEvent } from '../../reportSlice'; + +interface FiltersComboboxProps { + event: IChartEvent; +} + +export function FiltersCombobox({ event }: FiltersComboboxProps) { + const dispatch = useDispatch(); + const { projectId } = useAppParams(); + + const query = api.chart.properties.useQuery( + { + event: event.name, + projectId, + }, + { + enabled: !!event.name, + } + ); + + const properties = (query.data ?? []).map((item) => ({ + label: item, + value: item, + })); + + return ( + { + dispatch( + changeEvent({ + ...event, + filters: [ + ...event.filters, + { + id: (event.filters.length + 1).toString(), + name: value, + operator: 'is', + value: [], + }, + ], + }) + ); + }} + > + + + ); +} diff --git a/apps/dashboard/src/components/report/sidebar/filters/FiltersList.tsx b/apps/dashboard/src/components/report/sidebar/filters/FiltersList.tsx new file mode 100644 index 00000000..58b73591 --- /dev/null +++ b/apps/dashboard/src/components/report/sidebar/filters/FiltersList.tsx @@ -0,0 +1,19 @@ +import type { IChartEvent } from '@openpanel/validation'; + +import { FilterItem } from './FilterItem'; + +interface ReportEventFiltersProps { + event: IChartEvent; +} + +export function FiltersList({ event }: ReportEventFiltersProps) { + return ( +
+
+ {event.filters.map((filter) => { + return ; + })} +
+
+ ); +} diff --git a/apps/web/src/components/ui/RenderDots.tsx b/apps/dashboard/src/components/ui/RenderDots.tsx similarity index 99% rename from apps/web/src/components/ui/RenderDots.tsx rename to apps/dashboard/src/components/ui/RenderDots.tsx index 8542aec9..267c42e7 100644 --- a/apps/web/src/components/ui/RenderDots.tsx +++ b/apps/dashboard/src/components/ui/RenderDots.tsx @@ -1,3 +1,5 @@ +'use client'; + import { cn } from '@/utils/cn'; import { Asterisk, ChevronRight } from 'lucide-react'; diff --git a/apps/dashboard/src/components/ui/accordion.tsx b/apps/dashboard/src/components/ui/accordion.tsx new file mode 100644 index 00000000..71398b45 --- /dev/null +++ b/apps/dashboard/src/components/ui/accordion.tsx @@ -0,0 +1,56 @@ +import * as React from "react" +import * as AccordionPrimitive from "@radix-ui/react-accordion" +import { ChevronDown } from "lucide-react" + +import { cn } from "@/utils/cn" + +const Accordion = AccordionPrimitive.Root + +const AccordionItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)) +AccordionItem.displayName = "AccordionItem" + +const AccordionTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + svg]:rotate-180", + className + )} + {...props} + > + {children} + + + +)) +AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName + +const AccordionContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + +
{children}
+
+)) + +AccordionContent.displayName = AccordionPrimitive.Content.displayName + +export { Accordion, AccordionItem, AccordionTrigger, AccordionContent } diff --git a/apps/web/src/components/ui/alert-dialog.tsx b/apps/dashboard/src/components/ui/alert-dialog.tsx similarity index 99% rename from apps/web/src/components/ui/alert-dialog.tsx rename to apps/dashboard/src/components/ui/alert-dialog.tsx index bc4751da..463dc1e2 100644 --- a/apps/web/src/components/ui/alert-dialog.tsx +++ b/apps/dashboard/src/components/ui/alert-dialog.tsx @@ -1,3 +1,5 @@ +'use client'; + import * as React from 'react'; import { buttonVariants } from '@/components/ui/button'; import { cn } from '@/utils/cn'; diff --git a/apps/dashboard/src/components/ui/alert.tsx b/apps/dashboard/src/components/ui/alert.tsx new file mode 100644 index 00000000..27093d2a --- /dev/null +++ b/apps/dashboard/src/components/ui/alert.tsx @@ -0,0 +1,59 @@ +import * as React from 'react'; +import { cn } from '@/utils/cn'; +import { cva } from 'class-variance-authority'; +import type { VariantProps } from 'class-variance-authority'; + +const alertVariants = cva( + 'relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground', + { + variants: { + variant: { + default: 'bg-background text-foreground', + destructive: + 'border-destructive text-destructive dark:border-destructive [&>svg]:text-destructive', + }, + }, + defaultVariants: { + variant: 'default', + }, + } +); + +const Alert = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes & VariantProps +>(({ className, variant, ...props }, ref) => ( +
+)); +Alert.displayName = 'Alert'; + +const AlertTitle = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)); +AlertTitle.displayName = 'AlertTitle'; + +const AlertDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => ( +
+)); +AlertDescription.displayName = 'AlertDescription'; + +export { Alert, AlertTitle, AlertDescription }; diff --git a/apps/web/src/components/ui/aspect-ratio.tsx b/apps/dashboard/src/components/ui/aspect-ratio.tsx similarity index 90% rename from apps/web/src/components/ui/aspect-ratio.tsx rename to apps/dashboard/src/components/ui/aspect-ratio.tsx index 5dfdf1e6..aaabffbc 100644 --- a/apps/web/src/components/ui/aspect-ratio.tsx +++ b/apps/dashboard/src/components/ui/aspect-ratio.tsx @@ -1,3 +1,5 @@ +'use client'; + import * as AspectRatioPrimitive from '@radix-ui/react-aspect-ratio'; const AspectRatio = AspectRatioPrimitive.Root; diff --git a/apps/web/src/components/ui/avatar.tsx b/apps/dashboard/src/components/ui/avatar.tsx similarity index 98% rename from apps/web/src/components/ui/avatar.tsx rename to apps/dashboard/src/components/ui/avatar.tsx index 24042045..2817f1c6 100644 --- a/apps/web/src/components/ui/avatar.tsx +++ b/apps/dashboard/src/components/ui/avatar.tsx @@ -1,3 +1,5 @@ +'use client'; + import * as React from 'react'; import { cn } from '@/utils/cn'; import * as AvatarPrimitive from '@radix-ui/react-avatar'; diff --git a/apps/web/src/components/ui/badge.tsx b/apps/dashboard/src/components/ui/badge.tsx similarity index 77% rename from apps/web/src/components/ui/badge.tsx rename to apps/dashboard/src/components/ui/badge.tsx index 79b75eef..60b45ea9 100644 --- a/apps/web/src/components/ui/badge.tsx +++ b/apps/dashboard/src/components/ui/badge.tsx @@ -1,10 +1,12 @@ +'use client'; + import * as React from 'react'; import { cn } from '@/utils/cn'; import { cva } from 'class-variance-authority'; import type { VariantProps } from 'class-variance-authority'; const badgeVariants = cva( - 'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2', + 'inline-flex items-center rounded-full border px-1.5 h-[20px] text-[10px] font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2', { variants: { variant: { @@ -14,6 +16,8 @@ const badgeVariants = cva( 'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80', destructive: 'border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80', + success: + 'border-transparent bg-emerald-500 text-emerald-100 hover:bg-emerald-500/80', outline: 'text-foreground', }, }, diff --git a/apps/dashboard/src/components/ui/button.tsx b/apps/dashboard/src/components/ui/button.tsx new file mode 100644 index 00000000..ca40c6f1 --- /dev/null +++ b/apps/dashboard/src/components/ui/button.tsx @@ -0,0 +1,98 @@ +'use client'; + +import * as React from 'react'; +import { cn } from '@/utils/cn'; +import { Slot } from '@radix-ui/react-slot'; +import { cva } from 'class-variance-authority'; +import type { VariantProps } from 'class-variance-authority'; +import type { LucideIcon } from 'lucide-react'; +import { Loader2 } from 'lucide-react'; + +const buttonVariants = cva( + 'flex-shrink-0 inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background whitespace-nowrap transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50', + { + variants: { + variant: { + default: 'bg-primary text-primary-foreground hover:bg-primary/90', + cta: 'bg-blue-600 text-primary-foreground hover:bg-blue-500', + destructive: + 'bg-destructive text-destructive-foreground hover:bg-destructive/90', + outline: + 'border border-input bg-background hover:bg-accent hover:text-accent-foreground', + secondary: + 'bg-secondary text-secondary-foreground hover:bg-secondary/80', + ghost: 'hover:bg-accent hover:text-accent-foreground', + link: 'text-primary underline-offset-4 hover:underline', + }, + size: { + default: 'h-10 px-4 py-2', + sm: 'h-8 rounded-md px-2', + lg: 'h-11 rounded-md px-8', + icon: 'h-8 w-8', + }, + }, + defaultVariants: { + variant: 'default', + size: 'sm', + }, + } +); + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean; + loading?: boolean; + icon?: LucideIcon; + responsive?: boolean; +} + +const Button = React.forwardRef( + ( + { + className, + variant, + size, + asChild = false, + children, + loading, + disabled, + icon, + responsive, + ...props + }, + ref + ) => { + const Comp = asChild ? Slot : 'button'; + const Icon = loading ? Loader2 : icon ?? null; + return ( + + {Icon && ( + + )} + {responsive ? ( + {children} + ) : ( + children + )} + + ); + } +); +Button.displayName = 'Button'; +Button.defaultProps = { + type: 'button', +}; + +export { Button, buttonVariants }; diff --git a/apps/dashboard/src/components/ui/calendar.tsx b/apps/dashboard/src/components/ui/calendar.tsx new file mode 100644 index 00000000..9fd16ef5 --- /dev/null +++ b/apps/dashboard/src/components/ui/calendar.tsx @@ -0,0 +1,64 @@ +import * as React from "react" +import { ChevronLeft, ChevronRight } from "lucide-react" +import { DayPicker } from "react-day-picker" + +import { cn } from "@/utils/cn" +import { buttonVariants } from "@/components/ui/button" + +export type CalendarProps = React.ComponentProps + +function Calendar({ + className, + classNames, + showOutsideDays = true, + ...props +}: CalendarProps) { + return ( + , + IconRight: ({ ...props }) => , + }} + {...props} + /> + ) +} +Calendar.displayName = "Calendar" + +export { Calendar } diff --git a/apps/dashboard/src/components/ui/carousel.tsx b/apps/dashboard/src/components/ui/carousel.tsx new file mode 100644 index 00000000..cc9bb130 --- /dev/null +++ b/apps/dashboard/src/components/ui/carousel.tsx @@ -0,0 +1,258 @@ +import * as React from 'react'; +import { Button } from '@/components/ui/button'; +import { cn } from '@/utils/cn'; +import useEmblaCarousel from 'embla-carousel-react'; +import type { UseEmblaCarouselType } from 'embla-carousel-react'; +import { ArrowLeft, ArrowRight } from 'lucide-react'; + +type CarouselApi = UseEmblaCarouselType[1]; +type UseCarouselParameters = Parameters; +type CarouselOptions = UseCarouselParameters[0]; +type CarouselPlugin = UseCarouselParameters[1]; + +interface CarouselProps { + opts?: CarouselOptions; + plugins?: CarouselPlugin; + orientation?: 'horizontal' | 'vertical'; + setApi?: (api: CarouselApi) => void; +} + +type CarouselContextProps = { + carouselRef: ReturnType[0]; + api: ReturnType[1]; + scrollPrev: () => void; + scrollNext: () => void; + canScrollPrev: boolean; + canScrollNext: boolean; +} & CarouselProps; + +const CarouselContext = React.createContext(null); + +function useCarousel() { + const context = React.useContext(CarouselContext); + + if (!context) { + throw new Error('useCarousel must be used within a '); + } + + return context; +} + +const Carousel = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes & CarouselProps +>( + ( + { + orientation = 'horizontal', + opts, + setApi, + plugins, + className, + children, + ...props + }, + ref + ) => { + const [carouselRef, api] = useEmblaCarousel( + { + ...opts, + axis: orientation === 'horizontal' ? 'x' : 'y', + }, + plugins + ); + const [canScrollPrev, setCanScrollPrev] = React.useState(false); + const [canScrollNext, setCanScrollNext] = React.useState(false); + + const onSelect = React.useCallback((api: CarouselApi) => { + if (!api) { + return; + } + + setCanScrollPrev(api.canScrollPrev()); + setCanScrollNext(api.canScrollNext()); + }, []); + + const scrollPrev = React.useCallback(() => { + api?.scrollPrev(); + }, [api]); + + const scrollNext = React.useCallback(() => { + api?.scrollNext(); + }, [api]); + + const handleKeyDown = React.useCallback( + (event: React.KeyboardEvent) => { + if (event.key === 'ArrowLeft') { + event.preventDefault(); + scrollPrev(); + } else if (event.key === 'ArrowRight') { + event.preventDefault(); + scrollNext(); + } + }, + [scrollPrev, scrollNext] + ); + + React.useEffect(() => { + if (!api || !setApi) { + return; + } + + setApi(api); + }, [api, setApi]); + + React.useEffect(() => { + if (!api) { + return; + } + + onSelect(api); + api.on('reInit', onSelect); + api.on('select', onSelect); + + return () => { + api?.off('select', onSelect); + }; + }, [api, onSelect]); + + return ( + +
+ {children} +
+
+ ); + } +); +Carousel.displayName = 'Carousel'; + +const CarouselContent = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => { + const { carouselRef, orientation } = useCarousel(); + + return ( +
+
+
+ ); +}); +CarouselContent.displayName = 'CarouselContent'; + +const CarouselItem = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes +>(({ className, ...props }, ref) => { + const { orientation } = useCarousel(); + + return ( +
+ ); +}); +CarouselItem.displayName = 'CarouselItem'; + +const CarouselPrevious = React.forwardRef< + HTMLButtonElement, + React.ComponentProps +>(({ className, variant = 'outline', size = 'icon', ...props }, ref) => { + const { orientation, scrollPrev, canScrollPrev } = useCarousel(); + + return ( + + ); +}); +CarouselPrevious.displayName = 'CarouselPrevious'; + +const CarouselNext = React.forwardRef< + HTMLButtonElement, + React.ComponentProps +>(({ className, variant = 'outline', size = 'icon', ...props }, ref) => { + const { orientation, scrollNext, canScrollNext } = useCarousel(); + + return ( + + ); +}); +CarouselNext.displayName = 'CarouselNext'; + +export { + type CarouselApi, + Carousel, + CarouselContent, + CarouselItem, + CarouselPrevious, + CarouselNext, +}; diff --git a/apps/dashboard/src/components/ui/checkbox.tsx b/apps/dashboard/src/components/ui/checkbox.tsx new file mode 100644 index 00000000..0e02bc1a --- /dev/null +++ b/apps/dashboard/src/components/ui/checkbox.tsx @@ -0,0 +1,40 @@ +'use client'; + +import * as React from 'react'; +import { cn } from '@/utils/cn'; +import * as CheckboxPrimitive from '@radix-ui/react-checkbox'; +import { Check } from 'lucide-react'; + +const Checkbox = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + + + +)); +Checkbox.displayName = CheckboxPrimitive.Root.displayName; + +const CheckboxInput = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>((props, ref) => ( + +)); +CheckboxInput.displayName = 'CheckboxInput'; + +export { Checkbox, CheckboxInput }; diff --git a/apps/dashboard/src/components/ui/combobox-advanced.tsx b/apps/dashboard/src/components/ui/combobox-advanced.tsx new file mode 100644 index 00000000..91251087 --- /dev/null +++ b/apps/dashboard/src/components/ui/combobox-advanced.tsx @@ -0,0 +1,121 @@ +import * as React from 'react'; +import { Badge } from '@/components/ui/badge'; +import { + Command, + CommandGroup, + CommandInput, + CommandItem, + CommandList, +} from '@/components/ui/command'; +import { ChevronsUpDownIcon } from 'lucide-react'; +import { useOnClickOutside } from 'usehooks-ts'; + +import { Button } from './button'; +import { Checkbox } from './checkbox'; +import { Popover, PopoverContent, PopoverTrigger } from './popover'; + +type IValue = any; +type IItem = Record<'value' | 'label', IValue>; + +interface ComboboxAdvancedProps { + value: IValue[]; + onChange: React.Dispatch>; + items: IItem[]; + placeholder: string; + className?: string; +} + +export function ComboboxAdvanced({ + items, + value, + onChange, + placeholder, + className, +}: ComboboxAdvancedProps) { + const [open, setOpen] = React.useState(false); + const [inputValue, setInputValue] = React.useState(''); + const ref = React.useRef(null); + useOnClickOutside(ref, () => setOpen(false)); + + const selectables = items + .filter((item) => !value.find((s) => s === item.value)) + .filter( + (item) => + (typeof item.label === 'string' && + item.label.toLowerCase().includes(inputValue.toLowerCase())) || + (typeof item.value === 'string' && + item.value.toLowerCase().includes(inputValue.toLowerCase())) + ); + + const renderItem = (item: IItem) => { + const checked = !!value.find((s) => s === item.value); + return ( + { + e.preventDefault(); + e.stopPropagation(); + }} + onSelect={() => { + setInputValue(''); + onChange((prev) => { + if (prev.includes(item.value)) { + return prev.filter((s) => s !== item.value); + } + return [...prev, item.value]; + }); + }} + className={'cursor-pointer flex items-center gap-2'} + > + + {item?.label ?? item?.value} + + ); + }; + + const renderUnknownItem = (value: IValue) => { + const item = items.find((item) => item.value === value); + return item ? renderItem(item) : renderItem({ value, label: value }); + }; + + return ( + + + + + + + + + {inputValue !== '' && + renderItem({ + value: inputValue, + label: `Pick '${inputValue}'`, + })} + {value.map(renderUnknownItem)} + {selectables.map(renderItem)} + + + + + ); +} diff --git a/apps/dashboard/src/components/ui/combobox.tsx b/apps/dashboard/src/components/ui/combobox.tsx new file mode 100644 index 00000000..1e88e49a --- /dev/null +++ b/apps/dashboard/src/components/ui/combobox.tsx @@ -0,0 +1,148 @@ +'use client'; + +import * as React from 'react'; +import type { ButtonProps } from '@/components/ui/button'; +import { Button } from '@/components/ui/button'; +import { + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, +} from '@/components/ui/command'; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from '@/components/ui/popover'; +import { cn } from '@/utils/cn'; +import type { LucideIcon } from 'lucide-react'; +import { Check, ChevronsUpDown } from 'lucide-react'; + +export interface ComboboxProps { + placeholder: string; + items: { + value: T; + label: string; + disabled?: boolean; + }[]; + value: T | null | undefined; + onChange: (value: T) => void; + children?: React.ReactNode; + onCreate?: (value: T) => void; + className?: string; + searchable?: boolean; + icon?: LucideIcon; + size?: ButtonProps['size']; + label?: string; + align?: 'start' | 'end' | 'center'; + portal?: boolean; +} + +export type ExtendedComboboxProps = Omit< + ComboboxProps, + 'items' | 'placeholder' +> & { + placeholder?: string; +}; + +export function Combobox({ + placeholder, + items, + value, + onChange, + children, + onCreate, + className, + searchable, + icon: Icon, + size, + align = 'start', + portal, +}: ComboboxProps) { + const [open, setOpen] = React.useState(false); + const [search, setSearch] = React.useState(''); + function find(value: string) { + return items.find( + (item) => item.value.toLowerCase() === value.toLowerCase() + ); + } + + return ( + + + {children ?? ( + + )} + + + + {searchable === true && ( + + )} + {typeof onCreate === 'function' && search ? ( + + + + ) : ( + Nothing selected + )} +
+ + {items.map((item) => ( + { + const value = find(currentValue)?.value ?? currentValue; + onChange(value as T); + setOpen(false); + }} + {...(item.disabled && { disabled: true })} + > + + {item.label} + + ))} + +
+
+
+
+ ); +} diff --git a/apps/web/src/components/ui/command.tsx b/apps/dashboard/src/components/ui/command.tsx similarity index 99% rename from apps/web/src/components/ui/command.tsx rename to apps/dashboard/src/components/ui/command.tsx index c143a853..91b9f2af 100644 --- a/apps/web/src/components/ui/command.tsx +++ b/apps/dashboard/src/components/ui/command.tsx @@ -1,3 +1,5 @@ +'use client'; + import * as React from 'react'; import { Dialog, DialogContent } from '@/components/ui/dialog'; import { cn } from '@/utils/cn'; diff --git a/apps/dashboard/src/components/ui/dialog.tsx b/apps/dashboard/src/components/ui/dialog.tsx new file mode 100644 index 00000000..0465e161 --- /dev/null +++ b/apps/dashboard/src/components/ui/dialog.tsx @@ -0,0 +1,126 @@ +'use client'; + +import * as React from 'react'; +import { cn } from '@/utils/cn'; +import * as DialogPrimitive from '@radix-ui/react-dialog'; +import { X } from 'lucide-react'; + +const Dialog = DialogPrimitive.Root; + +const DialogTrigger = DialogPrimitive.Trigger; + +const DialogPortal = DialogPrimitive.Portal; + +const DialogClose = DialogPrimitive.Close; + +const DialogOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogOverlay.displayName = DialogPrimitive.Overlay.displayName; + +const DialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + onClose?: () => void; + } +>(({ className, children, onClose, ...props }, ref) => ( + + + + {children} + + + Close + + + +)); +DialogContent.displayName = DialogPrimitive.Content.displayName; + +const DialogHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +DialogHeader.displayName = 'DialogHeader'; + +const DialogFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +DialogFooter.displayName = 'DialogFooter'; + +const DialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogTitle.displayName = DialogPrimitive.Title.displayName; + +const DialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogDescription.displayName = DialogPrimitive.Description.displayName; + +export { + Dialog, + DialogPortal, + DialogOverlay, + DialogClose, + DialogTrigger, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +}; diff --git a/apps/web/src/components/ui/dropdown-menu.tsx b/apps/dashboard/src/components/ui/dropdown-menu.tsx similarity index 99% rename from apps/web/src/components/ui/dropdown-menu.tsx rename to apps/dashboard/src/components/ui/dropdown-menu.tsx index a2cf187a..842e461c 100644 --- a/apps/web/src/components/ui/dropdown-menu.tsx +++ b/apps/dashboard/src/components/ui/dropdown-menu.tsx @@ -1,3 +1,5 @@ +'use client'; + import * as React from 'react'; import { cn } from '@/utils/cn'; import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu'; diff --git a/apps/dashboard/src/components/ui/gradient-background.tsx b/apps/dashboard/src/components/ui/gradient-background.tsx new file mode 100644 index 00000000..f88c3e40 --- /dev/null +++ b/apps/dashboard/src/components/ui/gradient-background.tsx @@ -0,0 +1,24 @@ +import { cn } from '@/utils/cn'; + +interface GradientBackgroundProps { + children: React.ReactNode; + className?: string; +} + +export function GradientBackground({ + children, + className, + ...props +}: GradientBackgroundProps) { + return ( +
+
{children}
+
+ ); +} diff --git a/apps/dashboard/src/components/ui/input.tsx b/apps/dashboard/src/components/ui/input.tsx new file mode 100644 index 00000000..772c9e0e --- /dev/null +++ b/apps/dashboard/src/components/ui/input.tsx @@ -0,0 +1,45 @@ +'use client'; + +import * as React from 'react'; +import { cn } from '@/utils/cn'; +import type { VariantProps } from 'class-variance-authority'; +import { cva } from 'class-variance-authority'; + +const inputVariant = cva( + 'flex w-full rounded-md border border-input bg-background ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50', + { + variants: { + size: { + default: 'h-8 px-3 py-2 text-sm', + large: 'h-12 px-4 py-3 text-lg', + }, + }, + defaultVariants: { + size: 'default', + }, + } +); + +export type InputProps = VariantProps & + Omit, 'size'> & { + error?: string | undefined; + }; + +const Input = React.forwardRef( + ({ className, error, type, size, ...props }, ref) => { + return ( + + ); + } +); +Input.displayName = 'Input'; + +export { Input }; diff --git a/apps/dashboard/src/components/ui/key-value.tsx b/apps/dashboard/src/components/ui/key-value.tsx new file mode 100644 index 00000000..be2a718f --- /dev/null +++ b/apps/dashboard/src/components/ui/key-value.tsx @@ -0,0 +1,56 @@ +import { isValidElement } from 'react'; +import { cn } from '@/utils/cn'; +import Link from 'next/link'; + +interface KeyValueProps { + name: string; + value: unknown; + onClick?: () => void; + href?: string; +} + +export function KeyValue({ href, onClick, name, value }: KeyValueProps) { + const clickable = href || onClick; + const Component = href ? (Link as any) : onClick ? 'button' : 'div'; + + return ( + +
{name}
+
+ {value} +
+
+ ); +} + +export function KeyValueSubtle({ href, onClick, name, value }: KeyValueProps) { + const clickable = href || onClick; + const Component = href ? (Link as any) : onClick ? 'button' : 'div'; + return ( + +
{name}
+
+ {value} +
+
+ ); +} diff --git a/apps/web/src/components/ui/label.tsx b/apps/dashboard/src/components/ui/label.tsx similarity index 98% rename from apps/web/src/components/ui/label.tsx rename to apps/dashboard/src/components/ui/label.tsx index eada103c..19859916 100644 --- a/apps/web/src/components/ui/label.tsx +++ b/apps/dashboard/src/components/ui/label.tsx @@ -1,3 +1,5 @@ +'use client'; + import * as React from 'react'; import { cn } from '@/utils/cn'; import * as LabelPrimitive from '@radix-ui/react-label'; diff --git a/apps/dashboard/src/components/ui/popover.tsx b/apps/dashboard/src/components/ui/popover.tsx new file mode 100644 index 00000000..68538cf5 --- /dev/null +++ b/apps/dashboard/src/components/ui/popover.tsx @@ -0,0 +1,39 @@ +import * as React from 'react'; +import { cn } from '@/utils/cn'; +import * as PopoverPrimitive from '@radix-ui/react-popover'; + +const Popover = PopoverPrimitive.Root; + +const PopoverTrigger = PopoverPrimitive.Trigger; + +const PopoverContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + portal?: boolean; + } +>(({ className, align = 'center', sideOffset = 4, portal, ...props }, ref) => { + const node = ( + + ); + + if (portal) { + return {node}; + } + + return node; +}); +PopoverContent.displayName = PopoverPrimitive.Content.displayName; + +export { Popover, PopoverTrigger, PopoverContent }; diff --git a/apps/dashboard/src/components/ui/progress.tsx b/apps/dashboard/src/components/ui/progress.tsx new file mode 100644 index 00000000..77bd3f92 --- /dev/null +++ b/apps/dashboard/src/components/ui/progress.tsx @@ -0,0 +1,30 @@ +import * as React from 'react'; +import { cn } from '@/utils/cn'; +import * as ProgressPrimitive from '@radix-ui/react-progress'; + +const Progress = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + color: string; + } +>(({ className, value, color, ...props }, ref) => ( + + + +)); +Progress.displayName = ProgressPrimitive.Root.displayName; + +export { Progress }; diff --git a/apps/web/src/components/ui/radio-group.tsx b/apps/dashboard/src/components/ui/radio-group.tsx similarity index 98% rename from apps/web/src/components/ui/radio-group.tsx rename to apps/dashboard/src/components/ui/radio-group.tsx index a2975858..fb251a99 100644 --- a/apps/web/src/components/ui/radio-group.tsx +++ b/apps/dashboard/src/components/ui/radio-group.tsx @@ -1,3 +1,5 @@ +'use client'; + import * as React from 'react'; import { cn } from '@/utils/cn'; diff --git a/apps/web/src/components/ui/scroll-area.tsx b/apps/dashboard/src/components/ui/scroll-area.tsx similarity index 57% rename from apps/web/src/components/ui/scroll-area.tsx rename to apps/dashboard/src/components/ui/scroll-area.tsx index f25a5f8c..b2c7836c 100644 --- a/apps/web/src/components/ui/scroll-area.tsx +++ b/apps/dashboard/src/components/ui/scroll-area.tsx @@ -1,7 +1,8 @@ -import * as React from "react" -import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area" +'use client'; -import { cn } from "@/utils/cn" +import * as React from 'react'; +import { cn } from '@/utils/cn'; +import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area'; const ScrollArea = React.forwardRef< React.ElementRef, @@ -9,7 +10,7 @@ const ScrollArea = React.forwardRef< >(({ className, children, ...props }, ref) => ( @@ -18,34 +19,34 @@ const ScrollArea = React.forwardRef< -)) -ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName +)); +ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName; const ScrollBar = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef ->(({ className, orientation = "vertical", ...props }, ref) => ( +>(({ className, orientation = 'vertical', ...props }, ref) => ( -)) -ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName +)); +ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName; -export { ScrollArea, ScrollBar } +export { ScrollArea, ScrollBar }; diff --git a/apps/dashboard/src/components/ui/sheet.tsx b/apps/dashboard/src/components/ui/sheet.tsx new file mode 100644 index 00000000..87fe3a5e --- /dev/null +++ b/apps/dashboard/src/components/ui/sheet.tsx @@ -0,0 +1,147 @@ +'use client'; + +import * as React from 'react'; +import { cn } from '@/utils/cn'; +import * as SheetPrimitive from '@radix-ui/react-dialog'; +import { cva } from 'class-variance-authority'; +import type { VariantProps } from 'class-variance-authority'; +import { XIcon } from 'lucide-react'; + +const Sheet = SheetPrimitive.Root; + +const SheetTrigger = SheetPrimitive.Trigger; + +const SheetClose = SheetPrimitive.Close; + +const SheetPortal = SheetPrimitive.Portal; + +const SheetOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SheetOverlay.displayName = SheetPrimitive.Overlay.displayName; + +const sheetVariants = cva( + 'flex flex-col max-sm:w-[calc(100%-theme(spacing.8))] overflow-y-auto fixed z-50 gap-4 bg-background p-6 rounded-lg shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500', + { + variants: { + side: { + top: 'inset-x-4 top-4 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top', + bottom: + 'inset-x-4 bottom-4 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom', + left: 'top-4 bottom-4 left-4 w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm', + right: + 'top-4 bottom-4 right-4 w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm', + }, + }, + defaultVariants: { + side: 'right', + }, + } +); + +interface SheetContentProps + extends React.ComponentPropsWithoutRef, + VariantProps {} + +const SheetContent = React.forwardRef< + React.ElementRef, + SheetContentProps & { + onClose?: () => void; + } +>(({ side = 'right', className, children, onClose, ...props }, ref) => ( + + + + {children} + + + + Close + + + +)); +SheetContent.displayName = SheetPrimitive.Content.displayName; + +const SheetHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +SheetHeader.displayName = 'SheetHeader'; + +const SheetFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +SheetFooter.displayName = 'SheetFooter'; + +const SheetTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SheetTitle.displayName = SheetPrimitive.Title.displayName; + +const SheetDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SheetDescription.displayName = SheetPrimitive.Description.displayName; + +export { + Sheet, + SheetPortal, + SheetOverlay, + SheetTrigger, + SheetClose, + SheetContent, + SheetHeader, + SheetFooter, + SheetTitle, + SheetDescription, +}; diff --git a/apps/dashboard/src/components/ui/sonner.tsx b/apps/dashboard/src/components/ui/sonner.tsx new file mode 100644 index 00000000..537e52a5 --- /dev/null +++ b/apps/dashboard/src/components/ui/sonner.tsx @@ -0,0 +1,29 @@ +import { useTheme } from 'next-themes'; +import { Toaster as Sonner } from 'sonner'; + +type ToasterProps = React.ComponentProps; + +const Toaster = ({ ...props }: ToasterProps) => { + const { theme = 'system' } = useTheme(); + + return ( + + ); +}; + +export { Toaster }; diff --git a/apps/web/src/components/ui/table.tsx b/apps/dashboard/src/components/ui/table.tsx similarity index 88% rename from apps/web/src/components/ui/table.tsx rename to apps/dashboard/src/components/ui/table.tsx index 4e67313f..e99dfa41 100644 --- a/apps/web/src/components/ui/table.tsx +++ b/apps/dashboard/src/components/ui/table.tsx @@ -1,12 +1,17 @@ +'use client'; + import * as React from 'react'; import { cn } from '@/utils/cn'; const Table = React.forwardRef< HTMLTableElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
-
+ React.HTMLAttributes & { + wrapper?: boolean; + overflow?: boolean; + } +>(({ className, wrapper, overflow = true, ...props }, ref) => ( +
+
; + +const Toaster = ({ ...props }: ToasterProps) => { + const { theme = 'system' } = useTheme(); + + return ( + + ); +}; + +export { Toaster }; diff --git a/apps/dashboard/src/components/ui/toggle-group.tsx b/apps/dashboard/src/components/ui/toggle-group.tsx new file mode 100644 index 00000000..87cb456b --- /dev/null +++ b/apps/dashboard/src/components/ui/toggle-group.tsx @@ -0,0 +1,59 @@ +import * as React from "react" +import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group" +import { VariantProps } from "class-variance-authority" + +import { cn } from "@/utils/cn" +import { toggleVariants } from "@/components/ui/toggle" + +const ToggleGroupContext = React.createContext< + VariantProps +>({ + size: "default", + variant: "default", +}) + +const ToggleGroup = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & + VariantProps +>(({ className, variant, size, children, ...props }, ref) => ( + + + {children} + + +)) + +ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName + +const ToggleGroupItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & + VariantProps +>(({ className, children, variant, size, ...props }, ref) => { + const context = React.useContext(ToggleGroupContext) + + return ( + + {children} + + ) +}) + +ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName + +export { ToggleGroup, ToggleGroupItem } diff --git a/apps/dashboard/src/components/ui/toggle.tsx b/apps/dashboard/src/components/ui/toggle.tsx new file mode 100644 index 00000000..0569a7bc --- /dev/null +++ b/apps/dashboard/src/components/ui/toggle.tsx @@ -0,0 +1,43 @@ +import * as React from "react" +import * as TogglePrimitive from "@radix-ui/react-toggle" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/utils/cn" + +const toggleVariants = cva( + "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground", + { + variants: { + variant: { + default: "bg-transparent", + outline: + "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground", + }, + size: { + default: "h-10 px-3", + sm: "h-9 px-2.5", + lg: "h-11 px-5", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +const Toggle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & + VariantProps +>(({ className, variant, size, ...props }, ref) => ( + +)) + +Toggle.displayName = TogglePrimitive.Root.displayName + +export { Toggle, toggleVariants } diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/dashboard/src/components/ui/tooltip.tsx similarity index 65% rename from apps/web/src/components/ui/tooltip.tsx rename to apps/dashboard/src/components/ui/tooltip.tsx index f7ceae52..1849163f 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/dashboard/src/components/ui/tooltip.tsx @@ -1,3 +1,5 @@ +'use client'; + import * as React from 'react'; import { cn } from '@/utils/cn'; import * as TooltipPrimitive from '@radix-ui/react-tooltip'; @@ -16,7 +18,7 @@ const TooltipContent = React.forwardRef< ref={ref} sideOffset={sideOffset} className={cn( - 'z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2', + 'z-50 overflow-hidden rounded-md border bg-black px-3 py-1.5 text-sm text-popover shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2', className )} {...props} diff --git a/apps/web/src/env.mjs b/apps/dashboard/src/env.mjs similarity index 71% rename from apps/web/src/env.mjs rename to apps/dashboard/src/env.mjs index 32ac1455..df287104 100644 --- a/apps/web/src/env.mjs +++ b/apps/dashboard/src/env.mjs @@ -17,17 +17,6 @@ export const env = createEnv({ NODE_ENV: z .enum(['development', 'test', 'production']) .default('development'), - NEXTAUTH_SECRET: - process.env.NODE_ENV === 'production' - ? z.string() - : z.string().optional(), - NEXTAUTH_URL: z.preprocess( - // This makes Vercel deployments not fail if you don't set NEXTAUTH_URL - // Since NextAuth.js automatically uses the VERCEL_URL if present. - (str) => process.env.VERCEL_URL ?? str, - // VERCEL_URL doesn't include `https` so it cant be validated as a URL - process.env.VERCEL ? z.string() : z.string().url() - ), }, /** @@ -46,8 +35,6 @@ export const env = createEnv({ runtimeEnv: { DATABASE_URL: process.env.DATABASE_URL, NODE_ENV: process.env.NODE_ENV, - NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET, - NEXTAUTH_URL: process.env.NEXTAUTH_URL, }, /** * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially diff --git a/apps/dashboard/src/hooks/useAppParams.ts b/apps/dashboard/src/hooks/useAppParams.ts new file mode 100644 index 00000000..805ac9d6 --- /dev/null +++ b/apps/dashboard/src/hooks/useAppParams.ts @@ -0,0 +1,16 @@ +import { useParams } from 'next/navigation'; + +// eslint-disable-next-line +type AppParams = { + organizationId: string; + projectId: string; +}; + +export function useAppParams() { + const params = useParams(); + return { + ...(params ?? {}), + organizationId: params?.organizationId, + projectId: params?.projectId, + } as T & AppParams; +} diff --git a/apps/web/src/hooks/useBreakpoint.ts b/apps/dashboard/src/hooks/useBreakpoint.ts similarity index 100% rename from apps/web/src/hooks/useBreakpoint.ts rename to apps/dashboard/src/hooks/useBreakpoint.ts diff --git a/apps/dashboard/src/hooks/useCursor.ts b/apps/dashboard/src/hooks/useCursor.ts new file mode 100644 index 00000000..458c4710 --- /dev/null +++ b/apps/dashboard/src/hooks/useCursor.ts @@ -0,0 +1,14 @@ +import { parseAsInteger, useQueryState } from 'nuqs'; + +export function useCursor() { + const [cursor, setCursor] = useQueryState( + 'cursor', + parseAsInteger + .withOptions({ shallow: false, history: 'push' }) + .withDefault(0) + ); + return { + cursor, + setCursor, + }; +} diff --git a/apps/web/src/hooks/useDebounceFn.ts b/apps/dashboard/src/hooks/useDebounceFn.ts similarity index 100% rename from apps/web/src/hooks/useDebounceFn.ts rename to apps/dashboard/src/hooks/useDebounceFn.ts diff --git a/apps/dashboard/src/hooks/useEventNames.ts b/apps/dashboard/src/hooks/useEventNames.ts new file mode 100644 index 00000000..41dcb051 --- /dev/null +++ b/apps/dashboard/src/hooks/useEventNames.ts @@ -0,0 +1,9 @@ +import { api } from '@/app/_trpc/client'; + +export function useEventNames(projectId: string) { + const query = api.chart.events.useQuery({ + projectId: projectId, + }); + + return query.data ?? []; +} diff --git a/apps/dashboard/src/hooks/useEventProperties.ts b/apps/dashboard/src/hooks/useEventProperties.ts new file mode 100644 index 00000000..2bd5f1ff --- /dev/null +++ b/apps/dashboard/src/hooks/useEventProperties.ts @@ -0,0 +1,10 @@ +import { api } from '@/app/_trpc/client'; + +export function useEventProperties(projectId: string, event?: string) { + const query = api.chart.properties.useQuery({ + projectId: projectId, + event, + }); + + return query.data ?? []; +} diff --git a/apps/dashboard/src/hooks/useEventQueryFilters.ts b/apps/dashboard/src/hooks/useEventQueryFilters.ts new file mode 100644 index 00000000..34597131 --- /dev/null +++ b/apps/dashboard/src/hooks/useEventQueryFilters.ts @@ -0,0 +1,102 @@ +import { useCallback } from 'react'; + +// prettier-ignore +import type { Options as NuqsOptions } from 'nuqs'; + +import { + createParser, + parseAsArrayOf, + parseAsString, + useQueryState, +} from 'nuqs'; + +const nuqsOptions = { history: 'push' } as const; + +type Operator = 'is' | 'isNot' | 'contains' | 'doesNotContain'; + +export const eventQueryFiltersParser = createParser({ + parse: (query: string) => { + if (query === '') return []; + const filters = query.split(';'); + + return ( + filters.map((filter) => { + const [key, operator, value] = filter.split(','); + return { + id: key!, + name: key!, + operator: (operator ?? 'is') as Operator, + value: [decodeURIComponent(value!)], + }; + }) ?? [] + ); + }, + serialize: (value) => { + return value + .map( + (filter) => + `${filter.id},${filter.operator},${encodeURIComponent(filter.value[0] ?? '')}` + ) + .join(';'); + }, +}); + +export function useEventQueryFilters(options: NuqsOptions = {}) { + const [filters, setFilters] = useQueryState( + 'f', + eventQueryFiltersParser.withDefault([]).withOptions({ + ...nuqsOptions, + ...options, + }) + ); + + const setFilter = useCallback( + ( + name: string, + value: string | number | boolean | undefined | null, + operator: Operator = 'is' + ) => { + setFilters((prev) => { + const exists = prev.find((filter) => filter.name === name); + if (exists) { + // If same value is already set, remove the filter + if (exists.value[0] === value) { + return prev.filter((filter) => filter.name !== name); + } + + return prev.map((filter) => { + if (filter.name === name) { + return { + ...filter, + operator, + value: [String(value)], + }; + } + return filter; + }); + } + + return [ + ...prev, + { + id: name, + name, + operator, + value: [String(value)], + }, + ]; + }); + }, + [setFilters] + ); + + return [filters, setFilter, setFilters] as const; +} + +export const eventQueryNamesFilter = parseAsArrayOf(parseAsString).withDefault( + [] +); + +export function useEventQueryNamesFilter(options: NuqsOptions = {}) { + return useQueryState('events', eventQueryNamesFilter.withOptions(options)); +} diff --git a/apps/dashboard/src/hooks/useEventValues.ts b/apps/dashboard/src/hooks/useEventValues.ts new file mode 100644 index 00000000..22f8cd19 --- /dev/null +++ b/apps/dashboard/src/hooks/useEventValues.ts @@ -0,0 +1,15 @@ +import { api } from '@/app/_trpc/client'; + +export function useEventValues( + projectId: string, + event: string, + property: string +) { + const query = api.chart.values.useQuery({ + projectId: projectId, + event, + property, + }); + + return query.data?.values ?? []; +} diff --git a/apps/web/src/hooks/useFormatDateInterval.ts b/apps/dashboard/src/hooks/useFormatDateInterval.ts similarity index 93% rename from apps/web/src/hooks/useFormatDateInterval.ts rename to apps/dashboard/src/hooks/useFormatDateInterval.ts index 8ab03c68..d00f9fec 100644 --- a/apps/web/src/hooks/useFormatDateInterval.ts +++ b/apps/dashboard/src/hooks/useFormatDateInterval.ts @@ -1,4 +1,4 @@ -import type { IInterval } from '@/types'; +import type { IInterval } from '@openpanel/validation'; export function formatDateInterval(interval: IInterval, date: Date): string { if (interval === 'hour' || interval === 'minute') { diff --git a/apps/web/src/hooks/useMappings.ts b/apps/dashboard/src/hooks/useMappings.ts similarity index 80% rename from apps/web/src/hooks/useMappings.ts rename to apps/dashboard/src/hooks/useMappings.ts index 18ecfad9..35130c0c 100644 --- a/apps/web/src/hooks/useMappings.ts +++ b/apps/dashboard/src/hooks/useMappings.ts @@ -1,7 +1,7 @@ import mappings from '@/mappings.json'; export function useMappings() { - return (val: string) => { + return (val: string | null) => { return mappings.find((item) => item.id === val)?.name ?? val; }; } diff --git a/apps/dashboard/src/hooks/useNumerFormatter.ts b/apps/dashboard/src/hooks/useNumerFormatter.ts new file mode 100644 index 00000000..8e400746 --- /dev/null +++ b/apps/dashboard/src/hooks/useNumerFormatter.ts @@ -0,0 +1,60 @@ +import { round } from '@/utils/math'; +import { isNil } from 'ramda'; + +export function fancyMinutes(time: number) { + const minutes = Math.floor(time / 60); + const seconds = round(time - minutes * 60, 0); + if (minutes === 0) return `${seconds}s`; + return `${minutes}m ${seconds}s`; +} + +export const formatNumber = + (locale: string) => (value: number | null | undefined) => { + if (isNil(value)) { + return 'N/A'; + } + return new Intl.NumberFormat(locale, { + maximumSignificantDigits: 20, + }).format(value); + }; + +export const shortNumber = + (locale: string) => (value: number | null | undefined) => { + if (isNil(value)) { + return 'N/A'; + } + return new Intl.NumberFormat(locale, { + notation: 'compact', + }).format(value); + }; + +export function useNumber() { + const locale = 'en-gb'; + const format = formatNumber(locale); + const short = shortNumber(locale); + return { + format, + short, + shortWithUnit: (value: number | null | undefined, unit?: string | null) => { + if (isNil(value)) { + return 'N/A'; + } + if (unit === 'min') { + return fancyMinutes(value); + } + return `${short(value)}${unit ? ` ${unit}` : ''}`; + }, + formatWithUnit: ( + value: number | null | undefined, + unit?: string | null + ) => { + if (isNil(value)) { + return 'N/A'; + } + if (unit === 'min') { + return fancyMinutes(value); + } + return `${format(value)}${unit ? ` ${unit}` : ''}`; + }, + }; +} diff --git a/apps/dashboard/src/hooks/useProfileProperties.ts b/apps/dashboard/src/hooks/useProfileProperties.ts new file mode 100644 index 00000000..3cd44a50 --- /dev/null +++ b/apps/dashboard/src/hooks/useProfileProperties.ts @@ -0,0 +1,10 @@ +import { api } from '@/app/_trpc/client'; + +export function useProfileProperties(projectId: string, event?: string) { + const query = api.profile.properties.useQuery({ + projectId: projectId, + event, + }); + + return query.data ?? []; +} diff --git a/apps/dashboard/src/hooks/useProfileValues.ts b/apps/dashboard/src/hooks/useProfileValues.ts new file mode 100644 index 00000000..09cdf924 --- /dev/null +++ b/apps/dashboard/src/hooks/useProfileValues.ts @@ -0,0 +1,10 @@ +import { api } from '@/app/_trpc/client'; + +export function useProfileValues(projectId: string, property: string) { + const query = api.profile.values.useQuery({ + projectId: projectId, + property, + }); + + return query.data?.values ?? []; +} diff --git a/apps/web/src/hooks/useQueryParams.ts b/apps/dashboard/src/hooks/useQueryParams.ts similarity index 100% rename from apps/web/src/hooks/useQueryParams.ts rename to apps/dashboard/src/hooks/useQueryParams.ts diff --git a/apps/dashboard/src/hooks/useRechartDataModel.ts b/apps/dashboard/src/hooks/useRechartDataModel.ts new file mode 100644 index 00000000..dd443955 --- /dev/null +++ b/apps/dashboard/src/hooks/useRechartDataModel.ts @@ -0,0 +1,41 @@ +'use client'; + +import { useMemo } from 'react'; +import type { IChartData, IChartSerieDataItem } from '@/app/_trpc/client'; +import { getChartColor } from '@/utils/theme'; + +export type IRechartPayloadItem = IChartSerieDataItem & { color: string }; + +export function useRechartDataModel(series: IChartData['series']) { + return useMemo(() => { + return ( + series[0]?.data.map(({ date }) => { + return { + date, + timestamp: new Date(date).getTime(), + ...series.reduce((acc, serie, idx) => { + return { + ...acc, + ...serie.data.reduce( + (acc2, item) => { + if (item.date === date) { + if (item.previous) { + acc2[`${idx}:prev:count`] = item.previous.value; + } + acc2[`${idx}:count`] = item.count; + acc2[`${idx}:payload`] = { + ...item, + color: getChartColor(idx), + } satisfies IRechartPayloadItem; + } + return acc2; + }, + {} as Record + ), + }; + }, {}), + }; + }) ?? [] + ); + }, [series]); +} diff --git a/apps/web/src/hooks/useRefetchActive.ts b/apps/dashboard/src/hooks/useRefetchActive.ts similarity index 100% rename from apps/web/src/hooks/useRefetchActive.ts rename to apps/dashboard/src/hooks/useRefetchActive.ts diff --git a/apps/web/src/hooks/useRouterBeforeLeave.ts b/apps/dashboard/src/hooks/useRouterBeforeLeave.ts similarity index 100% rename from apps/web/src/hooks/useRouterBeforeLeave.ts rename to apps/dashboard/src/hooks/useRouterBeforeLeave.ts diff --git a/apps/dashboard/src/hooks/useSetCookie.ts b/apps/dashboard/src/hooks/useSetCookie.ts new file mode 100644 index 00000000..58097ecd --- /dev/null +++ b/apps/dashboard/src/hooks/useSetCookie.ts @@ -0,0 +1,16 @@ +import { usePathname, useRouter } from 'next/navigation'; + +export function useSetCookie() { + const router = useRouter(); + const pathname = usePathname(); + return (key: string, value: string, path?: string) => { + fetch(`/api/cookie?${key}=${value}`).then(() => { + if (path && path !== pathname) { + router.refresh(); + router.replace(path); + } else { + router.refresh(); + } + }); + }; +} diff --git a/apps/dashboard/src/hooks/useThrottle.ts b/apps/dashboard/src/hooks/useThrottle.ts new file mode 100644 index 00000000..0ad7dd34 --- /dev/null +++ b/apps/dashboard/src/hooks/useThrottle.ts @@ -0,0 +1,15 @@ +import { useCallback, useEffect, useRef } from 'react'; +import throttle from 'lodash.throttle'; + +export function useThrottle(cb: () => void, delay: number) { + const options = { leading: true, trailing: false }; // add custom lodash options + const cbRef = useRef(cb); + // use mutable ref to make useCallback/throttle not depend on `cb` dep + useEffect(() => { + cbRef.current = cb; + }); + return useCallback( + throttle(() => cbRef.current(), delay, options), + [delay] + ); +} diff --git a/apps/dashboard/src/hooks/useVisibleSeries.ts b/apps/dashboard/src/hooks/useVisibleSeries.ts new file mode 100644 index 00000000..0fb0b209 --- /dev/null +++ b/apps/dashboard/src/hooks/useVisibleSeries.ts @@ -0,0 +1,30 @@ +'use client'; + +import { useEffect, useMemo, useState } from 'react'; +import type { IChartData } from '@/app/_trpc/client'; + +export type IVisibleSeries = ReturnType['series']; +export function useVisibleSeries(data: IChartData, limit?: number | undefined) { + const max = limit ?? 5; + const [visibleSeries, setVisibleSeries] = useState( + data?.series?.slice(0, max).map((serie) => serie.name) ?? [] + ); + + useEffect(() => { + setVisibleSeries( + data?.series?.slice(0, max).map((serie) => serie.name) ?? [] + ); + }, [data, max]); + + return useMemo(() => { + return { + series: data.series + .map((serie, index) => ({ + ...serie, + index, + })) + .filter((serie) => visibleSeries.includes(serie.name)), + setVisibleSeries, + } as const; + }, [visibleSeries, data.series]); +} diff --git a/apps/web/src/lottie/airplane.json b/apps/dashboard/src/lottie/airplane.json similarity index 100% rename from apps/web/src/lottie/airplane.json rename to apps/dashboard/src/lottie/airplane.json diff --git a/apps/web/src/lottie/ballon.json b/apps/dashboard/src/lottie/ballon.json similarity index 100% rename from apps/web/src/lottie/ballon.json rename to apps/dashboard/src/lottie/ballon.json diff --git a/apps/web/src/lottie/no-data.json b/apps/dashboard/src/lottie/no-data.json similarity index 100% rename from apps/web/src/lottie/no-data.json rename to apps/dashboard/src/lottie/no-data.json diff --git a/apps/web/src/mappings.json b/apps/dashboard/src/mappings.json similarity index 100% rename from apps/web/src/mappings.json rename to apps/dashboard/src/mappings.json diff --git a/apps/dashboard/src/middleware.ts b/apps/dashboard/src/middleware.ts new file mode 100644 index 00000000..a9af39af --- /dev/null +++ b/apps/dashboard/src/middleware.ts @@ -0,0 +1,18 @@ +import { authMiddleware } from '@clerk/nextjs'; + +// This example protects all routes including api/trpc routes +// Please edit this to allow other routes to be public as needed. +// See https://clerk.com/docs/references/nextjs/auth-middleware for more information about configuring your Middleware +export default authMiddleware({ + publicRoutes: ['/share/overview/:id', '/api/trpc(.*)'], +}); + +export const config = { + matcher: [ + '/((?!.+\\.[\\w]+$|_next).*)', + '/', + '/(api)(.*)', + '/(api|trpc)(.*)', + '/api/trpc(.*)', + ], +}; diff --git a/apps/dashboard/src/modals/AddClient.tsx b/apps/dashboard/src/modals/AddClient.tsx new file mode 100644 index 00000000..d700145e --- /dev/null +++ b/apps/dashboard/src/modals/AddClient.tsx @@ -0,0 +1,260 @@ +'use client'; + +import { useEffect } from 'react'; +import { api, handleError } from '@/app/_trpc/client'; +import { Button } from '@/components/ui/button'; +import { CheckboxInput } from '@/components/ui/checkbox'; +import { Combobox } from '@/components/ui/combobox'; +import { + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { useAppParams } from '@/hooks/useAppParams'; +import { clipboard } from '@/utils/clipboard'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { Copy, SaveIcon } from 'lucide-react'; +import Link from 'next/link'; +import { useRouter } from 'next/navigation'; +import type { SubmitHandler } from 'react-hook-form'; +import { Controller, useForm, useWatch } from 'react-hook-form'; +import { toast } from 'sonner'; +import { z } from 'zod'; + +import { popModal } from '.'; +import { ModalContent, ModalHeader } from './Modal/Container'; + +const validation = z.object({ + name: z.string().min(1), + domain: z.string().optional(), + withSecret: z.boolean().optional(), + projectId: z.string(), +}); + +type IForm = z.infer; + +export default function AddClient() { + const { organizationId, projectId } = useAppParams(); + const router = useRouter(); + const form = useForm({ + resolver: zodResolver(validation), + defaultValues: { + withSecret: false, + name: '', + domain: '', + projectId, + }, + }); + const mutation = api.client.create2.useMutation({ + onError: handleError, + onSuccess() { + toast.success('Client created'); + router.refresh(); + }, + }); + const query = api.project.list.useQuery({ + organizationId, + }); + const onSubmit: SubmitHandler = (values) => { + mutation.mutate({ + name: values.name, + domain: values.withSecret ? undefined : values.domain, + projectId: values.projectId, + organizationId, + }); + }; + + const watch = useWatch({ + control: form.control, + name: 'withSecret', + }); + + return ( + + {mutation.isSuccess ? ( + <> + + {mutation.data.clientSecret + ? 'Use your client id and secret with our SDK to send events to us. ' + : 'Use your client id with our SDK to send events to us. '} + See our{' '} + + documentation + + + } + /> +
+ + {mutation.data.clientSecret ? ( + + ) : ( +
+ +
+ {mutation.data.cors} +
+
+ You can update cors settings{' '} + + here + +
+
+ )} +
+ + + + + ) : ( + <> + +
+
+ + +
+ ( + { + field.onChange(!checked); + }} + > + This is a website + + )} + /> +
+ + +
+
+ { + return ( +
+ + { + field.onChange(value); + }} + items={ + query.data?.map((item) => ({ + value: item.id, + label: item.name, + })) ?? [] + } + placeholder="Select a project" + /> +
+ ); + }} + /> +
+ + + + + + + )} +
+ ); +} + +{ + /*
+
+ Select your framework and we'll generate a client for you. +
+
+ + + + + + +
+
*/ +} diff --git a/apps/web/src/modals/AddDashboard.tsx b/apps/dashboard/src/modals/AddDashboard.tsx similarity index 74% rename from apps/web/src/modals/AddDashboard.tsx rename to apps/dashboard/src/modals/AddDashboard.tsx index f2cd7b2e..fde7d54a 100644 --- a/apps/web/src/modals/AddDashboard.tsx +++ b/apps/dashboard/src/modals/AddDashboard.tsx @@ -1,32 +1,28 @@ +'use client'; + +import { api, handleError } from '@/app/_trpc/client'; import { ButtonContainer } from '@/components/ButtonContainer'; import { InputWithLabel } from '@/components/forms/InputWithLabel'; import { Button } from '@/components/ui/button'; -import { toast } from '@/components/ui/use-toast'; -import { useRefetchActive } from '@/hooks/useRefetchActive'; -import { api, handleError } from '@/utils/api'; +import { useAppParams } from '@/hooks/useAppParams'; import { zodResolver } from '@hookform/resolvers/zod'; +import { useRouter } from 'next/navigation'; import { useForm } from 'react-hook-form'; +import { toast } from 'sonner'; import { z } from 'zod'; import { popModal } from '.'; import { ModalContent, ModalHeader } from './Modal/Container'; -interface AddDashboardProps { - organizationSlug: string; - projectSlug: string; -} - const validator = z.object({ name: z.string().min(1, 'Required'), }); type IForm = z.infer; -export default function AddDashboard({ - // organizationSlug, - projectSlug, -}: AddDashboardProps) { - const refetch = useRefetchActive(); +export default function AddDashboard() { + const { projectId, organizationId: organizationSlug } = useAppParams(); + const router = useRouter(); const { register, handleSubmit, formState } = useForm({ resolver: zodResolver(validator), @@ -38,9 +34,8 @@ export default function AddDashboard({ const mutation = api.dashboard.create.useMutation({ onError: handleError, onSuccess() { - refetch(); - toast({ - title: 'Success', + router.refresh(); + toast('Success', { description: 'Dashboard created.', }); popModal(); @@ -49,13 +44,14 @@ export default function AddDashboard({ return ( - +
{ mutation.mutate({ name, - projectSlug, + projectId, + organizationSlug, }); })} > diff --git a/apps/web/src/modals/AddProject.tsx b/apps/dashboard/src/modals/AddProject.tsx similarity index 70% rename from apps/web/src/modals/AddProject.tsx rename to apps/dashboard/src/modals/AddProject.tsx index 2bae2661..6ee2c799 100644 --- a/apps/web/src/modals/AddProject.tsx +++ b/apps/dashboard/src/modals/AddProject.tsx @@ -1,12 +1,13 @@ +'use client'; + +import { api, handleError } from '@/app/_trpc/client'; import { ButtonContainer } from '@/components/ButtonContainer'; import { InputWithLabel } from '@/components/forms/InputWithLabel'; import { Button } from '@/components/ui/button'; -import { toast } from '@/components/ui/use-toast'; -import { useOrganizationParams } from '@/hooks/useOrganizationParams'; -import { useRefetchActive } from '@/hooks/useRefetchActive'; -import { api, handleError } from '@/utils/api'; import { zodResolver } from '@hookform/resolvers/zod'; +import { useRouter } from 'next/navigation'; import { useForm } from 'react-hook-form'; +import { toast } from 'sonner'; import { z } from 'zod'; import { popModal } from '.'; @@ -17,18 +18,18 @@ const validator = z.object({ }); type IForm = z.infer; - -export default function AddProject() { - const params = useOrganizationParams(); - const refetch = useRefetchActive(); +interface AddProjectProps { + organizationId: string; +} +export default function AddProject({ organizationId }: AddProjectProps) { + const router = useRouter(); const mutation = api.project.create.useMutation({ onError: handleError, onSuccess() { - toast({ - title: 'Success', + router.refresh(); + toast('Success', { description: 'Project created! Lets create a client for it 🤘', }); - refetch(); popModal(); }, }); @@ -46,11 +47,17 @@ export default function AddProject() { onSubmit={handleSubmit((values) => { mutation.mutate({ ...values, - organizationSlug: params.organization, + organizationId, }); })} > - +
+ +
+ + + +
+ ); +} diff --git a/apps/web/src/modals/Confirm.tsx b/apps/dashboard/src/modals/Confirm.tsx similarity index 98% rename from apps/web/src/modals/Confirm.tsx rename to apps/dashboard/src/modals/Confirm.tsx index d4c1a90d..126d17ba 100644 --- a/apps/web/src/modals/Confirm.tsx +++ b/apps/dashboard/src/modals/Confirm.tsx @@ -1,3 +1,5 @@ +'use client'; + import { ButtonContainer } from '@/components/ButtonContainer'; import { Button } from '@/components/ui/button'; diff --git a/apps/web/src/modals/EditClient.tsx b/apps/dashboard/src/modals/EditClient.tsx similarity index 73% rename from apps/web/src/modals/EditClient.tsx rename to apps/dashboard/src/modals/EditClient.tsx index 8a081ed4..9c83eafb 100644 --- a/apps/web/src/modals/EditClient.tsx +++ b/apps/dashboard/src/modals/EditClient.tsx @@ -1,20 +1,20 @@ -import { useEffect } from 'react'; +'use client'; + +import { api, handleError } from '@/app/_trpc/client'; import { ButtonContainer } from '@/components/ButtonContainer'; import { InputWithLabel } from '@/components/forms/InputWithLabel'; import { Button } from '@/components/ui/button'; -import { toast } from '@/components/ui/use-toast'; -import { useRefetchActive } from '@/hooks/useRefetchActive'; -import { api, handleError } from '@/utils/api'; import { zodResolver } from '@hookform/resolvers/zod'; +import type { IServiceClient } from '@openpanel/db'; +import { useRouter } from 'next/navigation'; import { useForm } from 'react-hook-form'; +import { toast } from 'sonner'; import { z } from 'zod'; import { popModal } from '.'; import { ModalContent, ModalHeader } from './Modal/Container'; -interface EditClientProps { - id: string; -} +type EditClientProps = IServiceClient; const validator = z.object({ id: z.string().min(1), @@ -24,35 +24,28 @@ const validator = z.object({ type IForm = z.infer; -export default function EditClient({ id }: EditClientProps) { - const refetch = useRefetchActive(); - const mutation = api.client.update.useMutation({ - onError: handleError, - onSuccess() { - toast({ - title: 'Success', - description: 'Client updated.', - }); - popModal(); - refetch(); - }, - }); - const query = api.client.get.useQuery({ id }); - const data = query.data; +export default function EditClient({ id, name, cors }: EditClientProps) { + const router = useRouter(); const { register, handleSubmit, reset, formState } = useForm({ resolver: zodResolver(validator), defaultValues: { - id: '', - name: '', - cors: '', + id, + name, + cors, }, }); - useEffect(() => { - if (data) { - reset(data); - } - }, [data, reset]); + const mutation = api.client.update.useMutation({ + onError: handleError, + onSuccess() { + reset(); + toast('Success', { + description: 'Client updated.', + }); + popModal(); + router.refresh(); + }, + }); return ( @@ -67,11 +60,13 @@ export default function EditClient({ id }: EditClientProps) { label="Name" placeholder="Name" {...register('name')} + defaultValue={name} /> diff --git a/apps/web/src/modals/EditDashboard.tsx b/apps/dashboard/src/modals/EditDashboard.tsx similarity index 66% rename from apps/web/src/modals/EditDashboard.tsx rename to apps/dashboard/src/modals/EditDashboard.tsx index dca3ac8e..5028e52d 100644 --- a/apps/web/src/modals/EditDashboard.tsx +++ b/apps/dashboard/src/modals/EditDashboard.tsx @@ -1,20 +1,20 @@ -import { useEffect } from 'react'; +'use client'; + +import { api, handleError } from '@/app/_trpc/client'; import { ButtonContainer } from '@/components/ButtonContainer'; import { InputWithLabel } from '@/components/forms/InputWithLabel'; import { Button } from '@/components/ui/button'; -import { toast } from '@/components/ui/use-toast'; -import { useRefetchActive } from '@/hooks/useRefetchActive'; -import { api, handleError } from '@/utils/api'; import { zodResolver } from '@hookform/resolvers/zod'; +import type { IServiceDashboard } from '@openpanel/db'; +import { useRouter } from 'next/navigation'; import { useForm } from 'react-hook-form'; +import { toast } from 'sonner'; import { z } from 'zod'; import { popModal } from '.'; import { ModalContent, ModalHeader } from './Modal/Container'; -interface EditDashboardProps { - id: string; -} +type EditDashboardProps = Exclude; const validator = z.object({ id: z.string().min(1), @@ -23,34 +23,27 @@ const validator = z.object({ type IForm = z.infer; -export default function EditDashboard({ id }: EditDashboardProps) { - const refetch = useRefetchActive(); - const mutation = api.dashboard.update.useMutation({ - onError: handleError, - onSuccess() { - toast({ - title: 'Success', - description: 'Dashboard updated.', - }); - popModal(); - refetch(); - }, - }); - const query = api.dashboard.get.useQuery({ id }); - const data = query.data; +export default function EditDashboard({ id, name }: EditDashboardProps) { + const router = useRouter(); const { register, handleSubmit, reset, formState } = useForm({ resolver: zodResolver(validator), defaultValues: { - id: '', - name: '', + id, + name, }, }); - useEffect(() => { - if (data) { - reset(data); - } - }, [data, reset]); + const mutation = api.dashboard.update.useMutation({ + onError: handleError, + onSuccess() { + reset(); + toast('Success', { + description: 'Dashboard updated.', + }); + popModal(); + router.refresh(); + }, + }); return ( @@ -60,7 +53,12 @@ export default function EditDashboard({ id }: EditDashboardProps) { mutation.mutate(values); })} > - + + )} + + ); +} diff --git a/apps/web/src/modals/SaveReport.tsx b/apps/dashboard/src/modals/SaveReport.tsx similarity index 72% rename from apps/web/src/modals/SaveReport.tsx rename to apps/dashboard/src/modals/SaveReport.tsx index 2327bc7e..9f2b8090 100644 --- a/apps/web/src/modals/SaveReport.tsx +++ b/apps/dashboard/src/modals/SaveReport.tsx @@ -1,18 +1,17 @@ -import { useEffect } from 'react'; +'use client'; + +import { api, handleError } from '@/app/_trpc/client'; import { ButtonContainer } from '@/components/ButtonContainer'; import { InputWithLabel } from '@/components/forms/InputWithLabel'; import { Button } from '@/components/ui/button'; import { Combobox } from '@/components/ui/combobox'; import { Label } from '@/components/ui/label'; -import { toast } from '@/components/ui/use-toast'; -import { useOrganizationParams } from '@/hooks/useOrganizationParams'; -import { useRefetchActive } from '@/hooks/useRefetchActive'; -import type { IChartInput } from '@/types'; -import { api, handleError } from '@/utils/api'; -import { strip } from '@/utils/object'; +import { useAppParams } from '@/hooks/useAppParams'; import { zodResolver } from '@hookform/resolvers/zod'; -import { useRouter } from 'next/router'; +import type { IChartInput } from '@openpanel/validation'; +import { useRouter, useSearchParams } from 'next/navigation'; import { Controller, useForm } from 'react-hook-form'; +import { toast } from 'sonner'; import { z } from 'zod'; import { popModal } from '.'; @@ -32,21 +31,22 @@ type IForm = z.infer; export default function SaveReport({ report }: SaveReportProps) { const router = useRouter(); - const { organization, project, dashboard } = useOrganizationParams(); - const refetch = useRefetchActive(); + const { organizationId: organizationSlug, projectId } = useAppParams(); + const searchParams = useSearchParams(); + const dashboardId = searchParams?.get('dashboardId') ?? undefined; + const save = api.report.save.useMutation({ onError: handleError, onSuccess(res) { - toast({ - title: 'Success', + toast('Success', { description: 'Report saved.', }); popModal(); - refetch(); - router.push({ - pathname: `/${organization}/${project}/reports/${res.id}`, - query: strip({ dashboard }), - }); + router.push( + `/${organizationSlug}/${projectId}/reports/${ + res.id + }?${searchParams?.toString()}` + ); }, }); @@ -55,7 +55,7 @@ export default function SaveReport({ report }: SaveReportProps) { resolver: zodResolver(validator), defaultValues: { name: report.name, - dashboardId: '', + dashboardId, }, }); @@ -64,15 +64,14 @@ export default function SaveReport({ report }: SaveReportProps) { onSuccess(res) { setValue('dashboardId', res.id); dashboardQuery.refetch(); - toast({ - title: 'Success', + toast('Success', { description: 'Dashboard created.', }); }, }); const dashboardQuery = api.dashboard.list.useQuery({ - projectSlug: project, + projectId, }); const dashboards = (dashboardQuery.data ?? []).map((item) => ({ @@ -80,18 +79,9 @@ export default function SaveReport({ report }: SaveReportProps) { label: item.name, })); - useEffect(() => { - if (dashboard && dashboardQuery.data) { - const match = dashboardQuery.data.find((item) => item.slug === dashboard); - if (match) { - setValue('dashboardId', match.id); - } - } - }, [dashboard, dashboardQuery]); - return ( - +
{ @@ -121,10 +111,12 @@ export default function SaveReport({ report }: SaveReportProps) { {...field} items={dashboards} placeholder="Select a dashboard" + searchable onCreate={(value) => { dashboardMutation.mutate({ - projectSlug: project, + projectId, name: value, + organizationSlug, }); }} /> diff --git a/apps/dashboard/src/modals/ShareOverviewModal.tsx b/apps/dashboard/src/modals/ShareOverviewModal.tsx new file mode 100644 index 00000000..8631aa5f --- /dev/null +++ b/apps/dashboard/src/modals/ShareOverviewModal.tsx @@ -0,0 +1,96 @@ +'use client'; + +import { api, handleError } from '@/app/_trpc/client'; +import { ButtonContainer } from '@/components/ButtonContainer'; +import { InputWithLabel } from '@/components/forms/InputWithLabel'; +import { Button } from '@/components/ui/button'; +import { Checkbox } from '@/components/ui/checkbox'; +import { useAppParams } from '@/hooks/useAppParams'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { zShareOverview } from '@openpanel/validation'; +import { useRouter } from 'next/navigation'; +import { Controller, useForm } from 'react-hook-form'; +import { toast } from 'sonner'; +import type { z } from 'zod'; + +import { popModal } from '.'; +import { ModalContent, ModalHeader } from './Modal/Container'; + +const validator = zShareOverview; + +type IForm = z.infer; + +export default function ShareOverviewModal() { + const { projectId, organizationId: organizationSlug } = useAppParams(); + const router = useRouter(); + + const { register, handleSubmit, formState, control } = useForm({ + resolver: zodResolver(validator), + defaultValues: { + public: true, + password: '', + projectId, + organizationId: organizationSlug, + }, + }); + + const mutation = api.share.shareOverview.useMutation({ + onError: handleError, + onSuccess(res) { + router.refresh(); + toast('Success', { + description: `Your overview is now ${ + res.public ? 'public' : 'private' + }`, + }); + popModal(); + }, + }); + + return ( + + + { + mutation.mutate(values); + })} + > + ( + + )} + /> + + + + + + + + ); +} diff --git a/apps/web/src/modals/index.tsx b/apps/dashboard/src/modals/index.tsx similarity index 90% rename from apps/web/src/modals/index.tsx rename to apps/dashboard/src/modals/index.tsx index 3ac0fe48..febfd5c1 100644 --- a/apps/web/src/modals/index.tsx +++ b/apps/dashboard/src/modals/index.tsx @@ -1,3 +1,5 @@ +'use client'; + import { Suspense, useEffect, useRef, useState } from 'react'; import { Loader } from 'lucide-react'; import mitt from 'mitt'; @@ -7,7 +9,7 @@ import { useOnClickOutside } from 'usehooks-ts'; import type { ConfirmProps } from './Confirm'; const Loading = () => ( -
+
); @@ -40,6 +42,12 @@ const modals = { EditReport: dynamic(() => import('./EditReport'), { loading: Loading, }), + ShareOverviewModal: dynamic(() => import('./ShareOverviewModal'), { + loading: Loading, + }), + AddReference: dynamic(() => import('./AddReference'), { + loading: Loading, + }), }; const emitter = mitt<{ @@ -65,11 +73,11 @@ interface StateItem { interface ModalWrapperProps { children: React.ReactNode; - name: ModalRoutes; - isOnTop: boolean; + name?: ModalRoutes; + isOnTop?: boolean; } -function ModalWrapper({ children, name, isOnTop }: ModalWrapperProps) { +export function ModalWrapper({ children, name, isOnTop }: ModalWrapperProps) { const ref = useRef(null); useOnClickOutside(ref, (event) => { @@ -79,7 +87,7 @@ function ModalWrapper({ children, name, isOnTop }: ModalWrapperProps) { ? !!target.closest('[data-radix-popper-content-wrapper]') : false; - if (isOnTop && !isPortal) { + if (isOnTop && !isPortal && name) { emitter.emit('pop', { name, }); @@ -154,7 +162,7 @@ export function ModalProvider() { return ( <> {!!state.length && ( -
+
)} {state.map((item, index) => { const Modal = modals[item.name]; diff --git a/apps/web/src/redux/index.ts b/apps/dashboard/src/redux/index.ts similarity index 59% rename from apps/web/src/redux/index.ts rename to apps/dashboard/src/redux/index.ts index e20c2610..47aff75d 100644 --- a/apps/web/src/redux/index.ts +++ b/apps/dashboard/src/redux/index.ts @@ -6,16 +6,19 @@ import { } from 'react-redux'; import type { TypedUseSelectorHook } from 'react-redux'; -const store = configureStore({ - reducer: { - report: reportSlice, - }, -}); +const makeStore = () => + configureStore({ + reducer: { + report: reportSlice, + }, + }); -export type RootState = ReturnType; +export type AppStore = ReturnType; -export type AppDispatch = typeof store.dispatch; +export type RootState = ReturnType; + +export type AppDispatch = AppStore['dispatch']; export const useDispatch: () => AppDispatch = useBaseDispatch; export const useSelector: TypedUseSelectorHook = useBaseSelector; -export default store; +export default makeStore; diff --git a/apps/web/src/server/api/root.ts b/apps/dashboard/src/server/api/root.ts similarity index 81% rename from apps/web/src/server/api/root.ts rename to apps/dashboard/src/server/api/root.ts index 353d8717..0b09b4b7 100644 --- a/apps/web/src/server/api/root.ts +++ b/apps/dashboard/src/server/api/root.ts @@ -4,10 +4,13 @@ import { chartRouter } from './routers/chart'; import { clientRouter } from './routers/client'; import { dashboardRouter } from './routers/dashboard'; import { eventRouter } from './routers/event'; +import { onboardingRouter } from './routers/onboarding'; import { organizationRouter } from './routers/organization'; import { profileRouter } from './routers/profile'; import { projectRouter } from './routers/project'; +import { referenceRouter } from './routers/reference'; import { reportRouter } from './routers/report'; +import { shareRouter } from './routers/share'; import { uiRouter } from './routers/ui'; import { userRouter } from './routers/user'; @@ -27,6 +30,9 @@ export const appRouter = createTRPCRouter({ event: eventRouter, profile: profileRouter, ui: uiRouter, + share: shareRouter, + onboarding: onboardingRouter, + reference: referenceRouter, }); // export type definition of API diff --git a/apps/dashboard/src/server/api/routers/chart.helpers.ts b/apps/dashboard/src/server/api/routers/chart.helpers.ts new file mode 100644 index 00000000..4fe96cf3 --- /dev/null +++ b/apps/dashboard/src/server/api/routers/chart.helpers.ts @@ -0,0 +1,355 @@ +import { getDaysOldDate } from '@/utils/date'; +import { round } from '@/utils/math'; +import { alphabetIds, NOT_SET_VALUE } from '@openpanel/constants'; +import { chQuery, convertClickhouseDateToJs, getChartSql } from '@openpanel/db'; +import type { + IChartEvent, + IChartInput, + IChartRange, + IGetChartDataInput, + IInterval, +} from '@openpanel/validation'; +import * as mathjs from 'mathjs'; +import { sort } from 'ramda'; + +export type GetChartDataResult = Awaited>; +export interface ResultItem { + label: string | null; + count: number | null; + date: string; +} + +function getEventLegend(event: IChartEvent) { + return event.displayName ?? `${event.name} (${event.id})`; +} + +function fillEmptySpotsInTimeline( + items: ResultItem[], + interval: IInterval, + startDate: string, + endDate: string +) { + const result = []; + const clonedStartDate = new Date(startDate); + const clonedEndDate = new Date(endDate); + const today = new Date(); + + if (interval === 'minute') { + clonedStartDate.setUTCSeconds(0, 0); + clonedEndDate.setUTCMinutes(clonedEndDate.getUTCMinutes() + 1, 0, 0); + } else if (interval === 'hour') { + clonedStartDate.setUTCMinutes(0, 0, 0); + clonedEndDate.setUTCMinutes(0, 0, 0); + } else { + clonedStartDate.setUTCHours(0, 0, 0, 0); + clonedEndDate.setUTCHours(0, 0, 0, 0); + } + + if (interval === 'month') { + clonedStartDate.setUTCDate(1); + clonedEndDate.setUTCDate(1); + } + + // Force if interval is month and the start date is the same month as today + const shouldForce = () => + interval === 'month' && + clonedStartDate.getUTCFullYear() === today.getUTCFullYear() && + clonedStartDate.getUTCMonth() === today.getUTCMonth(); + let prev = undefined; + while ( + shouldForce() || + clonedStartDate.getTime() <= clonedEndDate.getTime() + ) { + if (prev === clonedStartDate.getTime()) { + break; + } + prev = clonedStartDate.getTime(); + + const getYear = (date: Date) => date.getUTCFullYear(); + const getMonth = (date: Date) => date.getUTCMonth(); + const getDay = (date: Date) => date.getUTCDate(); + const getHour = (date: Date) => date.getUTCHours(); + const getMinute = (date: Date) => date.getUTCMinutes(); + + const item = items.find((item) => { + const date = convertClickhouseDateToJs(item.date); + + if (interval === 'month') { + return ( + getYear(date) === getYear(clonedStartDate) && + getMonth(date) === getMonth(clonedStartDate) + ); + } + if (interval === 'day') { + return ( + getYear(date) === getYear(clonedStartDate) && + getMonth(date) === getMonth(clonedStartDate) && + getDay(date) === getDay(clonedStartDate) + ); + } + if (interval === 'hour') { + return ( + getYear(date) === getYear(clonedStartDate) && + getMonth(date) === getMonth(clonedStartDate) && + getDay(date) === getDay(clonedStartDate) && + getHour(date) === getHour(clonedStartDate) + ); + } + if (interval === 'minute') { + return ( + getYear(date) === getYear(clonedStartDate) && + getMonth(date) === getMonth(clonedStartDate) && + getDay(date) === getDay(clonedStartDate) && + getHour(date) === getHour(clonedStartDate) && + getMinute(date) === getMinute(clonedStartDate) + ); + } + + return false; + }); + + if (item) { + result.push({ + ...item, + date: clonedStartDate.toISOString(), + }); + } else { + result.push({ + date: clonedStartDate.toISOString(), + count: 0, + label: null, + }); + } + + switch (interval) { + case 'day': { + clonedStartDate.setUTCDate(clonedStartDate.getUTCDate() + 1); + break; + } + case 'hour': { + clonedStartDate.setUTCHours(clonedStartDate.getUTCHours() + 1); + break; + } + case 'minute': { + clonedStartDate.setUTCMinutes(clonedStartDate.getUTCMinutes() + 1); + break; + } + case 'month': { + clonedStartDate.setUTCMonth(clonedStartDate.getUTCMonth() + 1); + break; + } + } + } + + return sort(function (a, b) { + return new Date(a.date).getTime() - new Date(b.date).getTime(); + }, result); +} + +export function withFormula( + { formula, events }: IChartInput, + series: GetChartDataResult +) { + if (!formula) { + return series; + } + + if (!series) { + return series; + } + + if (!series[0]) { + return series; + } + if (!series[0].data) { + return series; + } + + if (events.length === 1) { + return series.map((serie) => { + return { + ...serie, + data: serie.data.map((item) => { + serie.event.id; + const scope = { + [serie.event.id]: item?.count ?? 0, + }; + + const count = mathjs + .parse(formula) + .compile() + .evaluate(scope) as number; + + return { + ...item, + count: + Number.isNaN(count) || !Number.isFinite(count) + ? null + : round(count, 2), + }; + }), + }; + }); + } + + return [ + { + ...series[0], + data: series[0].data.map((item, dIndex) => { + const scope = series.reduce((acc, item) => { + return { + ...acc, + [item.event.id]: item.data[dIndex]?.count ?? 0, + }; + }, {}); + + const count = mathjs.parse(formula).compile().evaluate(scope) as number; + return { + ...item, + count: + Number.isNaN(count) || !Number.isFinite(count) + ? null + : round(count, 2), + }; + }), + }, + ]; +} + +export async function getChartData(payload: IGetChartDataInput) { + let result = await chQuery(getChartSql(payload)); + + if (result.length === 0 && payload.breakdowns.length > 0) { + result = await chQuery( + getChartSql({ + ...payload, + breakdowns: [], + }) + ); + } + + // group by sql label + const series = result.reduce( + (acc, item) => { + // item.label can be null when using breakdowns on a property + // that doesn't exist on all events + const label = item.label?.trim() || NOT_SET_VALUE; + if (label) { + if (acc[label]) { + acc[label]?.push(item); + } else { + acc[label] = [item]; + } + } + + return { + ...acc, + }; + }, + {} as Record + ); + + return Object.keys(series).map((key) => { + // If we have breakdowns, we want to use the breakdown key as the legend + // But only if it successfully broke it down, otherwise we use the getEventLabel + const isBreakdown = + payload.breakdowns.length && !alphabetIds.includes(key as 'A'); + const serieName = isBreakdown ? key : getEventLegend(payload.event); + const data = + payload.chartType === 'area' || + payload.chartType === 'linear' || + payload.chartType === 'histogram' || + payload.chartType === 'metric' || + payload.chartType === 'pie' || + payload.chartType === 'bar' + ? fillEmptySpotsInTimeline( + series[key] ?? [], + payload.interval, + payload.startDate, + payload.endDate + ).map((item) => { + return { + label: serieName, + count: item.count ? round(item.count) : null, + date: new Date(item.date).toISOString(), + }; + }) + : (series[key] ?? []).map((item) => ({ + label: item.label, + count: item.count ? round(item.count) : null, + date: new Date(item.date).toISOString(), + })); + + return { + name: serieName, + event: payload.event, + data, + }; + }); +} + +export function getDatesFromRange(range: IChartRange) { + if (range === 'today') { + const startDate = new Date(); + const endDate = new Date(); + startDate.setUTCHours(0, 0, 0, 0); + endDate.setUTCHours(23, 59, 59, 999); + + return { + startDate: startDate.toUTCString(), + endDate: endDate.toUTCString(), + }; + } + + if (range === '30min' || range === '1h') { + const startDate = new Date( + Date.now() - 1000 * 60 * (range === '30min' ? 30 : 60) + ).toUTCString(); + const endDate = new Date().toUTCString(); + + return { + startDate, + endDate, + }; + } + + let days = 1; + + if (range === '24h') { + const startDate = getDaysOldDate(days); + const endDate = new Date(); + return { + startDate: startDate.toUTCString(), + endDate: endDate.toUTCString(), + }; + } else if (range === '7d') { + days = 7; + } else if (range === '14d') { + days = 14; + } else if (range === '1m') { + days = 30; + } else if (range === '3m') { + days = 90; + } else if (range === '6m') { + days = 180; + } else if (range === '1y') { + days = 365; + } + + const startDate = getDaysOldDate(days); + startDate.setUTCHours(0, 0, 0, 0); + const endDate = new Date(); + endDate.setUTCHours(23, 59, 59, 999); + return { + startDate: startDate.toUTCString(), + endDate: endDate.toUTCString(), + }; +} + +export function getChartStartEndDate( + input: Pick +) { + return input.startDate && input.endDate + ? { startDate: input.startDate, endDate: input.endDate } + : getDatesFromRange(input.range); +} diff --git a/apps/dashboard/src/server/api/routers/chart.ts b/apps/dashboard/src/server/api/routers/chart.ts new file mode 100644 index 00000000..b187493f --- /dev/null +++ b/apps/dashboard/src/server/api/routers/chart.ts @@ -0,0 +1,511 @@ +import { + createTRPCRouter, + protectedProcedure, + publicProcedure, +} from '@/server/api/trpc'; +import { average, max, min, round, sum } from '@/utils/math'; +import { + chQuery, + createSqlBuilder, + formatClickhouseDate, + getEventFiltersWhereClause, +} from '@openpanel/db'; +import { zChartInput } from '@openpanel/validation'; +import type { IChartEvent, IChartInput } from '@openpanel/validation'; +import { flatten, map, pipe, prop, repeat, reverse, sort, uniq } from 'ramda'; +import { z } from 'zod'; + +import { + getChartData, + getChartStartEndDate, + getDatesFromRange, + withFormula, +} from './chart.helpers'; + +async function getFunnelData({ projectId, ...payload }: IChartInput) { + const { startDate, endDate } = getChartStartEndDate(payload); + + if (payload.events.length === 0) { + return { + totalSessions: 0, + steps: [], + }; + } + + const funnels = payload.events.map((event) => { + const { sb, getWhere } = createSqlBuilder(); + sb.where = getEventFiltersWhereClause(event.filters); + sb.where.name = `name = '${event.name}'`; + return getWhere().replace('WHERE ', ''); + }); + + const innerSql = `SELECT + session_id, + windowFunnel(6048000000000000,'strict_increase')(toUnixTimestamp(created_at), ${funnels.join(', ')}) AS level + FROM events + WHERE (project_id = '${projectId}' AND created_at >= '${formatClickhouseDate(startDate)}') AND (created_at <= '${formatClickhouseDate(endDate)}') + GROUP BY session_id;`; + + const sql = `SELECT level, count() AS count FROM (${innerSql}) GROUP BY level ORDER BY level DESC;`; + + const [funnelRes, sessionRes] = await Promise.all([ + chQuery<{ level: number; count: number }>(sql), + chQuery<{ count: number }>( + `SELECT count(name) as count FROM events WHERE project_id = '${projectId}' AND name = 'session_start' AND (created_at >= '${formatClickhouseDate(startDate)}') AND (created_at <= '${formatClickhouseDate(endDate)}')` + ), + ]); + + console.log('Funnel SQL: ', sql); + + if (funnelRes[0]?.level !== payload.events.length) { + funnelRes.unshift({ + level: payload.events.length, + count: 0, + }); + } + + const totalSessions = sessionRes[0]?.count ?? 0; + const filledFunnelRes = funnelRes.reduce( + (acc, item, index) => { + const diff = + index !== 0 ? (acc[acc.length - 1]?.level ?? 0) - item.level : 1; + + if (diff > 1) { + acc.push( + ...reverse( + repeat({}, diff - 1).map((_, index) => ({ + count: acc[acc.length - 1]?.count ?? 0, + level: item.level + index + 1, + })) + ) + ); + } + + return [ + ...acc, + { + count: item.count + (acc[acc.length - 1]?.count ?? 0), + level: item.level, + }, + ]; + }, + [] as typeof funnelRes + ); + + const steps = reverse(filledFunnelRes) + .filter((item) => item.level !== 0) + .reduce( + (acc, item, index, list) => { + const prev = list[index - 1] ?? { count: totalSessions }; + return [ + ...acc, + { + event: payload.events[item.level - 1]!, + before: prev.count, + current: item.count, + dropoff: { + count: prev.count - item.count, + percent: 100 - (item.count / prev.count) * 100, + }, + percent: (item.count / totalSessions) * 100, + prevPercent: (prev.count / totalSessions) * 100, + }, + ]; + }, + [] as { + event: IChartEvent; + before: number; + current: number; + dropoff: { + count: number; + percent: number; + }; + percent: number; + prevPercent: number; + }[] + ); + + return { + totalSessions, + steps, + }; +} + +type PreviousValue = { + value: number; + diff: number | null; + state: 'positive' | 'negative' | 'neutral'; +} | null; + +interface Metrics { + sum: number; + average: number; + min: number; + max: number; + previous: { + sum: PreviousValue; + average: PreviousValue; + min: PreviousValue; + max: PreviousValue; + }; +} + +export interface IChartSerie { + name: string; + event: IChartEvent; + metrics: Metrics; + data: { + date: string; + count: number; + label: string | null; + previous: PreviousValue; + }[]; +} + +export interface FinalChart { + events: IChartInput['events']; + series: IChartSerie[]; + metrics: Metrics; +} + +export const chartRouter = createTRPCRouter({ + events: protectedProcedure + .input(z.object({ projectId: z.string() })) + .query(async ({ input: { projectId } }) => { + const events = await chQuery<{ name: string }>( + `SELECT DISTINCT name FROM events WHERE project_id = '${projectId}'` + ); + + return [ + { + name: '*', + }, + ...events, + ]; + }), + + properties: protectedProcedure + .input(z.object({ event: z.string().optional(), projectId: z.string() })) + .query(async ({ input: { projectId, event } }) => { + const events = await chQuery<{ keys: string[] }>( + `SELECT distinct mapKeys(properties) as keys from events where ${ + event && event !== '*' ? `name = '${event}' AND ` : '' + } project_id = '${projectId}';` + ); + + const properties = events + .flatMap((event) => event.keys) + .map((item) => item.replace(/\.([0-9]+)\./g, '.*.')) + .map((item) => item.replace(/\.([0-9]+)/g, '[*]')) + .map((item) => `properties.${item}`); + + properties.push( + 'name', + 'path', + 'referrer', + 'referrer_name', + 'duration', + 'created_at', + 'country', + 'city', + 'region', + 'os', + 'os_version', + 'browser', + 'browser_version', + 'device', + 'brand', + 'model' + ); + + return pipe( + sort((a, b) => a.length - b.length), + uniq + )(properties); + }), + + // TODO: Make this private + values: publicProcedure + .input( + z.object({ + event: z.string(), + property: z.string(), + projectId: z.string(), + }) + ) + .query(async ({ input: { event, property, projectId } }) => { + const { sb, getSql } = createSqlBuilder(); + sb.where.project_id = `project_id = '${projectId}'`; + if (event !== '*') { + sb.where.event = `name = '${event}'`; + } + if (property.startsWith('properties.')) { + sb.select.values = `distinct mapValues(mapExtractKeyLike(properties, '${property + .replace(/^properties\./, '') + .replace('.*.', '.%.')}')) as values`; + } else { + sb.select.values = `${property} as values`; + } + + const events = await chQuery<{ values: string[] }>(getSql()); + + const values = pipe( + (data: typeof events) => map(prop('values'), data), + flatten, + uniq, + sort((a, b) => a.length - b.length) + )(events); + + return { + values, + }; + }), + + funnel: publicProcedure.input(zChartInput).query(async ({ input }) => { + return getFunnelData(input); + }), + + // TODO: Make this private + chart: publicProcedure.input(zChartInput).query(async ({ input }) => { + const { startDate, endDate } = getChartStartEndDate(input); + let diff = 0; + + switch (input.range) { + case '30min': { + diff = 1000 * 60 * 30; + break; + } + case '1h': { + diff = 1000 * 60 * 60; + break; + } + case '24h': + case 'today': { + diff = 1000 * 60 * 60 * 24; + break; + } + case '7d': { + diff = 1000 * 60 * 60 * 24 * 7; + break; + } + case '14d': { + diff = 1000 * 60 * 60 * 24 * 14; + break; + } + case '1m': { + diff = 1000 * 60 * 60 * 24 * 30; + break; + } + case '3m': { + diff = 1000 * 60 * 60 * 24 * 90; + break; + } + case '6m': { + diff = 1000 * 60 * 60 * 24 * 180; + break; + } + } + + const promises = [getSeriesFromEvents(input)]; + + if (input.previous) { + promises.push( + getSeriesFromEvents({ + ...input, + ...{ + startDate: new Date( + new Date(startDate).getTime() - diff + ).toISOString(), + endDate: new Date(new Date(endDate).getTime() - diff).toISOString(), + }, + }) + ); + } + + const result = await Promise.all(promises); + const series = result[0]!; + const previousSeries = result[1]; + + const final: FinalChart = { + events: input.events, + series: series.map((serie, index) => { + const previousSerie = previousSeries?.[index]; + const metrics = { + sum: sum(serie.data.map((item) => item.count)), + average: round(average(serie.data.map((item) => item.count)), 2), + min: min(serie.data.map((item) => item.count)), + max: max(serie.data.map((item) => item.count)), + }; + + return { + name: serie.name, + event: serie.event, + metrics: { + ...metrics, + previous: { + sum: getPreviousMetric( + metrics.sum, + previousSerie + ? sum(previousSerie?.data.map((item) => item.count)) + : null + ), + average: getPreviousMetric( + metrics.average, + previousSerie + ? round( + average(previousSerie?.data.map((item) => item.count)), + 2 + ) + : null + ), + min: getPreviousMetric( + metrics.sum, + previousSerie + ? min(previousSerie?.data.map((item) => item.count)) + : null + ), + max: getPreviousMetric( + metrics.sum, + previousSerie + ? max(previousSerie?.data.map((item) => item.count)) + : null + ), + }, + }, + data: serie.data.map((item, index) => ({ + date: item.date, + count: item.count ?? 0, + label: item.label, + previous: previousSerie?.data[index] + ? getPreviousMetric( + item.count ?? 0, + previousSerie?.data[index]?.count ?? null + ) + : null, + })), + }; + }), + metrics: { + sum: 0, + average: 0, + min: 0, + max: 0, + previous: { + sum: null, + average: null, + min: null, + max: null, + }, + }, + }; + + final.metrics.sum = sum(final.series.map((item) => item.metrics.sum)); + final.metrics.average = round( + average(final.series.map((item) => item.metrics.average)), + 2 + ); + final.metrics.min = min(final.series.map((item) => item.metrics.min)); + final.metrics.max = max(final.series.map((item) => item.metrics.max)); + final.metrics.previous = { + sum: getPreviousMetric( + sum(final.series.map((item) => item.metrics.sum)), + sum(final.series.map((item) => item.metrics.previous.sum?.value ?? 0)) + ), + average: getPreviousMetric( + round(average(final.series.map((item) => item.metrics.average)), 2), + round( + average( + final.series.map( + (item) => item.metrics.previous.average?.value ?? 0 + ) + ), + 2 + ) + ), + min: getPreviousMetric( + min(final.series.map((item) => item.metrics.min)), + min(final.series.map((item) => item.metrics.previous.min?.value ?? 0)) + ), + max: getPreviousMetric( + max(final.series.map((item) => item.metrics.max)), + max(final.series.map((item) => item.metrics.previous.max?.value ?? 0)) + ), + }; + + final.series = final.series.sort((a, b) => { + if (input.chartType === 'linear') { + const sumA = a.data.reduce((acc, item) => acc + (item.count ?? 0), 0); + const sumB = b.data.reduce((acc, item) => acc + (item.count ?? 0), 0); + return sumB - sumA; + } else { + return b.metrics[input.metric] - a.metrics[input.metric]; + } + }); + + // await new Promise((res) => { + // setTimeout(() => { + // res(); + // }, 100); + // }); + return final; + }), +}); + +function getPreviousMetric( + current: number, + previous: number | null +): PreviousValue { + if (previous === null) { + return null; + } + + const diff = round( + ((current > previous + ? current / previous + : current < previous + ? previous / current + : 0) - + 1) * + 100, + 1 + ); + + return { + diff: + Number.isNaN(diff) || !Number.isFinite(diff) || current === previous + ? null + : diff, + state: + current > previous + ? 'positive' + : current < previous + ? 'negative' + : 'neutral', + value: previous, + }; +} + +async function getSeriesFromEvents(input: IChartInput) { + const { startDate, endDate } = + input.startDate && input.endDate + ? { + startDate: input.startDate, + endDate: input.endDate, + } + : getDatesFromRange(input.range); + + const series = ( + await Promise.all( + input.events.map(async (event) => + getChartData({ + ...input, + startDate, + endDate, + event, + }) + ) + ) + ).flat(); + + return withFormula(input, series); +} diff --git a/apps/web/src/server/api/routers/client.ts b/apps/dashboard/src/server/api/routers/client.ts similarity index 63% rename from apps/web/src/server/api/routers/client.ts rename to apps/dashboard/src/server/api/routers/client.ts index 3b51d7ef..17698c57 100644 --- a/apps/web/src/server/api/routers/client.ts +++ b/apps/dashboard/src/server/api/routers/client.ts @@ -1,22 +1,20 @@ import { randomUUID } from 'crypto'; import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc'; import { db } from '@/server/db'; -import { hashPassword } from '@/server/services/hash.service'; -import { getOrganizationBySlug } from '@/server/services/organization.service'; +import { hashPassword } from '@openpanel/common'; import { z } from 'zod'; export const clientRouter = createTRPCRouter({ list: protectedProcedure .input( z.object({ - organizationSlug: z.string(), + organizationId: z.string(), }) ) - .query(async ({ input }) => { - const organization = await getOrganizationBySlug(input.organizationSlug); + .query(async ({ input: { organizationId } }) => { return db.client.findMany({ where: { - organization_id: organization.id, + organization_slug: organizationId, }, include: { project: true, @@ -41,6 +39,7 @@ export const clientRouter = createTRPCRouter({ z.object({ id: z.string(), name: z.string(), + cors: z.string(), }) ) .mutation(({ input }) => { @@ -50,6 +49,7 @@ export const clientRouter = createTRPCRouter({ }, data: { name: input.name, + cors: input.cors, }, }); }), @@ -58,16 +58,15 @@ export const clientRouter = createTRPCRouter({ z.object({ name: z.string(), projectId: z.string(), - organizationSlug: z.string(), + organizationId: z.string(), withCors: z.boolean().default(true), }) ) .mutation(async ({ input }) => { - const organization = await getOrganizationBySlug(input.organizationSlug); const secret = randomUUID(); const client = await db.client.create({ data: { - organization_id: organization.id, + organization_slug: input.organizationId, project_id: input.projectId, name: input.name, secret: input.withCors ? null : await hashPassword(secret), @@ -80,6 +79,33 @@ export const clientRouter = createTRPCRouter({ cors: client.cors, }; }), + create2: protectedProcedure + .input( + z.object({ + name: z.string(), + projectId: z.string(), + organizationId: z.string(), + domain: z.string().nullish(), + }) + ) + .mutation(async ({ input }) => { + const secret = randomUUID(); + const client = await db.client.create({ + data: { + organization_slug: input.organizationId, + project_id: input.projectId, + name: input.name, + secret: input.domain ? undefined : await hashPassword(secret), + cors: input.domain || undefined, + }, + }); + + return { + clientSecret: input.domain ? null : secret, + clientId: client.id, + cors: client.cors, + }; + }), remove: protectedProcedure .input( z.object({ diff --git a/apps/web/src/server/api/routers/dashboard.ts b/apps/dashboard/src/server/api/routers/dashboard.ts similarity index 52% rename from apps/web/src/server/api/routers/dashboard.ts rename to apps/dashboard/src/server/api/routers/dashboard.ts index 32b5788b..f093024f 100644 --- a/apps/web/src/server/api/routers/dashboard.ts +++ b/apps/dashboard/src/server/api/routers/dashboard.ts @@ -1,74 +1,74 @@ import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc'; -import { db } from '@/server/db'; -import { getDashboardBySlug } from '@/server/services/dashboard.service'; -import { getProjectBySlug } from '@/server/services/project.service'; -import { slug } from '@/utils/slug'; -import { Prisma } from '@prisma/client'; +import { db, getId } from '@/server/db'; +import type { Prisma } from '@openpanel/db'; import { PrismaError } from 'prisma-error-enum'; import { z } from 'zod'; export const dashboardRouter = createTRPCRouter({ get: protectedProcedure - .input( - z - .object({ - slug: z.string(), - }) - .or(z.object({ id: z.string() })) - ) + .input(z.object({ id: z.string() })) .query(async ({ input }) => { - if ('id' in input) { - return db.dashboard.findUnique({ - where: { - id: input.id, - }, - }); - } else { - return getDashboardBySlug(input.slug); - } + return db.dashboard.findUnique({ + where: { + id: input.id, + }, + }); }), list: protectedProcedure .input( z .object({ - projectSlug: z.string(), + projectId: z.string(), }) .or( z.object({ - projectId: z.string(), + organizationId: z.string(), }) ) ) .query(async ({ input }) => { - let projectId = null; if ('projectId' in input) { - projectId = input.projectId; + return db.dashboard.findMany({ + where: { + project_id: input.projectId, + }, + orderBy: { + createdAt: 'desc', + }, + include: { + project: true, + }, + }); } else { - projectId = (await getProjectBySlug(input.projectSlug)).id; + return db.dashboard.findMany({ + where: { + project: { + organization_slug: input.organizationId, + }, + }, + include: { + project: true, + }, + orderBy: { + createdAt: 'desc', + }, + }); } - - return db.dashboard.findMany({ - where: { - project_id: projectId, - }, - orderBy: { - createdAt: 'desc', - }, - }); }), create: protectedProcedure .input( z.object({ name: z.string(), - projectSlug: z.string(), + projectId: z.string(), + organizationSlug: z.string(), }) ) - .mutation(async ({ input: { projectSlug, name } }) => { - const project = await getProjectBySlug(projectSlug); + .mutation(async ({ input: { organizationSlug, projectId, name } }) => { return db.dashboard.create({ data: { - slug: slug(name), - project_id: project.id, + id: await getId('dashboard', name), + project_id: projectId, + organization_slug: organizationSlug, name, }, }); @@ -94,17 +94,28 @@ export const dashboardRouter = createTRPCRouter({ .input( z.object({ id: z.string(), + forceDelete: z.boolean().optional(), }) ) - .mutation(async ({ input: { id } }) => { + .mutation(async ({ input: { id, forceDelete } }) => { try { + if (forceDelete) { + await db.report.deleteMany({ + where: { + dashboard_id: id, + }, + }); + } await db.dashboard.delete({ where: { id, }, }); - } catch (error) { - if (error instanceof Prisma.PrismaClientKnownRequestError) { + } catch (e) { + // Below does not work... + // error instanceof Prisma.PrismaClientKnownRequestError + if (typeof e === 'object' && e && 'code' in e) { + const error = e as Prisma.PrismaClientKnownRequestError; switch (error.code) { case PrismaError.ForeignConstraintViolation: throw new Error( diff --git a/apps/dashboard/src/server/api/routers/event.ts b/apps/dashboard/src/server/api/routers/event.ts new file mode 100644 index 00000000..fd027d7f --- /dev/null +++ b/apps/dashboard/src/server/api/routers/event.ts @@ -0,0 +1,28 @@ +import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc'; +import { db } from '@openpanel/db'; +import { z } from 'zod'; + +export const eventRouter = createTRPCRouter({ + updateEventMeta: protectedProcedure + .input( + z.object({ + projectId: z.string(), + name: z.string(), + icon: z.string().optional(), + color: z.string().optional(), + conversion: z.boolean().optional(), + }) + ) + .mutation(({ input: { projectId, name, icon, color, conversion } }) => { + return db.eventMeta.upsert({ + where: { + name_project_id: { + name, + project_id: projectId, + }, + }, + create: { project_id: projectId, name, icon, color, conversion }, + update: { icon, color, conversion }, + }); + }), +}); diff --git a/apps/dashboard/src/server/api/routers/onboarding.ts b/apps/dashboard/src/server/api/routers/onboarding.ts new file mode 100644 index 00000000..cf60c687 --- /dev/null +++ b/apps/dashboard/src/server/api/routers/onboarding.ts @@ -0,0 +1,39 @@ +import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc'; +import { clerkClient } from '@clerk/nextjs'; +import { db } from '@openpanel/db'; +import { z } from 'zod'; + +export const onboardingRouter = createTRPCRouter({ + organziation: protectedProcedure + .input( + z.object({ + organization: z.string(), + project: z.string().optional(), + }) + ) + .mutation(async ({ input, ctx }) => { + const org = await clerkClient.organizations.createOrganization({ + name: input.organization, + createdBy: ctx.session.userId, + }); + + if (org.slug && input.project) { + const project = await db.project.create({ + data: { + name: input.project, + organization_slug: org.slug, + }, + }); + + return { + project, + organization: org, + }; + } + + return { + project: null, + organization: org, + }; + }), +}); diff --git a/apps/dashboard/src/server/api/routers/organization.ts b/apps/dashboard/src/server/api/routers/organization.ts new file mode 100644 index 00000000..eaae290c --- /dev/null +++ b/apps/dashboard/src/server/api/routers/organization.ts @@ -0,0 +1,49 @@ +import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc'; +import { clerkClient } from '@clerk/nextjs'; +import { getOrganizationBySlug } from '@openpanel/db'; +import { zInviteUser } from '@openpanel/validation'; +import { z } from 'zod'; + +export const organizationRouter = createTRPCRouter({ + list: protectedProcedure.query(() => { + return clerkClient.organizations.getOrganizationList(); + }), + // first: protectedProcedure.query(() => getCurrentOrganization()), + get: protectedProcedure + .input( + z.object({ + id: z.string(), + }) + ) + .query(({ input }) => { + return getOrganizationBySlug(input.id); + }), + update: protectedProcedure + .input( + z.object({ + id: z.string(), + name: z.string(), + }) + ) + .mutation(({ input }) => { + return clerkClient.organizations.updateOrganization(input.id, { + name: input.name, + }); + }), + inviteUser: protectedProcedure + .input(zInviteUser) + .mutation(async ({ input, ctx }) => { + const organization = await getOrganizationBySlug(input.organizationSlug); + + if (!organization) { + throw new Error('Organization not found'); + } + + return clerkClient.organizations.createOrganizationInvitation({ + organizationId: organization.id, + emailAddress: input.email, + role: input.role, + inviterUserId: ctx.session.userId, + }); + }), +}); diff --git a/apps/dashboard/src/server/api/routers/profile.ts b/apps/dashboard/src/server/api/routers/profile.ts new file mode 100644 index 00000000..b139cb02 --- /dev/null +++ b/apps/dashboard/src/server/api/routers/profile.ts @@ -0,0 +1,122 @@ +import { + createTRPCRouter, + protectedProcedure, + publicProcedure, +} from '@/server/api/trpc'; +import { db } from '@/server/db'; +import { chQuery, createSqlBuilder } from '@openpanel/db'; +import { flatten, map, pipe, prop, sort, uniq } from 'ramda'; +import { z } from 'zod'; + +export const profileRouter = createTRPCRouter({ + list: protectedProcedure + .input( + z.object({ + query: z.string().nullable(), + projectId: z.string(), + take: z.number().default(100), + skip: z.number().default(0), + }) + ) + .query(async ({ input: { take, skip, projectId, query } }) => { + return db.profile.findMany({ + take, + skip, + where: { + project_id: projectId, + ...(query + ? { + OR: [ + { + first_name: { + contains: query, + mode: 'insensitive', + }, + }, + { + last_name: { + contains: query, + mode: 'insensitive', + }, + }, + { + email: { + contains: query, + mode: 'insensitive', + }, + }, + ], + } + : {}), + }, + orderBy: { + createdAt: 'desc', + }, + }); + }), + get: protectedProcedure + .input( + z.object({ + id: z.string(), + }) + ) + .query(async ({ input: { id } }) => { + return db.profile.findUniqueOrThrow({ + where: { + id, + }, + }); + }), + properties: protectedProcedure + .input(z.object({ projectId: z.string() })) + .query(async ({ input: { projectId } }) => { + const events = await chQuery<{ keys: string[] }>( + `SELECT distinct mapKeys(properties) as keys from profiles where project_id = '${projectId}';` + ); + + const properties = events + .flatMap((event) => event.keys) + .map((item) => item.replace(/\.([0-9]+)\./g, '.*.')) + .map((item) => item.replace(/\.([0-9]+)/g, '[*]')) + .map((item) => `properties.${item}`); + + properties.push('external_id', 'first_name', 'last_name', 'email'); + + return pipe( + sort((a, b) => a.length - b.length), + uniq + )(properties); + }), + values: publicProcedure + .input( + z.object({ + property: z.string(), + projectId: z.string(), + }) + ) + .query(async ({ input: { property, projectId } }) => { + const { sb, getSql } = createSqlBuilder(); + sb.from = 'profiles'; + sb.where.project_id = `project_id = '${projectId}'`; + if (property.startsWith('properties.')) { + sb.select.values = `distinct mapValues(mapExtractKeyLike(properties, '${property + .replace(/^properties\./, '') + .replace('.*.', '.%.')}')) as values`; + } else { + sb.select.values = `${property} as values`; + } + + const profiles = await chQuery<{ values: string[] }>(getSql()); + + const values = pipe( + (data: typeof profiles) => map(prop('values'), data), + flatten, + uniq, + sort((a, b) => a.length - b.length) + )(profiles); + + return { + values, + }; + }), +}); diff --git a/apps/web/src/server/api/routers/project.ts b/apps/dashboard/src/server/api/routers/project.ts similarity index 60% rename from apps/web/src/server/api/routers/project.ts rename to apps/dashboard/src/server/api/routers/project.ts index 975a77fd..9b8f87d3 100644 --- a/apps/web/src/server/api/routers/project.ts +++ b/apps/dashboard/src/server/api/routers/project.ts @@ -1,40 +1,34 @@ import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc'; -import { db } from '@/server/db'; -import { getOrganizationBySlug } from '@/server/services/organization.service'; -import { getProjectBySlug } from '@/server/services/project.service'; +import { db, getId } from '@/server/db'; +import { slug } from '@/utils/slug'; import { z } from 'zod'; export const projectRouter = createTRPCRouter({ list: protectedProcedure .input( z.object({ - organizationSlug: z.string(), + organizationId: z.string().nullable(), }) ) - .query(async ({ input }) => { - const organization = await getOrganizationBySlug(input.organizationSlug); + .query(async ({ input: { organizationId } }) => { + if (organizationId === null) return []; + return db.project.findMany({ where: { - organization_id: organization.id, + organization_slug: organizationId, }, }); }), get: protectedProcedure .input( - z - .object({ - id: z.string(), - }) - .or(z.object({ slug: z.string() })) + z.object({ + id: z.string(), + }) ) - .query(({ input }) => { - if ('slug' in input) { - return getProjectBySlug(input.slug); - } - + .query(({ input: { id } }) => { return db.project.findUniqueOrThrow({ where: { - id: input.id, + id, }, }); }), @@ -58,15 +52,15 @@ export const projectRouter = createTRPCRouter({ create: protectedProcedure .input( z.object({ - name: z.string(), - organizationSlug: z.string(), + name: z.string().min(1), + organizationId: z.string(), }) ) .mutation(async ({ input }) => { - const organization = await getOrganizationBySlug(input.organizationSlug); return db.project.create({ data: { - organization_id: organization.id, + id: await getId('project', input.name), + organization_slug: input.organizationId, name: input.name, }, }); diff --git a/apps/dashboard/src/server/api/routers/reference.ts b/apps/dashboard/src/server/api/routers/reference.ts new file mode 100644 index 00000000..70d8c467 --- /dev/null +++ b/apps/dashboard/src/server/api/routers/reference.ts @@ -0,0 +1,53 @@ +import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc'; +import { db, getReferences } from '@openpanel/db'; +import { zCreateReference, zRange } from '@openpanel/validation'; +import { z } from 'zod'; + +import { getChartStartEndDate } from './chart.helpers'; + +export const referenceRouter = createTRPCRouter({ + create: protectedProcedure + .input(zCreateReference) + .mutation( + async ({ input: { title, description, datetime, projectId } }) => { + return db.reference.create({ + data: { + title, + description, + project_id: projectId, + date: new Date(datetime), + }, + }); + } + ), + delete: protectedProcedure + .input(z.object({ id: z.string() })) + .mutation(async ({ input: { id } }) => { + return db.reference.delete({ + where: { + id, + }, + }); + }), + getChartReferences: protectedProcedure + .input( + z.object({ + projectId: z.string(), + startDate: z.string().nullish(), + endDate: z.string().nullish(), + range: zRange, + }) + ) + .query(({ input: { projectId, ...input } }) => { + const { startDate, endDate } = getChartStartEndDate(input); + return getReferences({ + where: { + project_id: projectId, + date: { + gte: new Date(startDate), + lte: new Date(endDate), + }, + }, + }); + }), +}); diff --git a/apps/web/src/server/api/routers/report.ts b/apps/dashboard/src/server/api/routers/report.ts similarity index 50% rename from apps/web/src/server/api/routers/report.ts rename to apps/dashboard/src/server/api/routers/report.ts index be8afb1e..240aae2d 100644 --- a/apps/web/src/server/api/routers/report.ts +++ b/apps/dashboard/src/server/api/routers/report.ts @@ -1,57 +1,9 @@ import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc'; import { db } from '@/server/db'; -import { getDashboardBySlug } from '@/server/services/dashboard.service'; -import { getProjectBySlug } from '@/server/services/project.service'; -import type { - IChartBreakdown, - IChartEvent, - IChartEventFilter, - IChartInput, - IChartRange, -} from '@/types'; -import { alphabetIds, timeRanges } from '@/utils/constants'; -import { zChartInput } from '@/utils/validation'; -import type { Report as DbReport } from '@prisma/client'; +import { transformReport } from '@openpanel/db'; +import { zChartInput } from '@openpanel/validation'; import { z } from 'zod'; -function transformFilter( - filter: Partial, - index: number -): IChartEventFilter { - return { - id: filter.id ?? alphabetIds[index]!, - name: filter.name ?? 'Unknown Filter', - operator: filter.operator ?? 'is', - value: - typeof filter.value === 'string' ? [filter.value] : filter.value ?? [], - }; -} - -function transformEvent( - event: Partial, - index: number -): IChartEvent { - return { - segment: event.segment ?? 'event', - filters: (event.filters ?? []).map(transformFilter), - id: event.id ?? alphabetIds[index]!, - name: event.name || 'unknown_event', - displayName: event.displayName, - }; -} - -function transformReport(report: DbReport): IChartInput & { id: string } { - return { - id: report.id, - events: (report.events as IChartEvent[]).map(transformEvent), - breakdowns: report.breakdowns as IChartBreakdown[], - chartType: report.chart_type, - interval: report.interval, - name: report.name || 'Untitled', - range: report.range as IChartRange ?? timeRanges['1m'], - }; -} - export const reportRouter = createTRPCRouter({ get: protectedProcedure .input( @@ -71,22 +23,27 @@ export const reportRouter = createTRPCRouter({ list: protectedProcedure .input( z.object({ - projectSlug: z.string(), - dashboardSlug: z.string(), + projectId: z.string(), + dashboardId: z.string(), }) ) - .query(async ({ input: { projectSlug, dashboardSlug } }) => { - const project = await getProjectBySlug(projectSlug); - const dashboard = await getDashboardBySlug(dashboardSlug); - const reports = await db.report.findMany({ - where: { - project_id: project.id, - dashboard_id: dashboard.id, - }, - orderBy: { - createdAt: 'desc', - }, - }); + .query(async ({ input: { projectId, dashboardId } }) => { + const [dashboard, reports] = await db.$transaction([ + db.dashboard.findUniqueOrThrow({ + where: { + id: dashboardId, + }, + }), + db.report.findMany({ + where: { + project_id: projectId, + dashboard_id: dashboardId, + }, + orderBy: { + createdAt: 'desc', + }, + }), + ]); return { reports: reports.map(transformReport), @@ -96,7 +53,7 @@ export const reportRouter = createTRPCRouter({ save: protectedProcedure .input( z.object({ - report: zChartInput, + report: zChartInput.omit({ projectId: true }), dashboardId: z.string(), }) ) @@ -115,7 +72,9 @@ export const reportRouter = createTRPCRouter({ interval: report.interval, breakdowns: report.breakdowns, chart_type: report.chartType, + line_type: report.lineType, range: report.range, + formula: report.formula, }, }); }), @@ -123,7 +82,7 @@ export const reportRouter = createTRPCRouter({ .input( z.object({ reportId: z.string(), - report: zChartInput, + report: zChartInput.omit({ projectId: true }), }) ) .mutation(({ input: { report, reportId } }) => { @@ -137,7 +96,9 @@ export const reportRouter = createTRPCRouter({ interval: report.interval, breakdowns: report.breakdowns, chart_type: report.chartType, + line_type: report.lineType, range: report.range, + formula: report.formula, }, }); }), diff --git a/apps/dashboard/src/server/api/routers/share.ts b/apps/dashboard/src/server/api/routers/share.ts new file mode 100644 index 00000000..758b408f --- /dev/null +++ b/apps/dashboard/src/server/api/routers/share.ts @@ -0,0 +1,29 @@ +import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc'; +import { db } from '@/server/db'; +import { zShareOverview } from '@openpanel/validation'; +import ShortUniqueId from 'short-unique-id'; + +const uid = new ShortUniqueId({ length: 6 }); + +export const shareRouter = createTRPCRouter({ + shareOverview: protectedProcedure + .input(zShareOverview) + .mutation(({ input }) => { + return db.shareOverview.upsert({ + where: { + project_id: input.projectId, + }, + create: { + id: uid.rnd(), + organization_slug: input.organizationId, + project_id: input.projectId, + public: input.public, + password: input.password || null, + }, + update: { + public: input.public, + password: input.password, + }, + }); + }), +}); diff --git a/apps/web/src/server/api/routers/ui.ts b/apps/dashboard/src/server/api/routers/ui.ts similarity index 100% rename from apps/web/src/server/api/routers/ui.ts rename to apps/dashboard/src/server/api/routers/ui.ts diff --git a/apps/dashboard/src/server/api/routers/user.ts b/apps/dashboard/src/server/api/routers/user.ts new file mode 100644 index 00000000..e1a71699 --- /dev/null +++ b/apps/dashboard/src/server/api/routers/user.ts @@ -0,0 +1,22 @@ +import { createTRPCRouter, protectedProcedure } from '@/server/api/trpc'; +import { clerkClient } from '@clerk/nextjs'; +import { transformUser } from '@openpanel/db'; +import { z } from 'zod'; + +export const userRouter = createTRPCRouter({ + update: protectedProcedure + .input( + z.object({ + firstName: z.string(), + lastName: z.string(), + }) + ) + .mutation(({ input, ctx }) => { + return clerkClient.users + .updateUser(ctx.session.userId, { + firstName: input.firstName, + lastName: input.lastName, + }) + .then(transformUser); + }), +}); diff --git a/apps/dashboard/src/server/api/trpc.ts b/apps/dashboard/src/server/api/trpc.ts new file mode 100644 index 00000000..df7673cd --- /dev/null +++ b/apps/dashboard/src/server/api/trpc.ts @@ -0,0 +1,49 @@ +import { clerkClient } from '@clerk/nextjs'; +import type { getAuth } from '@clerk/nextjs/server'; +import { initTRPC, TRPCError } from '@trpc/server'; +import superjson from 'superjson'; +import { ZodError } from 'zod'; + +interface CreateContextOptions { + session: ReturnType | null; +} + +const t = initTRPC.context().create({ + transformer: superjson, + errorFormatter({ shape, error }) { + return { + ...shape, + data: { + ...shape.data, + zodError: + error.cause instanceof ZodError ? error.cause.flatten() : null, + }, + }; + }, +}); + +export const createTRPCRouter = t.router; + +export const publicProcedure = t.procedure; + +const enforceUserIsAuthed = t.middleware(async ({ ctx, next }) => { + if (!ctx.session?.userId) { + throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Not authenticated' }); + } + try { + const user = await clerkClient.users.getUser(ctx.session.userId); + return next({ + ctx: { + session: { ...ctx.session, user }, + }, + }); + } catch (error) { + console.error('Failes to get user', error); + throw new TRPCError({ + code: 'UNAUTHORIZED', + message: 'Failed to get user', + }); + } +}); + +export const protectedProcedure = t.procedure.use(enforceUserIsAuthed); diff --git a/apps/dashboard/src/server/auth.ts b/apps/dashboard/src/server/auth.ts new file mode 100644 index 00000000..7ae3487b --- /dev/null +++ b/apps/dashboard/src/server/auth.ts @@ -0,0 +1,3 @@ +export async function getSession() { + return true; +} diff --git a/apps/web/src/server/cache.ts b/apps/dashboard/src/server/cache.ts similarity index 100% rename from apps/web/src/server/cache.ts rename to apps/dashboard/src/server/cache.ts diff --git a/apps/dashboard/src/server/db.ts b/apps/dashboard/src/server/db.ts new file mode 100644 index 00000000..52cfb321 --- /dev/null +++ b/apps/dashboard/src/server/db.ts @@ -0,0 +1,36 @@ +import { slug } from '@/utils/slug'; +import { db } from '@openpanel/db'; + +export { db } from '@openpanel/db'; + +export async function getId(tableName: 'project' | 'dashboard', name: string) { + const newId = slug(name); + if (!db[tableName]) { + throw new Error('Table does not exists'); + } + + if (!('findUnique' in db[tableName])) { + throw new Error('findUnique does not exists'); + } + + // @ts-expect-error + const existingProject = await db[tableName]!.findUnique({ + where: { + id: newId, + }, + }); + + function random(str: string) { + const numbers = Math.floor(1000 + Math.random() * 9000); + if (str.match(/-\d{4}$/g)) { + return str.replace(/-\d{4}$/g, `-${numbers}`); + } + return `${str}-${numbers}`; + } + + if (existingProject) { + return getId(tableName, random(name)); + } + + return newId; +} diff --git a/apps/dashboard/src/server/pageExists.tsx b/apps/dashboard/src/server/pageExists.tsx new file mode 100644 index 00000000..7e262276 --- /dev/null +++ b/apps/dashboard/src/server/pageExists.tsx @@ -0,0 +1,23 @@ +import { getOrganizationBySlug, getProjectById } from '@openpanel/db'; +import { notFound } from 'next/navigation'; + +export async function getExists(organizationSlug: string, projectId?: string) { + const promises: Promise[] = [getOrganizationBySlug(organizationSlug)]; + + if (projectId) { + promises.push(getProjectById(projectId)); + } + + const results = await Promise.all(promises); + + if (results.some((res) => !res)) { + return notFound(); + } + + return { + organization: results[0] as Awaited< + ReturnType + >, + project: results[1] as Awaited>, + }; +} diff --git a/apps/web/src/styles/globals.css b/apps/dashboard/src/styles/globals.css similarity index 89% rename from apps/web/src/styles/globals.css rename to apps/dashboard/src/styles/globals.css index 52e84e75..08cd73d3 100644 --- a/apps/web/src/styles/globals.css +++ b/apps/dashboard/src/styles/globals.css @@ -30,7 +30,7 @@ --border: 214.3 31.8% 91.4%; --input: 214.3 31.8% 91.4%; - --ring: 222.2 84% 4.9%; + --ring: 212.73deg 26.83% 83.92%; --radius: 0.5rem; } @@ -118,6 +118,12 @@ 0 0; transition-duration: 0.5s; } + + .card { + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05); + border: 0 !important; + @apply bg-white rounded-xl; + } } .resizer { @@ -157,3 +163,10 @@ -ms-overflow-style: none; /* IE and Edge */ scrollbar-width: none; /* Firefox */ } + +/* Rechart */ + +.recharts-wrapper .recharts-cartesian-grid-horizontal line:first-child, +.recharts-wrapper .recharts-cartesian-grid-horizontal line:last-child { + stroke-opacity: 0; +} diff --git a/apps/dashboard/src/types/index.ts b/apps/dashboard/src/types/index.ts new file mode 100644 index 00000000..9185365f --- /dev/null +++ b/apps/dashboard/src/types/index.ts @@ -0,0 +1,9 @@ +import type { TooltipProps } from 'recharts'; + +export type HtmlProps = Omit< + React.DetailedHTMLProps, T>, + 'ref' +>; +export type IToolTipProps = Omit, 'payload'> & { + payload?: T[]; +}; diff --git a/apps/web/src/utils/clipboard.ts b/apps/dashboard/src/utils/clipboard.ts similarity index 60% rename from apps/web/src/utils/clipboard.ts rename to apps/dashboard/src/utils/clipboard.ts index d2b4d29e..02bf3ba8 100644 --- a/apps/web/src/utils/clipboard.ts +++ b/apps/dashboard/src/utils/clipboard.ts @@ -1,9 +1,8 @@ -import { toast } from '@/components/ui/use-toast'; +import { toast } from 'sonner'; export function clipboard(value: string | number) { navigator.clipboard.writeText(value.toString()); - toast({ - title: 'Copied to clipboard', + toast('Copied to clipboard', { description: value.toString(), }); } diff --git a/apps/web/src/utils/cn.ts b/apps/dashboard/src/utils/cn.ts similarity index 100% rename from apps/web/src/utils/cn.ts rename to apps/dashboard/src/utils/cn.ts diff --git a/apps/web/src/utils/date.ts b/apps/dashboard/src/utils/date.ts similarity index 100% rename from apps/web/src/utils/date.ts rename to apps/dashboard/src/utils/date.ts diff --git a/apps/dashboard/src/utils/getters.ts b/apps/dashboard/src/utils/getters.ts new file mode 100644 index 00000000..1257b551 --- /dev/null +++ b/apps/dashboard/src/utils/getters.ts @@ -0,0 +1,6 @@ +import type { IServiceProfile } from '@openpanel/db'; + +export function getProfileName(profile: IServiceProfile | undefined | null) { + if (!profile) return 'No profile'; + return [profile.first_name, profile.last_name].filter(Boolean).join(' '); +} diff --git a/apps/dashboard/src/utils/math.ts b/apps/dashboard/src/utils/math.ts new file mode 100644 index 00000000..c24eb461 --- /dev/null +++ b/apps/dashboard/src/utils/math.ts @@ -0,0 +1,26 @@ +import { isNumber } from 'mathjs'; + +export const round = (num: number, decimals = 2) => { + const factor = Math.pow(10, decimals); + return Math.round((num + Number.EPSILON) * factor) / factor; +}; + +export const average = (arr: (number | null)[]) => { + const filtered = arr.filter( + (n): n is number => + isNumber(n) && !Number.isNaN(n) && Number.isFinite(n) && n !== 0 + ); + const avg = filtered.reduce((p, c) => p + c, 0) / filtered.length; + return Number.isNaN(avg) ? 0 : avg; +}; + +export const sum = (arr: (number | null)[]): number => + round(arr.filter(isNumber).reduce((acc, item) => acc + item, 0)); + +export const min = (arr: (number | null)[]): number => + Math.min(...arr.filter(isNumber)); + +export const max = (arr: (number | null)[]): number => + Math.max(...arr.filter(isNumber)); + +export const isFloat = (n: number) => n % 1 !== 0; diff --git a/apps/dashboard/src/utils/meta.ts b/apps/dashboard/src/utils/meta.ts new file mode 100644 index 00000000..17954631 --- /dev/null +++ b/apps/dashboard/src/utils/meta.ts @@ -0,0 +1,21 @@ +import type { Metadata } from 'next'; + +const title = 'Openpanel.dev | An open-source alternative to Mixpanel'; +const description = + 'Unlock actionable insights effortlessly with Insightful, the open-source analytics library that combines the power of Mixpanel with the simplicity of Plausible. Enjoy a unified overview, predictable pricing, and a vibrant community. Join us in democratizing analytics today!'; + +export const defaultMeta: Metadata = { + title, + description, + openGraph: { + title, + images: [ + { + url: 'https://openpanel.dev/ogimage.png', + width: 1200, + height: 630, + alt: title, + }, + ], + }, +}; diff --git a/apps/web/src/utils/slug.ts b/apps/dashboard/src/utils/slug.ts similarity index 100% rename from apps/web/src/utils/slug.ts rename to apps/dashboard/src/utils/slug.ts diff --git a/apps/web/src/utils/theme.ts b/apps/dashboard/src/utils/theme.ts similarity index 87% rename from apps/web/src/utils/theme.ts rename to apps/dashboard/src/utils/theme.ts index d67e187d..6fccc0fa 100644 --- a/apps/web/src/utils/theme.ts +++ b/apps/dashboard/src/utils/theme.ts @@ -4,7 +4,7 @@ import tailwinConfig from '../../tailwind.config'; export const resolvedTailwindConfig = resolveConfig(tailwinConfig); -export const theme = resolvedTailwindConfig.theme; +export const theme = resolvedTailwindConfig.theme as Record; export function getChartColor(index: number): string { const colors = theme?.colors ?? {}; diff --git a/apps/dashboard/src/utils/truncate.ts b/apps/dashboard/src/utils/truncate.ts new file mode 100644 index 00000000..9cecae76 --- /dev/null +++ b/apps/dashboard/src/utils/truncate.ts @@ -0,0 +1,6 @@ +export function truncate(str: string, len: number) { + if (str.length <= len) { + return str; + } + return str.slice(0, len) + '...'; +} diff --git a/apps/dashboard/tailwind.config.js b/apps/dashboard/tailwind.config.js new file mode 100644 index 00000000..311eb4ef --- /dev/null +++ b/apps/dashboard/tailwind.config.js @@ -0,0 +1,136 @@ +const colors = [ + '#2563EB', + '#ff7557', + '#7fe1d8', + '#f8bc3c', + '#b3596e', + '#72bef4', + '#ffb27a', + '#0f7ea0', + '#3ba974', + '#febbb2', + '#cb80dc', + '#5cb7af', + '#7856ff', +]; + +const twColors = [ + 'rose', + 'pink', + 'fuchsia', + 'purple', + 'violet', + 'indigo', + 'blue', + 'sky', + 'cyan', + 'teal', + 'emerald', + 'green', + 'lime', + 'yellow', + 'amber', + 'orange', + 'red', + 'stone', + 'neutral', + 'zinc', + 'grey', + 'slate', +]; +const twColorVariants = ['50', '100', '200', '700', '800', '900']; + +/** @type {import('tailwindcss').Config} */ +const config = { + safelist: [ + ...colors.flatMap((color) => + ['text', 'bg'].map((prefix) => `${prefix}-chart-${color}`) + ), + ...twColors.flatMap((color) => { + return twColorVariants.flatMap((variant) => { + return [ + `text-${color}-${variant}`, + `bg-${color}-${variant}`, + `hover:bg-${color}-${variant}`, + `border-${color}-${variant}`, + ]; + }); + }), + ], + content: [ + './pages/**/*.{ts,tsx}', + './components/**/*.{ts,tsx}', + './app/**/*.{ts,tsx}', + './src/**/*.{ts,tsx}', + ], + theme: { + extend: { + colors: { + border: 'hsl(var(--border))', + input: 'hsl(var(--input))', + ring: 'hsl(var(--ring))', + background: 'hsl(var(--background))', + foreground: 'hsl(var(--foreground))', + primary: { + DEFAULT: 'hsl(var(--primary))', + foreground: 'hsl(var(--primary-foreground))', + }, + secondary: { + DEFAULT: 'hsl(var(--secondary))', + foreground: 'hsl(var(--secondary-foreground))', + }, + destructive: { + DEFAULT: 'hsl(var(--destructive))', + foreground: 'hsl(var(--destructive-foreground))', + }, + muted: { + DEFAULT: 'hsl(var(--muted))', + foreground: 'hsl(var(--muted-foreground))', + }, + accent: { + DEFAULT: 'hsl(var(--accent))', + foreground: 'hsl(var(--accent-foreground))', + }, + popover: { + DEFAULT: 'hsl(var(--popover))', + foreground: 'hsl(var(--popover-foreground))', + }, + card: { + DEFAULT: 'hsl(var(--card))', + foreground: 'hsl(var(--card-foreground))', + }, + ...colors.reduce((acc, color, index) => { + return { + ...acc, + [`chart-${index}`]: color, + }; + }, {}), + }, + borderRadius: { + lg: 'var(--radius)', + md: 'calc(var(--radius) - 2px)', + sm: 'calc(var(--radius) - 4px)', + }, + boxShadow: { + DEFAULT: '0 5px 10px rgb(0 0 0 / 5%)', + }, + keyframes: { + 'accordion-down': { + from: { height: '0px' }, + to: { height: 'var(--radix-accordion-content-height)' }, + }, + 'accordion-up': { + from: { height: 'var(--radix-accordion-content-height)' }, + to: { height: '0px' }, + }, + }, + animation: { + 'accordion-down': 'accordion-down 0.2s ease-out', + 'accordion-up': 'accordion-up 0.2s ease-out', + }, + }, + }, + plugins: [require('tailwindcss-animate')], +}; + +export default config; diff --git a/apps/web/tsconfig.json b/apps/dashboard/tsconfig.json similarity index 63% rename from apps/web/tsconfig.json rename to apps/dashboard/tsconfig.json index b62436fc..d17f2ec2 100644 --- a/apps/web/tsconfig.json +++ b/apps/dashboard/tsconfig.json @@ -1,5 +1,5 @@ { - "extends": "@mixan/tsconfig/base.json", + "extends": "@openpanel/tsconfig/base.json", "compilerOptions": { "baseUrl": ".", "paths": { @@ -10,7 +10,8 @@ "name": "next" } ], - "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json" + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json", + "strictNullChecks": true }, "include": [".", ".next/types/**/*.ts"], "exclude": ["node_modules"] diff --git a/apps/docs/.gitignore b/apps/docs/.gitignore new file mode 100644 index 00000000..2971a0bd --- /dev/null +++ b/apps/docs/.gitignore @@ -0,0 +1,42 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# database +/prisma/db.sqlite +/prisma/db.sqlite-journal + +# next.js +/.next/ +/out/ +next-env.d.ts + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +# do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables +.env +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo diff --git a/apps/docs/.prettierignore b/apps/docs/.prettierignore new file mode 100644 index 00000000..0aa0c4cb --- /dev/null +++ b/apps/docs/.prettierignore @@ -0,0 +1 @@ +./src/pages/docs/* \ No newline at end of file diff --git a/apps/docs/Dockerfile b/apps/docs/Dockerfile new file mode 100644 index 00000000..35198283 --- /dev/null +++ b/apps/docs/Dockerfile @@ -0,0 +1,113 @@ +FROM --platform=linux/amd64 node:20-slim AS base + +ARG NEXT_PUBLIC_DASHBOARD_URL +ENV NEXT_PUBLIC_DASHBOARD_URL=$NEXT_PUBLIC_DASHBOARD_URL + +ARG NEXT_PUBLIC_API_URL +ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL + +ARG DATABASE_URL +ENV DATABASE_URL=$DATABASE_URL + +ARG CLICKHOUSE_DB +ENV CLICKHOUSE_DB=$CLICKHOUSE_DB + +ARG CLICKHOUSE_PASSWORD +ENV CLICKHOUSE_PASSWORD=$CLICKHOUSE_PASSWORD + +ARG CLICKHOUSE_URL +ENV CLICKHOUSE_URL=$CLICKHOUSE_URL + +ARG CLICKHOUSE_USER +ENV CLICKHOUSE_USER=$CLICKHOUSE_USER + +ARG REDIS_URL +ENV REDIS_URL=$REDIS_URL + +ARG NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY +ENV NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=$NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY + +ARG CLERK_SECRET_KEY +ENV CLERK_SECRET_KEY=$CLERK_SECRET_KEY + +ENV PNPM_HOME="/pnpm" + +ENV PATH="$PNPM_HOME:$PATH" + +RUN corepack enable + +ARG NODE_VERSION=20 + +RUN apt update \ + && apt install -y curl \ + && curl -L https://raw.githubusercontent.com/tj/n/master/bin/n -o n \ + && bash n $NODE_VERSION \ + && rm n \ + && npm install -g n + +WORKDIR /app + +COPY package.json package.json +COPY pnpm-lock.yaml pnpm-lock.yaml +COPY pnpm-workspace.yaml pnpm-workspace.yaml +COPY apps/public/package.json apps/public/package.json +COPY packages/db/package.json packages/db/package.json +COPY packages/redis/package.json packages/redis/package.json +COPY packages/queue/package.json packages/queue/package.json +COPY packages/common/package.json packages/common/package.json +COPY packages/constants/package.json packages/constants/package.json +COPY packages/validation/package.json packages/validation/package.json +COPY packages/sdk/package.json packages/sdk/package.json + +# BUILD +FROM base AS build + +WORKDIR /app/apps/public +RUN pnpm install --frozen-lockfile --ignore-scripts + +WORKDIR /app +COPY apps apps +COPY packages packages +COPY tooling tooling +RUN pnpm db:codegen + +WORKDIR /app/apps/public +RUN pnpm run build + +# PROD +FROM base AS prod + +WORKDIR /app/apps/public +RUN pnpm install --frozen-lockfile --prod --ignore-scripts + +# FINAL +FROM base AS runner + +COPY --from=build /app/package.json /app/package.json +COPY --from=prod /app/node_modules /app/node_modules +# Apps +COPY --from=build /app/apps/public /app/apps/public +# Apps node_modules +COPY --from=prod /app/apps/public/node_modules /app/apps/public/node_modules +# Packages +COPY --from=build /app/packages/db /app/packages/db +COPY --from=build /app/packages/redis /app/packages/redis +COPY --from=build /app/packages/common /app/packages/common +COPY --from=build /app/packages/queue /app/packages/queue +COPY --from=build /app/packages/constants /app/packages/constants +COPY --from=build /app/packages/validation /app/packages/validation +COPY --from=build /app/packages/sdk /app/packages/sdk +# Packages node_modules +COPY --from=prod /app/packages/db/node_modules /app/packages/db/node_modules +COPY --from=prod /app/packages/redis/node_modules /app/packages/redis/node_modules +COPY --from=prod /app/packages/common/node_modules /app/packages/common/node_modules +COPY --from=prod /app/packages/queue/node_modules /app/packages/queue/node_modules +COPY --from=prod /app/packages/validation/node_modules /app/packages/validation/node_modules + +RUN pnpm db:codegen + +WORKDIR /app/apps/public + +EXPOSE 3000 + +CMD ["pnpm", "start"] \ No newline at end of file diff --git a/apps/docs/README.md b/apps/docs/README.md new file mode 100644 index 00000000..d0fa60ed --- /dev/null +++ b/apps/docs/README.md @@ -0,0 +1 @@ +# Docs diff --git a/apps/docs/next.config.mjs b/apps/docs/next.config.mjs new file mode 100644 index 00000000..50072116 --- /dev/null +++ b/apps/docs/next.config.mjs @@ -0,0 +1,33 @@ +import nextra from 'nextra'; + +/** @type {import("next").NextConfig} */ +const config = { + reactStrictMode: true, + transpilePackages: ['@openpanel/queue'], + eslint: { ignoreDuringBuilds: true }, + typescript: { ignoreBuildErrors: true }, + experimental: { + // Avoid "Critical dependency: the request of a dependency is an expression" + serverComponentsExternalPackages: ['bullmq'], + }, + /** + * If you are using `appDir` then you must comment the below `i18n` config out. + * + * @see https://github.com/vercel/next.js/issues/41980 + */ + i18n: { + locales: ['en'], + defaultLocale: 'en', + }, +}; + +const withNextra = nextra({ + theme: 'nextra-theme-docs', + themeConfig: './theme.config.jsx', + flexsearch: { + codeblocks: false, + }, + defaultShowCopyCode: true, +}); + +export default withNextra(config); diff --git a/apps/docs/package.json b/apps/docs/package.json new file mode 100644 index 00000000..5459f19b --- /dev/null +++ b/apps/docs/package.json @@ -0,0 +1,46 @@ +{ + "name": "@openpanel/docs", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "rm -rf .next && pnpm with-env next dev", + "build": "next build", + "start": "next start", + "lint": "eslint .", + "format": "prettier --write \"**/*.{tsx,mjs,ts,md,json}\"", + "typecheck": "tsc --noEmit", + "with-env": "dotenv -e ../../.env -c --" + }, + "dependencies": { + "next": "~14.0.4", + "nextra": "^2.13.4", + "nextra-theme-docs": "^2.13.4", + "react": "18.2.0", + "react-dom": "18.2.0" + }, + "devDependencies": { + "@openpanel/eslint-config": "workspace:*", + "@openpanel/prettier-config": "workspace:*", + "@openpanel/tsconfig": "workspace:*", + "@types/node": "^18.16.0", + "@types/react": "^18.2.20", + "@types/react-dom": "^18.2.7", + "@typescript-eslint/eslint-plugin": "^6.6.0", + "@typescript-eslint/parser": "^6.6.0", + "autoprefixer": "^10.4.18", + "eslint": "^8.48.0", + "postcss": "^8.4.35", + "prettier": "^3.0.3", + "tailwindcss": "^3.4.1", + "typescript": "^5.2.2" + }, + "eslintConfig": { + "root": true, + "extends": [ + "@openpanel/eslint-config/base", + "@openpanel/eslint-config/react", + "@openpanel/eslint-config/nextjs" + ] + }, + "prettier": "@openpanel/prettier-config" +} diff --git a/apps/docs/postcss.config.js b/apps/docs/postcss.config.js new file mode 100644 index 00000000..33ad091d --- /dev/null +++ b/apps/docs/postcss.config.js @@ -0,0 +1,6 @@ +module.exports = { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +} diff --git a/apps/docs/src/components/device-id-warning.tsx b/apps/docs/src/components/device-id-warning.tsx new file mode 100644 index 00000000..dc210b7d --- /dev/null +++ b/apps/docs/src/components/device-id-warning.tsx @@ -0,0 +1,12 @@ +import Link from 'next/link'; +import { Callout } from 'nextra/components'; + +export function DeviceIdWarning() { + return ( + + Read more about{' '} + device id and why you might want it. + **We recommend not to but it's up to you.** + + ); +} diff --git a/apps/docs/src/components/personal-data-warning.tsx b/apps/docs/src/components/personal-data-warning.tsx new file mode 100644 index 00000000..c59d601b --- /dev/null +++ b/apps/docs/src/components/personal-data-warning.tsx @@ -0,0 +1,10 @@ +import { Callout } from 'nextra/components'; + +export function PersonalDataWarning() { + return ( + + Keep in mind that this is considered personal data. Make sure you have the + users consent before calling this! + + ); +} diff --git a/apps/docs/src/components/sdk-config.mdx b/apps/docs/src/components/sdk-config.mdx new file mode 100644 index 00000000..931bc164 --- /dev/null +++ b/apps/docs/src/components/sdk-config.mdx @@ -0,0 +1,5 @@ +- `url` - The url of the openpanel API or your self-hosted instance +- `clientId` - The client id of your application +- `trackScreenViews` - If true, the library will automatically track screen views +- `trackOutgoingLinks` - If true, the library will automatically track outgoing links +- `trackAttributes` - If true, the library will automatically track attributes diff --git a/apps/docs/src/globals.css b/apps/docs/src/globals.css new file mode 100644 index 00000000..a6b7e768 --- /dev/null +++ b/apps/docs/src/globals.css @@ -0,0 +1,7 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +article main a { + @apply underline; +} diff --git a/apps/docs/src/pages/_app.tsx b/apps/docs/src/pages/_app.tsx new file mode 100644 index 00000000..479b8ca4 --- /dev/null +++ b/apps/docs/src/pages/_app.tsx @@ -0,0 +1,11 @@ +import type { AppProps } from 'next/app'; + +import 'src/globals.css'; + +export default function App({ Component, pageProps }: AppProps) { + return ( + <> + + + ); +} diff --git a/apps/docs/src/pages/_meta.json b/apps/docs/src/pages/_meta.json new file mode 100644 index 00000000..e100049e --- /dev/null +++ b/apps/docs/src/pages/_meta.json @@ -0,0 +1,10 @@ +{ + "index": { + "title": "Introduction", + "type": "page" + }, + "docs": { + "title": "Documentation", + "type": "page" + } +} diff --git a/apps/docs/src/pages/docs/_meta.json b/apps/docs/src/pages/docs/_meta.json new file mode 100644 index 00000000..75350419 --- /dev/null +++ b/apps/docs/src/pages/docs/_meta.json @@ -0,0 +1,14 @@ +{ + "index": "Get Started", + "-- Implementation": { + "type": "separator", + "title": "Implementation" + }, + "script": "Script", + "javascript": "Javascript SDK", + "nextjs": "Next.js", + "react": "React", + "react-native": "React-Native", + "remix": "Remix", + "vue": "Vue" +} diff --git a/apps/docs/src/pages/docs/index.mdx b/apps/docs/src/pages/docs/index.mdx new file mode 100644 index 00000000..464c5565 --- /dev/null +++ b/apps/docs/src/pages/docs/index.mdx @@ -0,0 +1,80 @@ +import { Card, Cards } from 'nextra/components'; + +# Get started + +Create an account on [Openpanel](https://openpanel.dev) and setup your first project (takes 2 minutes). You will get a `clientId` that you will use to initialize Openpanel in your app. + + + + } + title="General / Script" + href="/docs/general" + > + {' '} + + + } + title="React" + href="/docs/react" + > + {' '} + + + } + title="React-Native" + href="/docs/react-native" + > + {' '} + + + } + title="Next.js" + href="/docs/nextjs" + > + {' '} + + + } + title="Remix" + href="/docs/remix" + > + {' '} + + + } + title="Vue" + href="/docs/vue" + > + {' '} + + diff --git a/apps/docs/src/pages/docs/javascript.mdx b/apps/docs/src/pages/docs/javascript.mdx new file mode 100644 index 00000000..3069d40b --- /dev/null +++ b/apps/docs/src/pages/docs/javascript.mdx @@ -0,0 +1,139 @@ +import Link from 'next/link'; +import { Callout, Steps, Tabs } from 'nextra/components'; +import { DeviceIdWarning } from 'src/components/device-id-warning'; +import { PersonalDataWarning } from 'src/components/personal-data-warning'; + +import SdkConfig from 'src/components/sdk-config.mdx'; + +# Javascript SDK + +This is the base SDK for Openpanel. All other SDKs are built on top of this one. + +## Installation + + +### Install dependencies + +```bash +pnpm install @openpanel/sdk +``` + +### Initialize + +```tsx +import { Openpanel } from '@openpanel/sdk'; + +const op = new Openpanel({ + url: 'https://api.openpanel.dev', + clientId: '{YOUR_CLIENT_ID}', + // mostly for backend and apps that can't rely on CORS + clientSecret: '{YOUR_CLIENT_SECRET}', +}); +``` + +#### Config + +- `url` - The url of the openpanel API or your self-hosted instance +- `clientId` - The client id of your application +- `clientSecret` - The client secret of your application (mostly for backend and apps that can't rely on CORS) + +### Ready! + +You're now ready to use the library. + +```typescript +// Sends an event with payload foo: bar +op.event('my_event', { foo: 'bar' }); + +// Identify with profile id +op.setProfileId('123'); + +// or with additional data +op.setProfile({ + profileId: '123', + firstName: 'John', + lastName: 'Doe', + email: 'john.doe@openpanel.dev', +}); + +// Increment a property +op.increment('app_opened'); // increment by 1 +op.increment('app_opened', 5); // increment by 5 + +// Decrement a property +op.decrement('app_opened'); // decrement by 1 +op.decrement('app_opened', 5); // decrement by 5 +``` + + + +## Usage + +### Track event + +```typescript +op.event('my_event', { foo: 'bar' }); +``` + +### Identify + +#### Set Profile Id + +Keep track of your users by identifying them with a unique id. This is a good features if you have things behind a login and want to track user behavior. + + + +```typescript +import { setProfileId } from '@openpanel/nextjs'; + +const profileId = '123'; +setProfileId(profileId); +``` + +#### Additional data + +This method does the same as `setProfileId` but also allows you to update the profile with additional data. + + + +```typescript +import { setProfile } from '@openpanel/nextjs'; + +const profileId = '123'; +setProfile({ + profileId, + // firstName?: string; + // lastName?: string; + // email?: string; + // avatar?: string; + // properties?: Record; +}); +``` + +#### Increment property + +Increment a property on the profile. + +```typescript +import { increment } from '@openpanel/nextjs'; + +// Increment by 1 +increment('app_opened'); + +// Increment by 5 +increment('app_opened', 5); +``` + +#### Decrement property + +Decrement a property on the profile. + +```typescript +import { decrement } from '@openpanel/nextjs'; + +// Increment by 1 +decrement('app_opened'); + +// Increment by 5 +decrement('app_opened', 5); +``` diff --git a/apps/docs/src/pages/docs/nextjs.mdx b/apps/docs/src/pages/docs/nextjs.mdx new file mode 100644 index 00000000..10e82fe3 --- /dev/null +++ b/apps/docs/src/pages/docs/nextjs.mdx @@ -0,0 +1,172 @@ +import Link from 'next/link'; +import { Callout, Steps, Tabs } from 'nextra/components'; +import { DeviceIdWarning } from 'src/components/device-id-warning'; +import { PersonalDataWarning } from 'src/components/personal-data-warning'; + +import SdkConfig from 'src/components/sdk-config.mdx'; + +# Next.js + +Keep in mind that all tracking here happens on the client! If you want to track server-side events, you should use the node SDK 👀. + +## Installation + + +### Install dependencies + +```bash +pnpm install @openpanel/nextjs +``` + +### Initialize + +Add `OpenpanelProvider` to your root layout component. + +```tsx +import { OpenpanelProvider } from '@openpanel/nextjs'; + +export default RootLayout({ children }) { + return ( + <> + + {children} + + ) +} +``` + +#### Config + + + +### Ready! + +You're now ready to use the library. + +```typescript +import { + decrement, + increment, + setProfile, + setProfileId, + trackEvent, + trackScreenView, +} from '@openpanel/nextjs'; + +// Sends an event with payload foo: bar +trackEvent('my_event', { foo: 'bar' }); + +// Identify with profile id +setProfileId('123'); + +// or with additional data +setProfile({ + profileId: '123', + firstName: 'John', + lastName: 'Doe', + email: 'john.doe@openpanel.dev', +}); + +// Increment a property +increment('app_opened'); // increment by 1 +increment('app_opened', 5); // increment by 5 + +// Decrement a property +decrement('app_opened'); // decrement by 1 +decrement('app_opened', 5); // decrement by 5 +``` + + + +## Usage + +### Track event + + + + ```typescript + import { trackEvent } from '@openpanel/nextjs'; + trackEvent('my_event', { foo: 'bar' }); + ``` + + + ```javascript + window.op('event', 'my_event', { foo: 'bar' }); + ``` + + + For this to work you need to enable `trackAttributes` in the config. + ```html + + ``` + + + +### Identify + +#### Set Profile Id + +Keep track of your users by identifying them with a unique id. This is a good features if you have things behind a login and want to track user behavior. + + + +```typescript +import { setProfileId } from '@openpanel/nextjs'; + +const profileId = '123'; +setProfileId(profileId); +``` + +#### Additional data + +This method does the same as `setProfileId` but also allows you to update the profile with additional data. + + + +```typescript +import { setProfile } from '@openpanel/nextjs'; + +const profileId = '123'; +setProfile({ + profileId, + // firstName?: string; + // lastName?: string; + // email?: string; + // avatar?: string; + // properties?: Record; +}); +``` + +#### Increment property + +Increment a property on the profile. + +```typescript +import { increment } from '@openpanel/nextjs'; + +// Increment by 1 +increment('app_opened'); + +// Increment by 5 +increment('app_opened', 5); +``` + +#### Decrement property + +Decrement a property on the profile. + +```typescript +import { decrement } from '@openpanel/nextjs'; + +// Increment by 1 +decrement('app_opened'); + +// Increment by 5 +decrement('app_opened', 5); +``` diff --git a/apps/docs/src/pages/docs/react-native.mdx b/apps/docs/src/pages/docs/react-native.mdx new file mode 100644 index 00000000..e4ea54f5 --- /dev/null +++ b/apps/docs/src/pages/docs/react-native.mdx @@ -0,0 +1,196 @@ +import Link from 'next/link'; +import { Callout, Steps, Tabs } from 'nextra/components'; +import { DeviceIdWarning } from 'src/components/device-id-warning'; +import { PersonalDataWarning } from 'src/components/personal-data-warning'; + +import SdkConfig from 'src/components/sdk-config.mdx'; + +# React-Native + +## Installation + + +### Install dependencies + +We're dependent on `expo-application` for `buildNumber`, `versionNumber` (and `referrer` on android) and `expo-constants` to get the `user-agent`. + +```bash +pnpm install @openpanel/react-native +expo install --pnpm expo-application expo-constants +``` + +### Initialize + +On native we use a clientSecret to authenticate the app. + +```typescript +const op = new Openpanel({ + url: 'https://api.openpanel.dev', + clientId: '{YOUR_CLIENT_ID}', + clientSecret: '{YOUR_CLIENT_SECRET}', +}); +``` + +#### Config + +- `url` - The url of the openpanel API or your self-hosted instance +- `clientId` - The client id of your application +- `clientSecret` - The client secret of your application + +### Ready! + +You're now ready to use the library. + +```typescript +// Sends an event with payload foo: bar +op.event('my_event', { foo: 'bar' }); + +// Identify with profile id +op.setProfileId('123'); + +// or with additional data +op.setProfile({ + profileId: '123', + firstName: 'John', + lastName: 'Doe', + email: 'john.doe@openpanel.dev', +}); + +// Increment a property +op.increment('app_opened'); // increment by 1 +op.increment('app_opened', 5); // increment by 5 + +// Decrement a property +op.decrement('app_opened'); // decrement by 1 +op.decrement('app_opened', 5); // decrement by 5 +``` + + + +## Usage + +### Track event + +```typescript +op.event('my_event', { foo: 'bar' }); +``` + +### Navigation / Screen views + + + + ```typescript + import { usePathname, useSegments } from 'expo-router'; + + function RootLayout() { + // ... + const pathname = usePathname() + // Segments is optional but can be nice to have if you + // want to group routes together + // pathname = /posts/123 + // segements = ['posts', '[id]'] + const segments = useSegments() + + useEffect(() => { + // Simple + op.screenView(pathname) + + // With extra data + op.screenView(pathname, { + // segments is optional but nice to have + segments: segments.join('/'), + // other optional data you want to send with the screen view + }) + }, [pathname,segments]) + // ... + } + ``` + + + + ```tsx + import { createNavigationContainerRef } from '@react-navigation/native' + import { Openpanel } from '@openpanel/react-native' + + const op = new Openpanel({ /* ... */ }) + const navigationRef = createNavigationContainerRef() + + export function NavigationRoot() { + const handleNavigationStateChange = () => { + const current = navigationRef.getCurrentRoute() + if (current) { + op.screenView(current.name, { + params: current.params, + }) + } + } + + return ( + + + + ) + } + ``` + + + + +### Identify + +#### Set Profile Id + +Keep track of your users by identifying them with a unique id. This is a good features if you have things behind a login and want to track user behavior. + + + +```typescript +const profileId = '123'; +op.setProfileId(profileId); +``` + +#### Additional data + +This method does the same as `setProfileId` but also allows you to update the profile with additional data. + + + +```typescript +const profileId = '123'; +op.setProfile({ + profileId, + // firstName?: string; + // lastName?: string; + // email?: string; + // avatar?: string; + // properties?: Record; +}); +``` + +#### Increment property + +Increment a property on the profile. + +```typescript +// Increment by 1 +op.increment('app_opened'); + +// Increment by 5 +op.increment('app_opened', 5); +``` + +#### Decrement property + +Decrement a property on the profile. + +```typescript +// Increment by 1 +op.decrement('app_opened'); + +// Increment by 5 +op.decrement('app_opened', 5); +``` diff --git a/apps/docs/src/pages/docs/react.mdx b/apps/docs/src/pages/docs/react.mdx new file mode 100644 index 00000000..66bee19c --- /dev/null +++ b/apps/docs/src/pages/docs/react.mdx @@ -0,0 +1,5 @@ +import Link from 'next/link'; + +# React + +Use script tag or Javascript SDK for now. We'll add a dedicated react sdk soon. diff --git a/apps/docs/src/pages/docs/remix.mdx b/apps/docs/src/pages/docs/remix.mdx new file mode 100644 index 00000000..8b3221ce --- /dev/null +++ b/apps/docs/src/pages/docs/remix.mdx @@ -0,0 +1,5 @@ +import Link from 'next/link'; + +# Remix + +Use script tag or Javascript SDK for now. We'll add a dedicated react sdk soon. diff --git a/apps/docs/src/pages/docs/script.mdx b/apps/docs/src/pages/docs/script.mdx new file mode 100644 index 00000000..d7f9c234 --- /dev/null +++ b/apps/docs/src/pages/docs/script.mdx @@ -0,0 +1,122 @@ +import { Callout, Tabs } from 'nextra/components'; +import { PersonalDataWarning } from 'src/components/personal-data-warning'; + +import SdkConfig from 'src/components/sdk-config.mdx'; + +# Script tag + +Just insert this snippet and replace `{YOUR_CLIENT_ID}` with your client id. + +```html + + +``` + +### Config + + + +## Usage + +You can let the library track screen views, outgoing links and attributes tracking by setting the `trackScreenViews`, `trackOutgoingLinks` and `trackAttributes` options to `true`. + +### Track event + + + + ```javascript + window.op('event', 'my_event', { foo: 'bar' }); + ``` + + + For this to work you need to enable `trackAttributes` in the config. + ```html + + ``` + + + +### Identify + +#### Set Profile Id + +Keep track of your users by identifying them with a unique id. This is a good features if you have things behind a login and want to track user behavior. + + + +```javascript +const profileId = '123'; +window.op('setProfileId', profileId); +``` + +#### Additional data + +This method does the same as `setProfileId` but also allows you to update the profile with additional data. + + + +```javascript +const profileId = '123'; +window.op('setProfile', { + profileId, + // firstName?: string; + // lastName?: string; + // email?: string; + // avatar?: string; + // properties?: Record; +}); +``` + +#### Increment property + +Increment a property on the profile. + +```javascript +// Increment by 1 +window.op('increment', 'app_opened'); + +// Increment by 5 +window.op('increment', 'app_opened', 5); +``` + +#### Decrement property + +Decrement a property on the profile. + +```javascript +// Increment by 1 +window.op('decrement', 'app_opened'); + +// Increment by 5 +window.op('decrement', 'app_opened', 5); +``` + +### Typescript + +Is your IDE mad at you for not using typescript? We got you covered. + +Add this and it will stop complain about `window.op` not being defined. + +```typescript +declare global { + interface Window { + op: { + q?: [string, ...any[]]; + (method: string, ...args: any[]): void; + }; + } +} +``` diff --git a/apps/docs/src/pages/docs/vue.mdx b/apps/docs/src/pages/docs/vue.mdx new file mode 100644 index 00000000..e7de0406 --- /dev/null +++ b/apps/docs/src/pages/docs/vue.mdx @@ -0,0 +1,5 @@ +import Link from 'next/link'; + +# Vue + +Use script tag or Javascript SDK for now. We'll add a dedicated react sdk soon. diff --git a/apps/docs/src/pages/index.mdx b/apps/docs/src/pages/index.mdx new file mode 100644 index 00000000..56e8d60c --- /dev/null +++ b/apps/docs/src/pages/index.mdx @@ -0,0 +1,14 @@ +# Introduction + +Openpanel is an open-source alternative to Mixpanel. Combining the power of Mixpanel with the ease of Plausible, Openpanel is a privacy-focused analytics tool that gives you the insights you need to make data-driven decisions. + +## Features + +- ✅ **Privacy-focused**: Openpanel is built with privacy in mind. We don't track any personal data and we don't use cookies. +- ✅ **Open-source**: Openpanel is open-source and you can host it yourself. +- ✅ **Cloud-hosted**: You can choose our cloud hosting if you don't want to host it yourself. We take care of the infrastructure and you can focus on your business. +- ✅ **Real-time analytics**: Everything is updated in real-time, no delays to see your insights. +- ✅ **Event-based tracking**: You can track any event you want, and you can track as many events as you want. +- ✅ **Custom properties**: You can add custom properties to your events to track more data. +- ✅ **Funnel analysis**: You can create funnels to see how your users are interacting with your product. +- ✅ **Reports**: Create as many reports as you want to visualize the data you need. diff --git a/apps/docs/tailwind.config.js b/apps/docs/tailwind.config.js new file mode 100644 index 00000000..a5a0b69c --- /dev/null +++ b/apps/docs/tailwind.config.js @@ -0,0 +1,8 @@ +/** @type {import('tailwindcss').Config} */ +module.exports = { + content: ['./src/**/*.{js,ts,jsx,tsx,mdx}'], + theme: { + extend: {}, + }, + plugins: [], +}; diff --git a/apps/docs/theme.config.jsx b/apps/docs/theme.config.jsx new file mode 100644 index 00000000..979dbd93 --- /dev/null +++ b/apps/docs/theme.config.jsx @@ -0,0 +1,75 @@ +import Image from 'next/image'; +import { useRouter } from 'next/router'; +import { useConfig } from 'nextra-theme-docs'; + +export default { + logo: ( + <> + + openpanel + + ), + head: (props) => { + const router = useRouter(); + const config = useConfig(); + const title = config.title; + const description = + config.description || 'An open-source alternative to Mixpanel'; + const domain = 'https://docs.openpanel.dev'; + const canonicalUrl = + `${domain}${router.asPath === '/' ? '' : router.asPath}`.split('?')[0]; + + return ( + <> + + + + + + + + + + + + + + + ); + }, + search: { + placeholder: 'Search', + }, + project: { + link: 'https://github.com/openpanel-dev/openpanel', + }, + docsRepositoryBase: + 'https://github.com/openpanel-dev/openpanel/blob/main/apps/docs', + useNextSeoProps() { + return { + titleTemplate: '%s - Openpanel', + }; + }, + footer: { + text: ( + + Made with ❤️ by{' '} + + Carl + + + ), + }, +}; diff --git a/apps/docs/tsconfig.json b/apps/docs/tsconfig.json new file mode 100644 index 00000000..f25ad65e --- /dev/null +++ b/apps/docs/tsconfig.json @@ -0,0 +1,25 @@ +{ + "extends": "@openpanel/tsconfig/base.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "@/*": [ + "./src/*" + ] + }, + "plugins": [ + { + "name": "next" + } + ], + "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json", + "strictNullChecks": true + }, + "include": [ + ".", + ".next/types/**/*.ts" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/apps/public/.gitignore b/apps/public/.gitignore new file mode 100644 index 00000000..2971a0bd --- /dev/null +++ b/apps/public/.gitignore @@ -0,0 +1,42 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# database +/prisma/db.sqlite +/prisma/db.sqlite-journal + +# next.js +/.next/ +/out/ +next-env.d.ts + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +# do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables +.env +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo diff --git a/apps/public/Dockerfile b/apps/public/Dockerfile new file mode 100644 index 00000000..35198283 --- /dev/null +++ b/apps/public/Dockerfile @@ -0,0 +1,113 @@ +FROM --platform=linux/amd64 node:20-slim AS base + +ARG NEXT_PUBLIC_DASHBOARD_URL +ENV NEXT_PUBLIC_DASHBOARD_URL=$NEXT_PUBLIC_DASHBOARD_URL + +ARG NEXT_PUBLIC_API_URL +ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL + +ARG DATABASE_URL +ENV DATABASE_URL=$DATABASE_URL + +ARG CLICKHOUSE_DB +ENV CLICKHOUSE_DB=$CLICKHOUSE_DB + +ARG CLICKHOUSE_PASSWORD +ENV CLICKHOUSE_PASSWORD=$CLICKHOUSE_PASSWORD + +ARG CLICKHOUSE_URL +ENV CLICKHOUSE_URL=$CLICKHOUSE_URL + +ARG CLICKHOUSE_USER +ENV CLICKHOUSE_USER=$CLICKHOUSE_USER + +ARG REDIS_URL +ENV REDIS_URL=$REDIS_URL + +ARG NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY +ENV NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=$NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY + +ARG CLERK_SECRET_KEY +ENV CLERK_SECRET_KEY=$CLERK_SECRET_KEY + +ENV PNPM_HOME="/pnpm" + +ENV PATH="$PNPM_HOME:$PATH" + +RUN corepack enable + +ARG NODE_VERSION=20 + +RUN apt update \ + && apt install -y curl \ + && curl -L https://raw.githubusercontent.com/tj/n/master/bin/n -o n \ + && bash n $NODE_VERSION \ + && rm n \ + && npm install -g n + +WORKDIR /app + +COPY package.json package.json +COPY pnpm-lock.yaml pnpm-lock.yaml +COPY pnpm-workspace.yaml pnpm-workspace.yaml +COPY apps/public/package.json apps/public/package.json +COPY packages/db/package.json packages/db/package.json +COPY packages/redis/package.json packages/redis/package.json +COPY packages/queue/package.json packages/queue/package.json +COPY packages/common/package.json packages/common/package.json +COPY packages/constants/package.json packages/constants/package.json +COPY packages/validation/package.json packages/validation/package.json +COPY packages/sdk/package.json packages/sdk/package.json + +# BUILD +FROM base AS build + +WORKDIR /app/apps/public +RUN pnpm install --frozen-lockfile --ignore-scripts + +WORKDIR /app +COPY apps apps +COPY packages packages +COPY tooling tooling +RUN pnpm db:codegen + +WORKDIR /app/apps/public +RUN pnpm run build + +# PROD +FROM base AS prod + +WORKDIR /app/apps/public +RUN pnpm install --frozen-lockfile --prod --ignore-scripts + +# FINAL +FROM base AS runner + +COPY --from=build /app/package.json /app/package.json +COPY --from=prod /app/node_modules /app/node_modules +# Apps +COPY --from=build /app/apps/public /app/apps/public +# Apps node_modules +COPY --from=prod /app/apps/public/node_modules /app/apps/public/node_modules +# Packages +COPY --from=build /app/packages/db /app/packages/db +COPY --from=build /app/packages/redis /app/packages/redis +COPY --from=build /app/packages/common /app/packages/common +COPY --from=build /app/packages/queue /app/packages/queue +COPY --from=build /app/packages/constants /app/packages/constants +COPY --from=build /app/packages/validation /app/packages/validation +COPY --from=build /app/packages/sdk /app/packages/sdk +# Packages node_modules +COPY --from=prod /app/packages/db/node_modules /app/packages/db/node_modules +COPY --from=prod /app/packages/redis/node_modules /app/packages/redis/node_modules +COPY --from=prod /app/packages/common/node_modules /app/packages/common/node_modules +COPY --from=prod /app/packages/queue/node_modules /app/packages/queue/node_modules +COPY --from=prod /app/packages/validation/node_modules /app/packages/validation/node_modules + +RUN pnpm db:codegen + +WORKDIR /app/apps/public + +EXPOSE 3000 + +CMD ["pnpm", "start"] \ No newline at end of file diff --git a/apps/public/README.md b/apps/public/README.md new file mode 100644 index 00000000..fba19eda --- /dev/null +++ b/apps/public/README.md @@ -0,0 +1,28 @@ +# Create T3 App + +This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`. + +## What's next? How do I make an app with this? + +We try to keep this project as simple as possible, so you can start with just the scaffolding we set up for you, and add additional things later when they become necessary. + +If you are not familiar with the different technologies used in this project, please refer to the respective docs. If you still are in the wind, please join our [Discord](https://t3.gg/discord) and ask for help. + +- [Next.js](https://nextjs.org) +- [NextAuth.js](https://next-auth.js.org) +- [Prisma](https://prisma.io) +- [Tailwind CSS](https://tailwindcss.com) +- [tRPC](https://trpc.io) + +## Learn More + +To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources: + +- [Documentation](https://create.t3.gg/) +- [Learn the T3 Stack](https://create.t3.gg/en/faq#what-learning-resources-are-currently-available) — Check out these awesome tutorials + +You can check out the [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome! + +## How do I deploy this? + +Follow our deployment guides for [Vercel](https://create.t3.gg/en/deployment/vercel), [Netlify](https://create.t3.gg/en/deployment/netlify) and [Docker](https://create.t3.gg/en/deployment/docker) for more information. diff --git a/apps/public/components.json b/apps/public/components.json new file mode 100644 index 00000000..9750ef2a --- /dev/null +++ b/apps/public/components.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "default", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "tailwind.config.ts", + "css": "src/styles/globals.css", + "baseColor": "slate", + "cssVariables": true + }, + "aliases": { + "components": "@/components", + "utils": "@/utils/cn" + } +} diff --git a/apps/public/next.config.mjs b/apps/public/next.config.mjs new file mode 100644 index 00000000..6c2cd5a9 --- /dev/null +++ b/apps/public/next.config.mjs @@ -0,0 +1,28 @@ +/** + * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially useful + * for Docker builds. + */ +await import('./src/env.mjs'); + +/** @type {import("next").NextConfig} */ +const config = { + reactStrictMode: true, + transpilePackages: ['@openpanel/queue'], + eslint: { ignoreDuringBuilds: true }, + typescript: { ignoreBuildErrors: true }, + experimental: { + // Avoid "Critical dependency: the request of a dependency is an expression" + serverComponentsExternalPackages: ['bullmq'], + }, + /** + * If you are using `appDir` then you must comment the below `i18n` config out. + * + * @see https://github.com/vercel/next.js/issues/41980 + */ + i18n: { + locales: ['en'], + defaultLocale: 'en', + }, +}; + +export default config; diff --git a/apps/web/package.json b/apps/public/package.json similarity index 51% rename from apps/web/package.json rename to apps/public/package.json index 14a797af..ee88b426 100644 --- a/apps/web/package.json +++ b/apps/public/package.json @@ -1,21 +1,18 @@ { - "name": "@mixan/web", + "name": "@openpanel/public", "version": "0.1.0", "private": true, "scripts": { - "postinstall": "prisma generate", - "dev": "next dev", + "dev": "rm -rf .next && pnpm with-env next dev", "build": "next build", "start": "next start", "lint": "eslint .", "format": "prettier --write \"**/*.{tsx,mjs,ts,md,json}\"", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "with-env": "dotenv -e ../../.env -c --" }, "dependencies": { - "@hookform/resolvers": "^3.3.2", - "@mixan/types": "workspace:*", - "@next-auth/prisma-adapter": "^1.0.7", - "@prisma/client": "^5.1.1", + "@openpanel/db": "workspace:*", "@radix-ui/react-alert-dialog": "^1.0.5", "@radix-ui/react-aspect-ratio": "^1.0.3", "@radix-ui/react-avatar": "^1.0.4", @@ -28,51 +25,28 @@ "@radix-ui/react-slot": "^1.0.2", "@radix-ui/react-toast": "^1.1.5", "@radix-ui/react-tooltip": "^1.0.7", - "@reduxjs/toolkit": "^1.9.7", "@t3-oss/env-nextjs": "^0.7.0", - "@tanstack/react-query": "^4.32.6", - "@tanstack/react-table": "^8.10.7", - "@trpc/client": "^10.37.1", - "@trpc/next": "^10.37.1", - "@trpc/react-query": "^10.37.1", - "@trpc/server": "^10.37.1", - "bcrypt": "^5.1.1", "class-variance-authority": "^0.7.0", "clsx": "^2.0.0", - "cmdk": "^0.2.0", - "lodash.debounce": "^4.0.8", - "lottie-react": "^2.4.0", - "lucide-react": "^0.286.0", - "mitt": "^3.0.1", - "next": "13.4", - "next-auth": "^4.23.0", - "prisma-error-enum": "^0.1.3", - "ramda": "^0.29.1", - "random-animal-name": "^0.1.1", + "email-validator": "^2.0.4", + "embla-carousel-autoplay": "8.0.0-rc22", + "embla-carousel-react": "8.0.0-rc22", + "lucide-react": "^0.323.0", + "next": "~14.0.4", "react": "18.2.0", + "react-animate-height": "^3.2.3", "react-dom": "18.2.0", - "react-hook-form": "^7.47.0", - "react-in-viewport": "1.0.0-alpha.30", - "react-redux": "^8.1.3", - "react-responsive": "^9.0.2", "react-syntax-highlighter": "^15.5.0", - "react-virtualized-auto-sizer": "^1.0.20", - "recharts": "^2.8.0", - "slugify": "^1.6.6", - "superjson": "^1.13.1", "tailwind-merge": "^1.14.0", "tailwindcss-animate": "^1.0.7", - "usehooks-ts": "^2.9.1", "zod": "^3.22.4" }, "devDependencies": { - "@mixan/eslint-config": "workspace:*", - "@mixan/prettier-config": "workspace:*", - "@mixan/tsconfig": "workspace:*", - "@types/bcrypt": "^5.0.0", - "@types/lodash.debounce": "^4.0.9", + "@openpanel/eslint-config": "workspace:*", + "@openpanel/prettier-config": "workspace:*", + "@openpanel/tsconfig": "workspace:*", + "@tailwindcss/typography": "^0.5.10", "@types/node": "^18.16.0", - "@types/ramda": "^0.29.6", "@types/react": "^18.2.20", "@types/react-dom": "^18.2.7", "@types/react-syntax-highlighter": "^15.5.9", @@ -83,7 +57,6 @@ "postcss": "^8.4.27", "prettier": "^3.0.3", "prettier-plugin-tailwindcss": "^0.5.1", - "prisma": "^5.1.1", "tailwindcss": "^3.3.3", "typescript": "^5.2.2" }, @@ -93,10 +66,10 @@ "eslintConfig": { "root": true, "extends": [ - "@mixan/eslint-config/base", - "@mixan/eslint-config/nextjs", - "@mixan/eslint-config/react" + "@openpanel/eslint-config/base", + "@openpanel/eslint-config/react", + "@openpanel/eslint-config/nextjs" ] }, - "prettier": "@mixan/prettier-config" + "prettier": "@openpanel/prettier-config" } diff --git a/apps/public/postcss.config.cjs b/apps/public/postcss.config.cjs new file mode 100644 index 00000000..e305dd92 --- /dev/null +++ b/apps/public/postcss.config.cjs @@ -0,0 +1,8 @@ +const config = { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; + +module.exports = config; diff --git a/apps/public/public/demo-2/1.png b/apps/public/public/demo-2/1.png new file mode 100644 index 00000000..fdfec989 Binary files /dev/null and b/apps/public/public/demo-2/1.png differ diff --git a/apps/public/public/demo-2/2.png b/apps/public/public/demo-2/2.png new file mode 100644 index 00000000..ae691d9a Binary files /dev/null and b/apps/public/public/demo-2/2.png differ diff --git a/apps/public/public/demo-2/3.png b/apps/public/public/demo-2/3.png new file mode 100644 index 00000000..210f0332 Binary files /dev/null and b/apps/public/public/demo-2/3.png differ diff --git a/apps/public/public/demo-2/4.png b/apps/public/public/demo-2/4.png new file mode 100644 index 00000000..11a69cb3 Binary files /dev/null and b/apps/public/public/demo-2/4.png differ diff --git a/apps/public/public/demo-2/5.png b/apps/public/public/demo-2/5.png new file mode 100644 index 00000000..17356ab5 Binary files /dev/null and b/apps/public/public/demo-2/5.png differ diff --git a/apps/public/public/demo-2/6.png b/apps/public/public/demo-2/6.png new file mode 100644 index 00000000..e3d3a124 Binary files /dev/null and b/apps/public/public/demo-2/6.png differ diff --git a/apps/public/public/demo-2/7.png b/apps/public/public/demo-2/7.png new file mode 100644 index 00000000..3c08953d Binary files /dev/null and b/apps/public/public/demo-2/7.png differ diff --git a/apps/public/public/demo/bar-min.png b/apps/public/public/demo/bar-min.png new file mode 100644 index 00000000..9d723b55 Binary files /dev/null and b/apps/public/public/demo/bar-min.png differ diff --git a/apps/public/public/demo/events-min.png b/apps/public/public/demo/events-min.png new file mode 100644 index 00000000..cb36a7f7 Binary files /dev/null and b/apps/public/public/demo/events-min.png differ diff --git a/apps/public/public/demo/histogram-min.png b/apps/public/public/demo/histogram-min.png new file mode 100644 index 00000000..745612c5 Binary files /dev/null and b/apps/public/public/demo/histogram-min.png differ diff --git a/apps/public/public/demo/line-min.png b/apps/public/public/demo/line-min.png new file mode 100644 index 00000000..0256db75 Binary files /dev/null and b/apps/public/public/demo/line-min.png differ diff --git a/apps/public/public/demo/metrics-min.png b/apps/public/public/demo/metrics-min.png new file mode 100644 index 00000000..fbfe7455 Binary files /dev/null and b/apps/public/public/demo/metrics-min.png differ diff --git a/apps/public/public/demo/overview-min.png b/apps/public/public/demo/overview-min.png new file mode 100644 index 00000000..5f6d2612 Binary files /dev/null and b/apps/public/public/demo/overview-min.png differ diff --git a/apps/public/public/demo/overview-share-min.png b/apps/public/public/demo/overview-share-min.png new file mode 100644 index 00000000..3228c6b1 Binary files /dev/null and b/apps/public/public/demo/overview-share-min.png differ diff --git a/apps/public/public/demo/pie-min.png b/apps/public/public/demo/pie-min.png new file mode 100644 index 00000000..d28d0a61 Binary files /dev/null and b/apps/public/public/demo/pie-min.png differ diff --git a/apps/public/public/demo/worldmap-min.png b/apps/public/public/demo/worldmap-min.png new file mode 100644 index 00000000..90b412f4 Binary files /dev/null and b/apps/public/public/demo/worldmap-min.png differ diff --git a/apps/public/public/google30d28bbdbd56aa6e.html b/apps/public/public/google30d28bbdbd56aa6e.html new file mode 100644 index 00000000..7438696c --- /dev/null +++ b/apps/public/public/google30d28bbdbd56aa6e.html @@ -0,0 +1 @@ +google-site-verification: google30d28bbdbd56aa6e.html \ No newline at end of file diff --git a/apps/public/public/logo-white.png b/apps/public/public/logo-white.png new file mode 100644 index 00000000..27f53ef7 Binary files /dev/null and b/apps/public/public/logo-white.png differ diff --git a/apps/public/public/logo.svg b/apps/public/public/logo.svg new file mode 100644 index 00000000..e45d0d95 --- /dev/null +++ b/apps/public/public/logo.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/apps/public/public/ogimage.png b/apps/public/public/ogimage.png new file mode 100644 index 00000000..0f646d6d Binary files /dev/null and b/apps/public/public/ogimage.png differ diff --git a/apps/public/public/op.js b/apps/public/public/op.js new file mode 100644 index 00000000..fb92b806 --- /dev/null +++ b/apps/public/public/op.js @@ -0,0 +1,2 @@ +"use strict";(()=>{function w(s){return Promise.all(Object.entries(s).map(async([t,e])=>[t,await e??""])).then(t=>Object.fromEntries(t))}function P(s){let t={"Content-Type":"application/json"};return{headers:t,async fetch(e,i,n){let o=`${s}${e}`,u,m=await w(t);return new Promise(c=>{let h=r=>{clearTimeout(u),fetch(o,{headers:m,method:"POST",body:JSON.stringify(i??{}),keepalive:!0,...n??{}}).then(async a=>{if(a.status!==200&&a.status!==202)return f(r,c);let g=await a.text();if(!g)return c(null);c(g)}).catch(()=>f(r,c))};function f(r,a){if(r>1)return a(null);u=setTimeout(()=>{h(r+1)},Math.pow(2,r)*500)}h(0)})}}}var l=class{options;api;state={properties:{}};constructor(t){this.options=t,this.api=P(t.url),this.api.headers["openpanel-client-id"]=t.clientId,this.options.clientSecret&&(this.api.headers["openpanel-client-secret"]=this.options.clientSecret)}init(t){this.state.properties=t??{}}setUser(t){this.api.fetch("/profile",{profileId:this.getProfileId(),...t,properties:{...this.state.properties,...t.properties}})}increment(t,e){this.api.fetch("/profile/increment",{property:t,value:e,profileId:this.getProfileId()})}decrement(t,e){this.api.fetch("/profile/decrement",{property:t,value:e,profileId:this.getProfileId()})}event(t,e){this.api.fetch("/event",{name:t,properties:{...this.state.properties,...e??{}},timestamp:this.timestamp(),profileId:this.getProfileId()}).then(i=>{this.options.setProfileId&&i&&this.options.setProfileId(i)})}setGlobalProperties(t){this.state.properties={...this.state.properties,...t}}clear(){this.state.profileId=void 0,this.options.removeProfileId&&this.options.removeProfileId()}timestamp(){return new Date().toISOString()}getProfileId(){if(this.state.profileId)return this.state.profileId;this.options.getProfileId&&(this.state.profileId=this.options.getProfileId()||void 0)}};var d=class extends l{lastPath="";constructor(t){super(t),this.isServer()||(this.setGlobalProperties({referrer:document.referrer}),this.options.trackOutgoingLinks&&this.trackOutgoingLinks(),this.options.trackScreenViews&&this.trackScreenViews())}isServer(){return typeof document>"u"}trackOutgoingLinks(){this.isServer()||document.addEventListener("click",t=>{let e=t.target,i=e.closest("a");if(i&&e){let n=i.getAttribute("href");n?.startsWith("http")&&super.event("link_out",{href:n,text:i.innerText||i.getAttribute("title")||e.getAttribute("alt")||e.getAttribute("title")})}})}trackScreenViews(){if(this.isServer())return;let t=history.pushState;history.pushState=function(...n){let o=t.apply(this,n);return window.dispatchEvent(new Event("pushstate")),window.dispatchEvent(new Event("locationchange")),o};let e=history.replaceState;history.replaceState=function(...n){let o=e.apply(this,n);return window.dispatchEvent(new Event("replacestate")),window.dispatchEvent(new Event("locationchange")),o},window.addEventListener("popstate",()=>window.dispatchEvent(new Event("locationchange"))),this.options.hash?window.addEventListener("hashchange",()=>this.screenView()):window.addEventListener("locationchange",()=>this.screenView()),this.screenView()}screenView(t){if(this.isServer())return;let e=window.location.href;this.lastPath!==e&&(this.lastPath=e,super.event("screen_view",{...t??{},path:e,title:document.title}))}};var p=document.currentScript;p&&(window.openpanel=new d({url:p?.getAttribute("data-url"),clientId:p?.getAttribute("data-client-id"),trackOutgoingLinks:!!p?.getAttribute("data-track-outgoing-links"),trackScreenViews:!!p?.getAttribute("data-track-screen-views")}));})(); +//# sourceMappingURL=cdn.global.js.map \ No newline at end of file diff --git a/apps/public/public/react-native.svg b/apps/public/public/react-native.svg new file mode 100644 index 00000000..d4a571d1 --- /dev/null +++ b/apps/public/public/react-native.svg @@ -0,0 +1,2 @@ + +React icon \ No newline at end of file diff --git a/apps/public/src/app/api/waitlist/route.ts b/apps/public/src/app/api/waitlist/route.ts new file mode 100644 index 00000000..06fb0548 --- /dev/null +++ b/apps/public/src/app/api/waitlist/route.ts @@ -0,0 +1,26 @@ +import * as EmailValidator from 'email-validator'; +import { NextResponse } from 'next/server'; + +import { db } from '@openpanel/db'; + +export const dynamic = 'force-dynamic'; + +export async function POST(req: Request) { + const body = await req.json(); + + if (!body.email) { + return NextResponse.json({ error: 'Email is required' }, { status: 400 }); + } + + if (!EmailValidator.validate(body.email)) { + return NextResponse.json({ error: 'Email is not valid' }, { status: 400 }); + } + + await db.waitlist.create({ + data: { + email: body.email.toLowerCase(), + }, + }); + + return NextResponse.json(body); +} diff --git a/apps/public/src/app/blob.tsx b/apps/public/src/app/blob.tsx new file mode 100644 index 00000000..3b115ea2 --- /dev/null +++ b/apps/public/src/app/blob.tsx @@ -0,0 +1,74 @@ +import * as React from 'react'; +import type { SVGProps } from 'react'; + +export const Blob1 = (props: SVGProps) => ( + + + +); + +export const Blob2 = (props: SVGProps) => ( + + + +); + +export const Blob3 = (props: SVGProps) => ( + + + +); + +export const Blob4 = (props: SVGProps) => ( + + + +); + +export const Blob5 = (props: SVGProps) => ( + + + +); + +export const Blob6 = (props: SVGProps) => ( + + + +); + +export const Blob7 = (props: SVGProps) => ( + + + +); + +export const Blob8 = (props: SVGProps) => ( + + + +); + +export const Blob9 = (props: SVGProps) => ( + + + +); + +export const Blob10 = (props: SVGProps) => ( + + + +); + +export const Blob11 = (props: SVGProps) => ( + + + +); + +export const Blob12 = (props: SVGProps) => ( + + + +); diff --git a/apps/public/src/app/carousel.tsx b/apps/public/src/app/carousel.tsx new file mode 100644 index 00000000..630c8f9d --- /dev/null +++ b/apps/public/src/app/carousel.tsx @@ -0,0 +1,75 @@ +'use client'; + +import { + Carousel, + CarouselContent, + CarouselItem, + CarouselNext, + CarouselPrevious, +} from '@/components/ui/carousel'; +import Autoplay from 'embla-carousel-autoplay'; +import Image from 'next/image'; + +const images = [ + { + title: 'Beautiful overview, everything is clickable to get more details', + url: '/demo-2/1.png', + }, + { + title: 'Histogram, perfect for showing active users', + url: '/demo-2/2.png', + }, + { title: 'Make your overview public', url: '/demo-2/3.png' }, + { + title: 'See real time events from your users', + url: '/demo-2/4.png', + }, + { title: 'The classic line chart', url: '/demo-2/5.png' }, + { + title: 'Bar charts to see your most popular content', + url: '/demo-2/6.png', + }, + { title: 'Get nice metric cards with graphs', url: '/demo-2/7.png' }, +]; + +export function PreviewCarousel() { + return ( + + + {images.map((item) => ( + +
+
+ +
+
+
+ ))} +
+ + +
+ ); +} diff --git a/apps/public/src/app/copy.tsx b/apps/public/src/app/copy.tsx new file mode 100644 index 00000000..61274589 --- /dev/null +++ b/apps/public/src/app/copy.tsx @@ -0,0 +1,57 @@ +import { cn } from '@/utils/cn'; + +interface Props { + children: React.ReactNode; + className?: string; +} + +export function Lead({ children, className }: Props) { + return ( +

+ {children} +

+ ); +} + +export function Lead2({ children, className }: Props) { + return ( +

{children}

+ ); +} + +export function Paragraph({ children, className }: Props) { + return

{children}

; +} + +export function Heading1({ children, className }: Props) { + return ( +

+ {children} +

+ ); +} + +export function Heading2({ children, className }: Props) { + return ( +

+ {children} +

+ ); +} + +export function Heading3({ children, className }: Props) { + return ( +

+ {children} +

+ ); +} diff --git a/apps/public/src/app/favicon.ico b/apps/public/src/app/favicon.ico new file mode 100644 index 00000000..dd5ab726 Binary files /dev/null and b/apps/public/src/app/favicon.ico differ diff --git a/apps/public/src/app/footer.tsx b/apps/public/src/app/footer.tsx new file mode 100644 index 00000000..dd33682d --- /dev/null +++ b/apps/public/src/app/footer.tsx @@ -0,0 +1,62 @@ +import { Logo } from '@/components/Logo'; +import Image from 'next/image'; +import Link from 'next/link'; + +import { Heading2, Lead2 } from './copy'; +import { JoinWaitlist } from './join-waitlist'; + +export default function Footer() { + return ( +
+
+
+
+ Get early access + Ready to set your analytics free? Get on our waitlist. + +
+ +
+
+ +
+
+ +
+
+
+
+
+
+
+
+ +
+ + Terms and Conditions + + + Privacy Policy + + + Follow on X + +
+
+
+
+
+
+ ); +} diff --git a/apps/public/src/app/hero.tsx b/apps/public/src/app/hero.tsx new file mode 100644 index 00000000..337cf92e --- /dev/null +++ b/apps/public/src/app/hero.tsx @@ -0,0 +1,56 @@ +import Image from 'next/image'; + +import { PreviewCarousel } from './carousel'; +import { Heading1, Lead2 } from './copy'; +import { JoinWaitlistHero } from './join-waitlist-hero'; + +const avatars = [ + 'https://api.dicebear.com/7.x/adventurer/svg?seed=Chester&backgroundColor=b6e3f4', + 'https://api.dicebear.com/7.x/adventurer/svg?seed=Casper&backgroundColor=c0aede', + 'https://api.dicebear.com/7.x/adventurer/svg?seed=Boo&backgroundColor=ffdfbf', +]; + +export function Hero({ waitlistCount }: { waitlistCount: number }) { + return ( +
+ {/*
*/} +
+
+
+
+
+
+
+
+
+
+ + + An open-source +
+ alternative to Mixpanel +
+ + Mixpanel + Plausible = Openpanel!{' '} +
A simple analytics tool that your wallet can afford. +
+
+ +
+

+ {waitlistCount} people have already signed up! 🚀 +

+
+
+
+ + +
+ ); +} diff --git a/apps/public/src/app/join-waitlist-hero.tsx b/apps/public/src/app/join-waitlist-hero.tsx new file mode 100644 index 00000000..e5c68232 --- /dev/null +++ b/apps/public/src/app/join-waitlist-hero.tsx @@ -0,0 +1,128 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { cn } from '@/utils/cn'; +import Link from 'next/link'; + +interface JoinWaitlistProps { + className?: string; +} + +export function JoinWaitlistHero({ className }: JoinWaitlistProps) { + const [value, setValue] = useState(''); + const [open, setOpen] = useState(false); + const [success, setSuccess] = useState(false); + + useEffect(() => { + if (open) { + // @ts-ignore + window.openpanel.event('waitlist_open'); + } + }, [open]); + + useEffect(() => { + if (success) { + // @ts-ignore + window.openpanel.event('waitlist_success', { + email: value, + }); + } + }, [success]); + + const renderSuccess = () => ( + + + Thanks so much! + + You're now on the waiting list. We'll let you know when we're ready. + Should be within a month or two 🚀 + + + + + + + + ); + + const renderForm = () => ( + + + Almost there! + + Enter your email to join the waiting list. We'll let you know when + we're ready. + + + +
{ + e.preventDefault(); + fetch('/api/waitlist', { + method: 'POST', + body: JSON.stringify({ email: value }), + headers: { + 'Content-Type': 'application/json', + }, + }).then((res) => { + if (res.ok) { + setSuccess(true); + } + }); + }} + > +
+ setValue(e.target.value)} + /> + +
+ +
+ ); + + return ( + <> + + {success ? renderSuccess() : renderForm()} + +
+ + + + +
+ + ); +} diff --git a/apps/public/src/app/join-waitlist.tsx b/apps/public/src/app/join-waitlist.tsx new file mode 100644 index 00000000..9efc7e7e --- /dev/null +++ b/apps/public/src/app/join-waitlist.tsx @@ -0,0 +1,81 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { cn } from '@/utils/cn'; + +interface JoinWaitlistProps { + className?: string; +} + +export function JoinWaitlist({ className }: JoinWaitlistProps) { + const [value, setValue] = useState(''); + const [open, setOpen] = useState(false); + + useEffect(() => { + if (open) { + // @ts-ignore + window.openpanel.event('waitlist_success'); + } + }, [open]); + + return ( + <> + + + + Thanks so much! + + You're now on the waiting list. We'll let you know when we're + ready. Should be within a month or two 🚀 + + + + + + + + +
{ + e.preventDefault(); + fetch('/api/waitlist', { + method: 'POST', + body: JSON.stringify({ email: value }), + headers: { + 'Content-Type': 'application/json', + }, + }).then((res) => { + if (res.ok) { + setOpen(true); + } + }); + }} + > +
+ setValue(e.target.value)} + /> + +
+ + + ); +} diff --git a/apps/public/src/app/layout.tsx b/apps/public/src/app/layout.tsx new file mode 100644 index 00000000..c802af60 --- /dev/null +++ b/apps/public/src/app/layout.tsx @@ -0,0 +1,61 @@ +import { cn } from '@/utils/cn'; + +import '@/styles/globals.css'; + +import type { Metadata } from 'next'; +import { Bricolage_Grotesque } from 'next/font/google'; +import Script from 'next/script'; + +import Footer from './footer'; +import { defaultMeta } from './meta'; + +export const metadata: Metadata = { + ...defaultMeta, + alternates: { + canonical: 'https://openpanel.dev', + }, +}; + +const font = Bricolage_Grotesque({ + display: 'swap', + subsets: ['latin'], + weight: ['400', '700'], +}); + +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( + + +
+
{children}
+
+ +